text
stringlengths
957
885k
import tensorflow as tf import numpy as np import threading import time batch_size =32 flag = False class CustomRunner(object): """ This class manages the the background threads needed to fill a queue full of data. """ def __init__(self): #self.data_iterator = data self.n_threads = 2 self.dataX = tf.placeholder(dtype=tf.float32, shape=[None, 10]) self.dataY = tf.placeholder(dtype=tf.int64, shape=[None, ]) # The actual queue of data. The queue contains a vector for # the mnist features, and a scalar label. self.queue = tf.RandomShuffleQueue(shapes=[[10], []], dtypes=[tf.float32, tf.int64], capacity=100, min_after_dequeue=0) # The symbolic operation to add data to the queue # we could do some preprocessing here or do it in numpy. In this example # we do the scaling in numpy self.enqueue_op = self.queue.enqueue_many([self.dataX, self.dataY]) #self.qr = tf.train.QueueRunner(self.queue, [self.enqueue_op] * 4) def data_iterator(self, n): #global flag # while True: print('===============TRAIN==========') total_samples = 1024 samples_per_thread = total_samples//self.n_threads start = n*samples_per_thread for idx in range(start, start + samples_per_thread, batch_size): feats = np.random.randn(batch_size, 10) labels = np.random.randint(0, 2, batch_size) yield feats, labels return def data_iterator2(self, n): #global flag # while True: print('===============VAL==========') total_samples = 1024 samples_per_thread = total_samples//self.n_threads start = n*samples_per_thread for idx in range(start, start + samples_per_thread, batch_size): feats = np.ones((batch_size, 10)) labels = np.random.randint(0, 2, batch_size) yield feats, labels return def get_inputs(self): """ Return's tensors containing a batch of images and labels """ images_batch, labels_batch = self.queue.dequeue_many(batch_size) return images_batch, labels_batch def thread_main(self, sess, coord, n, samples='train'): """ Function run on alternate thread. Basically, keep adding data to the queue. """ if samples == 'train': fn = self.data_iterator elif samples == 'val': fn = self.data_iterator2 for dataX, dataY in fn(n): sess.run(self.enqueue_op, feed_dict={self.dataX:dataX, self.dataY:dataY}) #exit() #coord.request_stop() #Non-deterministic, can make other threads stop early #sess.run(self.queue.close(cancel_pending_enqueues=False)) def start_threads(self, sess, coord, samples): """ Start background threads to feed queue """ threads = [] for n in range(self.n_threads): t = threading.Thread(target=self.thread_main, args=(sess, coord, n, samples)) t.daemon = True # thread will close when parent quits t.start() threads.append(t) return threads #Doing anything with data on the CPU is generally a good idea. with tf.device("/cpu:0"): custom_runner = CustomRunner() images_batch, labels_batch = custom_runner.get_inputs() # simple model w = tf.get_variable("w1", [10, 2]) y_pred = tf.matmul(images_batch, w) sum = tf.reduce_sum(images_batch) loss = tf.nn.sparse_softmax_cross_entropy_with_logits(y_pred, labels_batch) # for monitoring loss_mean = tf.reduce_mean(loss) train_op = tf.train.AdamOptimizer().minimize(loss) sess = tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=8)) init = tf.initialize_all_variables() sess.run(init) def step(samples): coord = tf.train.Coordinator() # start the tensorflow QueueRunner's #threads1 = tf.train.start_queue_runners(sess=sess, coord=coord) # start our custom queue runner's threads threads = custom_runner.start_threads(sess, coord, samples=samples) print "%d Threads started"%len(threads) ctr = 0 #One epoch try: while True : _, sum_val, loss_val = sess.run([train_op, sum, loss_mean]) print "ctr %d : "%ctr, loss_val, sum_val, sess.run(custom_runner.queue.size()), threading.activeCount() ctr += 1 #if coord.should_stop() and sess.run(custom_runner.queue.size()) == 0: break if threading.active_count() == 1 and sess.run(custom_runner.queue.size()) == 0: break except Exception, e: print('catched exception: ', e) coord.request_stop(e) #finally: #coord.request_stop() #coord.join(threads) start = time.time() for i in range(3): step('val') print("==================", i) step('val') print time.time()-start
import json import numpy as np import os import requests import sys from bs4 import BeautifulSoup from settings import DATA_DIR AUTOCOMPLETE_URL = 'http://www.fipiran.com/DataService/AutoCompleteindex' EXPORT_URL = 'http://www.fipiran.com/DataService/Exportindex' START_DATE = 13980101 # YYYYMMDD Solar Hijri calendar END_DATE = 13990101 # YYYYMMDD Solar Hijri calendar class IranStock: def __init__(self): self._instrument_id_to_node_index = {} self._instrument_ids = [] self._names = [] self._date_to_time_frame_index = {} self._dates = [] self.raw_data = None self._get_raw_data() self._fill_raw_data_empty_entries() self._delete_static_columns() @staticmethod def _get_stock_indices(): all_instrument_ids = [] all_names = [] cached_path = os.path.join(DATA_DIR, 'iran_stock_indices.json') if os.path.exists(cached_path): with open(cached_path, 'r') as cached_file: response_json = json.loads(cached_file.read()) else: response = requests.post(AUTOCOMPLETE_URL, data={ 'id': '', }) if response.status_code == 200: with open(cached_path, 'w') as cached_file: cached_file.write(response.text) response_json = json.loads(response.text) else: response_json = [] for item in response_json: name = item['LVal30'] if name[0].isdigit(): instrument_id = item['InstrumentID'] all_instrument_ids.append(instrument_id) all_names.append(name) return all_instrument_ids, all_names def _get_raw_data(self): dates = set() entries = [] all_instrument_ids, all_names = self._get_stock_indices() node_counter = 0 for i, instrument_id in enumerate(all_instrument_ids): # progress bar sys.stdout.write('\rExcel Files [%d/%d]' % (i + 1, len(all_instrument_ids))) sys.stdout.flush() cached_path = os.path.join(DATA_DIR, instrument_id) if os.path.exists(cached_path): with open(cached_path, 'r') as cached_file: response_text = cached_file.read() else: response = requests.post(EXPORT_URL, data={ 'inscodeindex': instrument_id, 'indexStart': START_DATE, 'indexEnd': END_DATE, }) response_text = response.text with open(cached_path, 'w') as cached_file: cached_file.write(response_text) soup = BeautifulSoup(response_text, features='html.parser') table = soup.find('table') if table: for row in table.findAll('tr'): if row: columns = row.findAll('td') if columns: date = columns[1].string.strip() dates.add(date) amount = columns[2].string.strip() entries.append((date, instrument_id, amount)) self._instrument_ids.append(instrument_id) self._instrument_id_to_node_index[instrument_id] = node_counter node_counter += 1 self._names.append(all_names[i]) print() # newline self._dates = sorted(dates) for i, date in enumerate(self._dates): self._date_to_time_frame_index[date] = i self.raw_data = np.zeros((len(self._dates), len(self._instrument_ids))) for entry in entries: date = entry[0] time_frame_index = self._date_to_time_frame_index[date] instrument_id = entry[1] node_index = self._instrument_id_to_node_index[instrument_id] amount = entry[2] self.raw_data[time_frame_index, node_index] = amount def _fill_raw_data_empty_entries(self): for column_index in range(self.raw_data.shape[1]): previous_value = 0 for row_index in range(self.raw_data.shape[0]): if not self.raw_data[row_index, column_index]: self.raw_data[row_index, column_index] = previous_value else: previous_value = self.raw_data[row_index, column_index] @staticmethod def _subtract(x): normalized_columns = [] for column_index in range(x.shape[1]): column = x[:, column_index] normalized_column = column - column[0] normalized_columns.append(normalized_column) normalized_x = np.column_stack(normalized_columns) return normalized_x def _delete_static_columns(self): normalized_x = self._subtract(self.raw_data) mask = (normalized_x == 0).all(0) column_indices = np.where(mask)[0] new_names = [] new_instrument_ids = [] for i in range(len(self._names)): name = self._names[i] instrument_id = self._instrument_ids[i] if i not in column_indices: new_names.append(name) new_instrument_ids.append(instrument_id) self.raw_data = self.raw_data[:, ~mask] if __name__ == '__main__': iran_stock = IranStock() print(iran_stock.raw_data.shape) print(iran_stock.raw_data)
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'style_image.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_StyleImg(object): def setupUi(self, StyleImg): StyleImg.setObjectName("StyleImg") StyleImg.resize(386, 593) self.horizontalLayout = QtWidgets.QHBoxLayout(StyleImg) self.horizontalLayout.setObjectName("horizontalLayout") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.gridLayout_2 = QtWidgets.QGridLayout() self.gridLayout_2.setSpacing(0) self.gridLayout_2.setObjectName("gridLayout_2") self.label_10 = QtWidgets.QLabel(StyleImg) self.label_10.setObjectName("label_10") self.gridLayout_2.addWidget(self.label_10, 3, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_11 = QtWidgets.QLabel(StyleImg) self.label_11.setStyleSheet("QLabel{\n" "image: url(:/style/style_image/oil_crop.jpg);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_11.setText("") self.label_11.setObjectName("label_11") self.gridLayout_2.addWidget(self.label_11, 2, 2, 1, 1) self.label = QtWidgets.QLabel(StyleImg) self.label.setStyleSheet("QLabel{\n" " image: url(:/style/style_image/matisse_crop.jpg);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label.setText("") self.label.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter) self.label.setObjectName("label") self.gridLayout_2.addWidget(self.label, 2, 1, 1, 1) self.label_12 = QtWidgets.QLabel(StyleImg) self.label_12.setObjectName("label_12") self.gridLayout_2.addWidget(self.label_12, 3, 2, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_2 = QtWidgets.QLabel(StyleImg) self.label_2.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_2.setObjectName("label_2") self.gridLayout_2.addWidget(self.label_2, 3, 1, 1, 1) self.label_13 = QtWidgets.QLabel(StyleImg) self.label_13.setStyleSheet("QLabel{\n" "image: url(:/style/style_image/oily_mcoilface.jpg);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_13.setText("") self.label_13.setObjectName("label_13") self.gridLayout_2.addWidget(self.label_13, 4, 0, 1, 1) self.label_18 = QtWidgets.QLabel(StyleImg) self.label_18.setObjectName("label_18") self.gridLayout_2.addWidget(self.label_18, 5, 2, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_14 = QtWidgets.QLabel(StyleImg) self.label_14.setStyleSheet("QLabel{\n" "image: url(:/style/style_image/okeffe.jpg);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_14.setText("") self.label_14.setObjectName("label_14") self.gridLayout_2.addWidget(self.label_14, 4, 1, 1, 1) self.label_15 = QtWidgets.QLabel(StyleImg) self.label_15.setStyleSheet("QLabel{\n" "image: url(:/style/style_image/okeffe_iris.png);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_15.setText("") self.label_15.setObjectName("label_15") self.gridLayout_2.addWidget(self.label_15, 4, 2, 1, 1) self.label_19 = QtWidgets.QLabel(StyleImg) self.label_19.setStyleSheet("QLabel{\n" "image: url(:/style/style_image/water_lilies_crop.jpg);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_19.setText("") self.label_19.setObjectName("label_19") self.gridLayout_2.addWidget(self.label_19, 6, 0, 1, 1) self.label_24 = QtWidgets.QLabel(StyleImg) self.label_24.setText("") self.label_24.setObjectName("label_24") self.gridLayout_2.addWidget(self.label_24, 7, 2, 1, 1) self.label_17 = QtWidgets.QLabel(StyleImg) self.label_17.setObjectName("label_17") self.gridLayout_2.addWidget(self.label_17, 5, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_23 = QtWidgets.QLabel(StyleImg) self.label_23.setObjectName("label_23") self.gridLayout_2.addWidget(self.label_23, 7, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_21 = QtWidgets.QLabel(StyleImg) self.label_21.setText("") self.label_21.setObjectName("label_21") self.gridLayout_2.addWidget(self.label_21, 6, 2, 1, 1) self.label_16 = QtWidgets.QLabel(StyleImg) self.label_16.setObjectName("label_16") self.gridLayout_2.addWidget(self.label_16, 5, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_20 = QtWidgets.QLabel(StyleImg) self.label_20.setStyleSheet("QLabel{\n" "image: url(:/style/style_image/wave_crop.jpg);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_20.setText("") self.label_20.setObjectName("label_20") self.gridLayout_2.addWidget(self.label_20, 6, 1, 1, 1) self.label_22 = QtWidgets.QLabel(StyleImg) self.label_22.setObjectName("label_22") self.gridLayout_2.addWidget(self.label_22, 7, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_9 = QtWidgets.QLabel(StyleImg) self.label_9.setStyleSheet("QLabel{;\n" "image: url(:/style/style_image/kandinsky_crop.jpg);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_9.setText("") self.label_9.setObjectName("label_9") self.gridLayout_2.addWidget(self.label_9, 2, 0, 1, 1) self.label_3 = QtWidgets.QLabel(StyleImg) self.label_3.setStyleSheet("QLabel{;\n" "image: url(:/style/style_image/ben_giles.png);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_3.setText("") self.label_3.setObjectName("label_3") self.gridLayout_2.addWidget(self.label_3, 0, 0, 1, 1) self.label_5 = QtWidgets.QLabel(StyleImg) self.label_5.setObjectName("label_5") self.gridLayout_2.addWidget(self.label_5, 1, 1, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_7 = QtWidgets.QLabel(StyleImg) self.label_7.setStyleSheet("QLabel{;\n" "image: url(:/style/style_image/dark_matter_bw.png);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_7.setText("") self.label_7.setObjectName("label_7") self.gridLayout_2.addWidget(self.label_7, 0, 1, 1, 1) self.label_8 = QtWidgets.QLabel(StyleImg) self.label_8.setStyleSheet("QLabel{;\n" "image: url(:/style/style_image/flowers_crop.jpg);\n" "border:1px solid;\n" " border-color: rgba(255, 255, 255,0);\n" "}\n" "QLabel:hover{border:2px solid;\n" "border-color:\"blue\"}") self.label_8.setText("") self.label_8.setObjectName("label_8") self.gridLayout_2.addWidget(self.label_8, 0, 2, 1, 1) self.label_4 = QtWidgets.QLabel(StyleImg) self.label_4.setObjectName("label_4") self.gridLayout_2.addWidget(self.label_4, 1, 0, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label_6 = QtWidgets.QLabel(StyleImg) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label_6.sizePolicy().hasHeightForWidth()) self.label_6.setSizePolicy(sizePolicy) self.label_6.setMaximumSize(QtCore.QSize(200, 50)) self.label_6.setObjectName("label_6") self.gridLayout_2.addWidget(self.label_6, 1, 2, 1, 1, QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.gridLayout_2.setRowStretch(0, 10) self.gridLayout_2.setRowStretch(1, 2) self.gridLayout_2.setRowStretch(2, 10) self.gridLayout_2.setRowStretch(3, 2) self.gridLayout_2.setRowStretch(4, 10) self.gridLayout_2.setRowStretch(5, 2) self.gridLayout_2.setRowStretch(6, 10) self.gridLayout_2.setRowStretch(7, 2) self.verticalLayout.addLayout(self.gridLayout_2) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setContentsMargins(-1, 10, -1, -1) self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.lineEdit = QtWidgets.QLineEdit(StyleImg) self.lineEdit.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n" "border:None;") self.lineEdit.setReadOnly(True) self.lineEdit.setObjectName("lineEdit") self.horizontalLayout_3.addWidget(self.lineEdit) self.verticalLayout.addLayout(self.horizontalLayout_3) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setContentsMargins(-1, 10, -1, -1) self.horizontalLayout_2.setObjectName("horizontalLayout_2") spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem) self.pushButton_2 = QtWidgets.QPushButton(StyleImg) self.pushButton_2.setObjectName("pushButton_2") self.horizontalLayout_2.addWidget(self.pushButton_2) self.pushButton = QtWidgets.QPushButton(StyleImg) self.pushButton.setObjectName("pushButton") self.horizontalLayout_2.addWidget(self.pushButton) self.verticalLayout.addLayout(self.horizontalLayout_2) self.horizontalLayout.addLayout(self.verticalLayout) self.retranslateUi(StyleImg) self.pushButton_2.clicked.connect(StyleImg.accept) self.pushButton.clicked.connect(StyleImg.reject) QtCore.QMetaObject.connectSlotsByName(StyleImg) def retranslateUi(self, StyleImg): _translate = QtCore.QCoreApplication.translate StyleImg.setWindowTitle(_translate("StyleImg", "Dialog")) self.label_10.setText(_translate("StyleImg", "kandinsky_crop")) self.label_12.setText(_translate("StyleImg", "oil_crop")) self.label_2.setText(_translate("StyleImg", "matisse_crop")) self.label_18.setText(_translate("StyleImg", "okeffe_iris")) self.label_17.setText(_translate("StyleImg", "okeffe")) self.label_23.setText(_translate("StyleImg", "wave_crop")) self.label_16.setText(_translate("StyleImg", "oily_mcoilface")) self.label_22.setText(_translate("StyleImg", "water_lilies_crop")) self.label_5.setText(_translate("StyleImg", "dark_matter_bw")) self.label_4.setText(_translate("StyleImg", "ben_giles")) self.label_6.setText(_translate("StyleImg", "flowers_crop")) self.lineEdit.setText(_translate("StyleImg", "Note:you can select four imgs at most.")) self.pushButton_2.setText(_translate("StyleImg", "OK")) self.pushButton.setText(_translate("StyleImg", "CANCEL")) import picture_rc
"""The BERT-based triple clustering mechanism.""" from typing import List, Dict, Tuple import numpy as np import torch from sklearn.cluster import AgglomerativeClustering from sklearn.metrics.pairwise import cosine_similarity from transformers import RobertaTokenizer, RobertaForSequenceClassification from triple_clustering.simple_assertion import SimpleAssertion class TripleClusteringFactory(object): """Class for BERT-based clustering factory.""" def __init__(self, model_path: str, device, distance_threshold: float, batch_size: int, top_n: int = 5): super().__init__() self.tokenizer = RobertaTokenizer.from_pretrained(model_path) self.model = RobertaForSequenceClassification.from_pretrained(model_path) self.device = device self.model.eval() if self.device != "cpu": self.model.to(self.device) self.distance_threshold = distance_threshold self.batch_size = batch_size self.top_n = top_n def cluster(self, assertion_list: List[SimpleAssertion]) -> List[List[SimpleAssertion]]: """Group assertions of identical meaning into same groups.""" # grouping assertions having same lower-cased form triple2duplicate_list = self.group_same_triples(assertion_list) if len(triple2duplicate_list) == 1: return [assertion_list] # list of distinct triples distinct_triple_list = [triple for triple, _ in sorted(triple2duplicate_list.items(), key=lambda x: ( -len(x[1]), len(x[0].get_triple_str()), x[0].pred, x[0].obj) ) ] # indexes of triple pairs to be processed to_be_processed_index_list = self.get_list_of_triple_pairs_to_be_processed(distinct_triple_list) # convert assertions to BERT-like sentences to_be_processed_sentence_list = [ (self.prepare(distinct_triple_list[idx[0]]), self.prepare(distinct_triple_list[idx[1]])) for idx in to_be_processed_index_list] # compute BERT scores bert_scores = self.compute_bert_based_dissimilarity(to_be_processed_sentence_list) # building distance matrix distance_matrix = np.ones((len(distinct_triple_list), len(distinct_triple_list))) for idx, pair in enumerate(to_be_processed_index_list): score = bert_scores[idx] i, j = pair distance_matrix[i][j] = score distance_matrix[j][i] = score # special cases for i in range(distance_matrix.shape[0]): distance_matrix[i][i] = 0.0 object_i = distinct_triple_list[i].get_simplified_object() for j in range(i + 1, distance_matrix.shape[1]): if distinct_triple_list[j].pred != distinct_triple_list[i].pred: continue object_j = distinct_triple_list[j].get_simplified_object() if object_i == object_j: distance_matrix[i][j] = 0.0 distance_matrix[j][i] = 0.0 # hierarchical clustering clustering = AgglomerativeClustering(n_clusters=None, affinity="precomputed", distance_threshold=self.distance_threshold, compute_full_tree=True, linkage="single") clustering.fit(distance_matrix) labels = clustering.labels_ np_distinct_triple_array = np.array(distinct_triple_list) clusters = [] for label in range(np.max(labels) + 1): cluster = [a for a in np_distinct_triple_array[labels == label]] alias = [] for a in cluster: alias.extend(triple2duplicate_list[a]) cluster.extend(alias) clusters.append(cluster) return clusters @staticmethod def prepare(assertion: SimpleAssertion) -> str: """Prepare BERT-based input sentence.""" return ' '.join(['[subj]', assertion.pred, '[u-sep]', assertion.obj]) @staticmethod def group_same_triples(assertion_list: List[SimpleAssertion]) -> Dict[SimpleAssertion, List[SimpleAssertion]]: """Triples having same utterances are grouped together.""" triple2duplicate_list = {} for assertion in assertion_list: if assertion in triple2duplicate_list: triple2duplicate_list[assertion].append(assertion) else: triple2duplicate_list[assertion] = [] return triple2duplicate_list def compute_bert_based_dissimilarity(self, pairs: List[Tuple[str, str]]) -> List[float]: """Distance between two triples is the p_0 probability obtained by the BERT-based classification model.""" forward_probs = [] with torch.no_grad(): for i in range(0, len(pairs), self.batch_size): batch = pairs[i:(i + self.batch_size)] input_batch = self.tokenizer.batch_encode_plus( batch, return_tensors="pt", padding="max_length", truncation="longest_first", max_length=32, return_token_type_ids=True ) if self.device != "cpu": for k in input_batch: input_batch[k] = input_batch[k].to(self.device) logits = self.model(**input_batch)[0] batch_probs = torch.softmax(logits, dim=1).tolist() # probabilities of being not paraphrase = distance between 2 triples batch_probs = [p[0] for p in batch_probs] forward_probs.extend(batch_probs) return forward_probs def get_list_of_triple_pairs_to_be_processed(self, triple_list: List[SimpleAssertion]) -> List[Tuple[int, int]]: """Tricks to lower the search space for each triple, using pure word2vec.""" # vector for (predicate + object) similarity_matrix = compute_word2vec_similarity_matrix(triple_list, includes_predicate=True) # vector for object only, stop words and punctuations discarded object_similarity_matrix = compute_word2vec_similarity_matrix(triple_list, includes_predicate=False) # sort by decreasing similarity ind = np.argsort(-similarity_matrix, axis=1) obj_ind = np.argsort(-object_similarity_matrix, axis=1) # extract top similar triples for each row pairs = [] for i in range(ind.shape[0]): local_ind_pairs = set() local_obj_ind_pairs = set() for j in range(ind.shape[1]): # top pairs using (predicate + object) vector if ind[i][j] > i and len(local_ind_pairs) < self.top_n: local_ind_pairs.add((i, ind[i][j])) # top pairs using only object vector if obj_ind[i][j] > i and len(local_obj_ind_pairs) < self.top_n: local_obj_ind_pairs.add((i, obj_ind[i][j])) if len(local_ind_pairs) >= self.top_n and len(local_obj_ind_pairs) >= self.top_n: break same_head_word_pairs = set() head_word_i = triple_list[i].get_obj_head_word() for j in range(i + 1, ind.shape[0]): # same head words head_word_j = triple_list[j].get_obj_head_word() if head_word_i == head_word_j and len(same_head_word_pairs) < self.top_n: same_head_word_pairs.add((i, j)) if len(same_head_word_pairs) >= self.top_n: break # unite pair sets pairs.extend( local_ind_pairs.union(local_obj_ind_pairs).union(same_head_word_pairs)) # filter antonyms to_be_removed = set() for ind, (i, j) in enumerate(pairs): obj1 = triple_list[i].obj obj2 = triple_list[j].obj shorter = obj1 if len(obj1) < len(obj2) else obj2 longer = obj1 if len(obj1) > len(obj2) else obj2 if longer in {"in" + shorter, "un" + shorter, "ir" + shorter}: to_be_removed.add(ind) pairs = [pair for ind, pair in enumerate(pairs) if ind not in to_be_removed] return pairs def compute_word2vec_similarity_matrix(triple_list, includes_predicate=True) -> np.ndarray: """Fast computation for vector-vector cosine similarity.""" if not includes_predicate: matrix = np.array([triple.get_object_vector() for triple in triple_list]) else: matrix = np.array([triple.get_vector() for triple in triple_list]) return cosine_similarity(matrix)
#! /usr/bin/python #-*- coding: utf-8 -*- from __future__ import print_function import sys import os import argparse import datetime from shutil import copyfileobj from pybern.products.downloaders.retrieve import http_retrieve from pybern.products.fileutils.keyholders import parse_key_file ## https://vmf.geo.tuwien.ac.at/trop_products/GRID/2.5x2/VMF1/VMF1_OP/2021/ TUW_URL = 'https://vmf.geo.tuwien.ac.at' OP_URL_DIR = '/trop_products/GRID/2.5x2/VMF1/VMF1_OP' FC_URL_DIR = '/trop_products/GRID/2.5x2/VMF1/VMF1_FC' def downloading_complete(dct,flag=None): """ Utility function: check if all files in the dictionary have been successefully downloaded. You can se the flag to: * 'op' to only check for final products (forecast are ignored) * 'fc' to only check for forecast products (final are ignored) * None to either check final or forecast, i.e. a file is considered successefully downloaded in either case """ if not flag: all([dct[x]['fc'] or dct[x]['op'] for x in dct]) elif flag == 'fc': return all([dct[x]['fc'] for x in dct]) elif flag=='op': return all([dct[x]['op'] for x in dct]) else: raise RuntimeError('[ERROR] Invalid argument to downloading_complete function!') def remove_local(dct): """ Utility function: remove files specified in the dct, which has the form: {...'VMFG_YYYYMMDD.H00':{'op':0/1, 'fc':0/1, 'fn':foo}...} For every entr, try to remove the 'fn' value if any of 'op', 'fc' is not zero. For more info on the passed in dictionary, see the main code. """ for key, idct in dct.items(): if idct['op'] or idct['fc']: try: os.remove(idct['fn']) except: pass def get_credentials_from_args(arg_dict): """ Iterate through command line arguments to find the credentials needed to access the forecast vmf grid files. First see if we have a config file and parse from there the credentials. Then check to see if we have username/password cmd options and resolve them. Note! some cmd options have a default value of None; guard against this. """ if 'config_file' in arg_dict and arg_dict['config_file']: d = parse_key_file(arg_dict['config_file']); username = d['TUWIEN_VMF1_USER'] if 'TUWIEN_VMF1_USER' in d else None password = d['<PASSWORD>'] if 'TUWIEN_VMF1_PASS' in d else None if 'username' in arg_dict and arg_dict['username']: username = arg_dict['username'] if 'password' in arg_dict and arg_dict['password']: password = arg_dict['password'] try: assert(username != None) assert(password != None) except: raise RuntimeError('[ERROR] Could not resolve credentials for forecast grid file access') return username, password def final_dir(dt): return '{:}/{:}/{:4d}'.format(TUW_URL, OP_URL_DIR, dt.year) def forecast_dir(dt): return '{:}/{:}/{:4d}'.format(TUW_URL, FC_URL_DIR, dt.year) def decompose_grid_fn(fn): """ Decompose a VMF1 grid file to a Python datetime instance. Generic format of grid files is: VMFG_YYYYMMDD.H00. Return the corresponding datetime from YYYY, MM, DD and hour. """ fn = os.path.basename(fn) m = re.match(r'VMFG_([0-9]{8})\.H([0-9]{2})$', fn) if not m: print('[ERROR] Invalid vmf1 grid filename', file=sys.stderr) raise RuntimeError('[ERROR] Invalid vmf1 grid filename') return datetime.datetime.strptime( '{:} {:}:00:00'.format(g.group(1), m.group(2)), '%Y%m%d %H:%M:%S') ## If only the formatter_class could be: ##+ argparse.RawTextHelpFormatter|ArgumentDefaultsHelpFormatter .... ## Seems to work with multiple inheritance! class myFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter): pass parser = argparse.ArgumentParser( formatter_class=myFormatter, description= 'Download VMF1 grid files from https://vmf.geo.tuwien.ac.at/trop_products/GRID/2.5x2/VMF1/\nThe script allows downloading of both final and forecast grid files but note that for the later you will need credentials. The program will return an exit status of zero on a successeful run, else it will return a positive integer (>0).\nReference: re3data.org: VMF Data Server; editing status 2020-12-14; re3data.org - Registry of Research Data Repositories. http://doi.org/10.17616/R3RD2H', epilog=('''National Technical University of Athens, Dionysos Satellite Observatory\n Send bug reports to: <NAME>, <EMAIL> <NAME>,<EMAIL> March, 2021''')) parser.add_argument('-y', '--year', metavar='YEAR', dest='year', type=int, required=True, help='The year of date.') parser.add_argument('-d', '--doy', metavar='DOY', dest='doy', type=int, required=True, help='The day-of-year (doy) of date.') ## hour of day parser.add_argument('--hour', action='store', required=False, type=int, help='The hour of day (integer in range [0-23]). This is for downloading individual hourly files (each file covers an 6-hour time span.', metavar='HOUR', dest='hour', default=None) ## download path parser.add_argument( '-O', '--outpur-dir', action='store', required=False, help='The directory where the downloaded files shall be placed. Note that this does not affect the merged file (if \'--merge [MERGED_FILE]\' is used).', metavar='OUTPUT_DIR', dest='output_dir', default=os.getcwd()) ## merge individual (hourly) files parser.add_argument('-m', '--merge', action='store', required=False, help='Merge/concatenate individual grid files to this final grid file. This can be a filename optionaly including path (if not path is set, then the file will be created in cwd).', metavar='MERGED_FILE', dest='merge_to', default=None) ## allow forecast products to be used parser.add_argument( '-f', '--allow-forecast', dest='allow_fc', action='store_true', help='If needed, allow the downloading of forecast VMF1 grid file(s)') parser.add_argument( '--del-after-merge', dest='del_after_merge', action='store_true', help='Delete individual grid files after a successeful merge (aka only valid if \'--merge [MERGED_FILE]\' is set).') ## merge individual (hourly) files parser.add_argument('-c', '--config-file', action='store', required=False, help='If you request forecast grid files, you need credentials to access the data; if you provide a CONFIG_FILE here, the program will try to parse lines: \'TUWIEN_VMF1_USER=\"username\" and TUWIEN_VMF1_PASS=\"<PASSWORD>\" \' and use the \"username\" and \"mypassword\" credentials to access the forecast data center', metavar='CONFIG_FILE', dest='config_file', default=None) parser.add_argument('-u', '--username', action='store', required=False, help='If you request forecast grid files, you need credentials to access the data; use this username to access the forecast data center. Note: this will overwite any \"username\" value found in the CONFIG_FILE (if you also specify one).', metavar='USERNAME', dest='username', default=None) parser.add_argument('-p', '--password', action='store', required=False, help='If you request forecast grid files, you need credentials to access the data; use this password to access the forecast data center. Note: this will overwite any \"password\" value found in the CONFIG_FILE (if you also specify one). Note that if you have special characters in the password string (e.g. \"!\") it\'d be better to enclose the password string in singe quotes (e.g. -p \'my!pass\').', metavar='PASSWORD', dest='password', default=None) parser.add_argument('--verbose', dest='verbose', action='store_true', help='Trigger verbose run (prints debug messages).') if __name__ == '__main__': args = parser.parse_args() ## verbose print verboseprint = print if args.verbose else lambda *a, **k: None if args.hour and (args.hour > 23 or args.hour < 0): print('[ERROR] Invalid hour given (0<hour<24)', file=sys.stderr) sys.exit(1) if not os.path.isdir(args.output_dir): print('[ERROR] Invaild output dir given!', file=sys.stderr) sys.exit(1) ## Resolve the date from input args. dt = datetime.datetime.strptime('{:} {:03d}'.format(args.year, args.doy), '%Y %j') ## Where are we going to store local files? save_dir = args.output_dir if args.output_dir is not None else os.getcwd() if not os.path.isdir(save_dir): print('[ERROR] Failed to find requested directory \'{:}\''.format(save_dir), file=sys.stderr) sys.exit(5) ## Generic format of grid files is: VMFG_YYYYMMDD.H00; make a list with the ## (remote) grid files we want. if args.hour: hours_ext = ['{:02d}'.format((args.hour // 6) * 6)] else: hours_ext = ['{:02d}'.format(h) for h in [0, 6, 12, 18]] grid_files_remote = [ 'VMFG_{:}.H{:}'.format(dt.strftime('%Y%m%d'), hstr) for hstr in hours_ext ] ## Make a dictionary to signal the download status for each file, aka ## something like {...'VMFG_YYYYMMDD.H00':{'op':0/1, 'fc':0/1, 'fn':foo}...} ## where 'op' is the status of the final download (0 if final product could ## not be found/downloaded or 1 if the downloading was sucesseful), 'fc' is ## is the status of the forecast download (accordingly to 'op') and 'fn' is ## the local filename of the downloaded file. grid_files_dict = {} for i in grid_files_remote: grid_files_dict[i] = {'op': 0, 'fc': 0} ## Try downloading first for final products. If we can also try for the ## forecast products, do not exit if download fails. verboseprint('Trying to download final grid files.') for fn in grid_files_remote: if dt < datetime.datetime.now(): try: status, target, saveas = http_retrieve(final_dir(dt), fn, save_dir=save_dir, fail_error=(not args.allow_fc)) if not status: grid_files_dict[fn]['op'] = 1 grid_files_dict[fn]['fn'] = saveas verboseprint('\tFinal VMF1 grid file {:} downloaded and saved to {:}'.format(fn, saveas)) else: verboseprint('\tFailed downloading final VMF1 grid file {:}'.format(fn)) except Exception as e: remove_local(grid_files_dict) print('{:}'.format(e), file=sys.stderr) print('[ERROR] Aborting!', file=sys.stderr) sys.exit(1) ## If forecast allowed and date is close to the current, try downloading ## forecast files. If we fail, exit. Of course we need to have credentials ## for that! ## We are only trying for forecast if: ## 1. we haven't already downloaded everything, ## 2. forecast files are allowed (via --allow-forecast) ## 3. date requested is less than 2 days from today if not downloading_complete(grid_files_dict, 'op') and args.allow_fc and (datetime.datetime.now().date() - dt.date()).days < 2: verboseprint('Trying to download forecast grid files.') try: user, passwd = get_credentials_from_args(vars(args)) except Exception as e: remove_local(grid_files_dict) print('{:}'.format(e), file=sys.stderr) print('[ERROR] Aborting!', file=sys.stderr) sys.exit(1) for fn in grid_files_remote: if not grid_files_dict[fn]['op'] and (datetime.datetime.now().date() - dt.date()).days < 2: try: status, target, saveas = http_retrieve(forecast_dir(dt), fn, save_dir=save_dir, username=user, password=<PASSWORD>) if not status: grid_files_dict[fn]['fc'] = 1 grid_files_dict[fn]['fn'] = saveas verboseprint('\tForecast VMF1 grid file {:} downloaded and saved to {:}'.format(fn, saveas)) else: verboseprint('\tFailed downloading forecast VMF1 grid file {:}'.format(fn)) except Exception as e: remove_local(grid_files_dict) print('{:}'.format(e), file=sys.stderr) print('[ERROR] Aborting!', file=sys.stderr) sys.exit(1) ## Done downloading; if we don't have everything, delete what we downloaded ## and exit. Aka, a final check. for fn, status in grid_files_dict.items(): if status['op'] + status['fc'] < 1 or not os.path.isfile(status['fn']): print('[ERROR] Failed to download grid file: {:}'.format(fn), file=sys.stderr) remove_local(grid_files_dict) sys.exit(2) ## Merge individual grid files if needed. if args.merge_to: fn2merge = sorted([ status['fn'] for _, status in grid_files_dict.items() ]) with open(args.merge_to, 'w') as fout: for fn in fn2merge: with open(fn, 'r') as fin: copyfileobj(fin, fout) if args.del_after_merge: remove_local(grid_files_dict)
<reponame>Cure20001019/BTP_DM ''' Author: Ligcox Date: 2021-04-06 15:20:21 LastEditors: Ligcox LastEditTime: 2021-07-21 16:26:50 Description: Apache License (http://www.apache.org/licenses/) Shanghai University Of Engineering Science Copyright (c) 2021 Birdiebot R&D department ''' import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.models import Sequential from tensorflow.keras.preprocessing import image from tensorflow.python.client import device_lib import cv2 import time import numpy as np # TF_MODEL = r'/home/nvidia/Desktop/BTPDM/src/saved_model' TF_MODEL = r'C:\Users\1\Desktop\Competition\2021全国大学生机器人大赛RoboMaster对抗赛\BTP&DM\src\saved_model' class NumClassifier(object): def __init__(self): print("{:=^40}".format("")) print("{:=^40}".format("Number classifier launching...")) print("{:=^40}".format("")) print(device_lib.list_local_devices()) print(tf.__version__) print("Loding model:", TF_MODEL) self.model = tf.keras.models.load_model(TF_MODEL) print("Number classifier launch success") print("Model details:") print(self.model.summary()) def process(self, image): ImageCrop = cv2.resize(image, (640,480)) ImageCrop = cv2.resize(image, (64,64)) # 去除红蓝色 frame = cv2.cvtColor(ImageCrop, cv2.COLOR_BGR2HSV) final_mask = np.ones(frame.shape[:2], np.uint8)*255 _, low_mask = cv2.threshold( frame[:, :, 1], 100, 255, cv2.THRESH_BINARY) _, high_mask = cv2.threshold( frame[:, :, 1],255, 255, cv2.THRESH_TOZERO_INV) channel_masks = cv2.bitwise_and(low_mask, high_mask) final_mask = cv2.bitwise_and(final_mask, channel_masks) output = cv2.bitwise_and(frame, frame, mask=final_mask) output = cv2.cvtColor(output, cv2.COLOR_HSV2BGR) final_mask = cv2.subtract(ImageCrop, output) cv2.imshow("a", final_mask) cv2.waitKey(1) num = self.getImgClass(final_mask) return 0 def getImgClass(self, img): """ 数字分类 """ img = tf.keras.preprocessing.image.array_to_img(img) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) pred_class = self.model(img, training = False) pred_class2 = list(pred_class) tmp_list = sorted(pred_class2[0]) if tmp_list[len(tmp_list) - 1] - tmp_list[len(tmp_list) - 2] > 1.3: num = np.argmax(pred_class) + 1 print("class", num) return num else: return 0 if __name__ == '__main__': c = NumClassifier() while True: # img = cv2.imread(r'/home/nvidia/Desktop/BTPDM/src/Samples/classifierSample.jpg') img = cv2.imread(r'C:\Users\1\Desktop\classifierSample.jpg') st = time.time() c.process(img) print(time.time()-st)
<gh_stars>10-100 # coding=utf8 # Copyright 2018 The trfl Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Tests for retrace_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf from trfl import retrace_ops class RetraceOpsTest(tf.test.TestCase): """Tests for `Retrace` ops.""" def setUp(self): """Defines example data for, and an expected result of, Retrace operations. The example data comprises a minibatch of two sequences of four consecutive timesteps, allowing the data to be interpreted by Retrace as three successive transitions. """ super(RetraceOpsTest, self).setUp() ### Example input data: self.lambda_ = 0.9 self.qs = [ [[2.2, 3.2, 4.2], [5.2, 6.2, 7.2]], [[7.2, 6.2, 5.2], [4.2, 3.2, 2.2]], [[3.2, 5.2, 7.2], [4.2, 6.2, 9.2]], [[2.2, 8.2, 4.2], [9.2, 1.2, 8.2]]] self.targnet_qs = [ [[2., 3., 4.], [5., 6., 7.]], [[7., 6., 5.], [4., 3., 2.]], [[3., 5., 7.], [4., 6., 9.]], [[2., 8., 4.], [9., 1., 8.]]] self.actions = [ [2, 0], [1, 2], [0, 1], [2, 0]] self.rewards = [ [1.9, 2.9], [3.9, 4.9], [5.9, 6.9], [np.nan, # nan marks entries we should never use. np.nan]] self.pcontinues = [ [0.8, 0.9], [0.7, 0.8], [0.6, 0.5], [np.nan, np.nan]] self.target_policy_probs = [ [[np.nan] * 3, [np.nan] * 3], [[0.41, 0.28, 0.31], [0.19, 0.77, 0.04]], [[0.22, 0.44, 0.34], [0.14, 0.25, 0.61]], [[0.16, 0.72, 0.12], [0.33, 0.30, 0.37]]] self.behaviour_policy_probs = [ [np.nan, np.nan], [0.85, 0.86], [0.87, 0.88], [0.89, 0.84]] ### Expected results of Retrace as applied to the above: # NOTE: To keep the test code compact, we don't use the example data when # manually computing our expected results, but instead duplicate their # values explictly in those calculations. Some patterns in the values can # help you track who's who: for example, note that target network Q values # are integers, whilst learning network Q values all end in 0.2. # In a purely theoretical setting, we would compute the quantity we call # the "trace" using this recurrence relation: # # ΔQ_tm1 = δ_tm1 + λγπ(a_t | s_t)/μ(a_t | s_t) ⋅ ΔQ_t # δ_tm1 = r_t + γ𝔼_π[Q(s_t, .)] - Q(s_tm1, a_tm1) # # In a target network setting, you might rewrite ΔQ_t as ΔQ'_t, indicating # that this value is the next-timestep trace as computed when all # Q(s_tm1, a_tm1) terms (in δ_t, δ_t+1, ...) come from the target network, # not the learning network. # # To generate our collection of expected outputs, we'll first compute # "ΔQ'_tm1" (the "target network trace") at all timesteps. # # We start at the end of the sequence and work backward, like the # implementation does. targ_trace = np.zeros((3, 2)) targ_trace[2, 0] = (5.9 + 0.6*(0.16*2 + 0.72*8 + 0.12*4) - 3) # δ_tm1[2,0] targ_trace[2, 1] = (6.9 + 0.5*(0.33*9 + 0.30*1 + 0.37*8) - 6) # δ_tm1[2,1] targ_trace[1, 0] = (3.9 + 0.7*(0.22*3 + 0.44*5 + 0.34*7) - 6 + # δ_tm1[1,0] 0.9*0.7*0.22/0.87 * targ_trace[2, 0]) targ_trace[1, 1] = (4.9 + 0.8*(0.14*4 + 0.25*6 + 0.61*9) - 2 + # δ_tm1[1,1] 0.9*0.8*0.25/0.88 * targ_trace[2, 1]) targ_trace[0, 0] = (1.9 + 0.8*(0.41*7 + 0.28*6 + 0.31*5) - 4 + # δ_tm1[0,0] 0.9*0.8*0.28/0.85 * targ_trace[1, 0]) targ_trace[0, 1] = (2.9 + 0.9*(0.19*4 + 0.77*3 + 0.04*2) - 5 + # δ_tm1[0,1] 0.9*0.9*0.04/0.86 * targ_trace[1, 1]) # We can evaluate target Q values by adding targ_trace to single step # returns. target_q = np.zeros((3, 2)) target_q[2, 0] = (5.9 + 0.6*(0.16*2 + 0.72*8 + 0.12*4)) target_q[2, 1] = (6.9 + 0.5*(0.33*9 + 0.30*1 + 0.37*8)) target_q[1, 0] = (3.9 + 0.7*(0.22*3 + 0.44*5 + 0.34*7) + 0.9*0.7*0.22/0.87 * targ_trace[2, 0]) target_q[1, 1] = (4.9 + 0.8*(0.14*4 + 0.25*6 + 0.61*9) + 0.9*0.8*0.25/0.88 * targ_trace[2, 1]) target_q[0, 0] = (1.9 + 0.8*(0.41*7 + 0.28*6 + 0.31*5) + 0.9*0.8*0.28/0.85 * targ_trace[1, 0]) target_q[0, 1] = (2.9 + 0.9*(0.19*4 + 0.77*3 + 0.04*2) + 0.9*0.9*0.04/0.86 * targ_trace[1, 1]) # Now we can compute the "official" trace (ΔQ_tm1), which involves the # learning network. The only difference from the "target network trace" # calculations is the Q(s_tm1, a_tm1) terms we use: trace = np.zeros((3, 2)) # ↓ Q(s_tm1, a_tm1) trace[2, 0] = target_q[2, 0] - 3.2 # δ_tm1[2,0] trace[2, 1] = target_q[2, 1] - 6.2 # δ_tm1[2,1] trace[1, 0] = target_q[1, 0] - 6.2 # δ_tm1[1,0] trace[1, 1] = target_q[1, 1] - 2.2 # δ_tm1[1,1] trace[0, 0] = target_q[0, 0] - 4.2 # δ_tm1[0,0] trace[0, 1] = target_q[0, 1] - 5.2 # δ_tm1[0,0] self.expected_result = 0.5 * np.square(trace) self.target_q = target_q def testRetraceThreeTimeSteps(self): """Subject Retrace to a two-sequence, three-timestep minibatch.""" retrace = retrace_ops.retrace( self.lambda_, self.qs, self.targnet_qs, self.actions, self.rewards, self.pcontinues, self.target_policy_probs, self.behaviour_policy_probs) with self.test_session() as sess: self.assertAllClose(sess.run(retrace.loss), self.expected_result) def _get_retrace_core(self): """Constructs a tf subgraph from `retrace_core` op. A retrace core namedtuple is built from a two-sequence, three-timestep input minibatch. Returns: Tuple of size 3 containing non-differentiable inputs, differentiable inputs and retrace_core namedtuple. """ # Here we essentially replicate the preprocessing that `retrace` does # as it constructs the inputs to `retrace_core`. # These ops must be Tensors so that we can use them in the # `testNoOtherGradients` unit test. TensorFlow can only compute gradients # with respect to other parts of the graph lambda_ = tf.constant(self.lambda_) q_tm1 = tf.constant(self.qs[:3]) a_tm1 = tf.constant(self.actions[:3]) r_t = tf.constant(self.rewards[:3]) pcont_t = tf.constant(self.pcontinues[:3]) target_policy_t = tf.constant(self.target_policy_probs[1:4]) behaviour_policy_t = tf.constant(self.behaviour_policy_probs[1:4]) targnet_q_t = tf.constant(self.targnet_qs[1:4]) a_t = tf.constant(self.actions[1:4]) static_args = [lambda_, a_tm1, r_t, pcont_t, target_policy_t, behaviour_policy_t, targnet_q_t, a_t] diff_args = [q_tm1] return (static_args, diff_args, retrace_ops.retrace_core(lambda_, q_tm1, a_tm1, r_t, pcont_t, target_policy_t, behaviour_policy_t, targnet_q_t, a_t)) def testRetraceCoreTargetQThreeTimeSteps(self): """Tests whether retrace_core evaluates correct targets for regression.""" _, _, retrace = self._get_retrace_core() with self.test_session() as sess: self.assertAllClose(sess.run(retrace.extra.target), self.target_q) def testRetraceCoreLossThreeTimeSteps(self): """Tests whether retrace_core evaluates correct losses.""" _, _, retrace = self._get_retrace_core() with self.test_session() as sess: self.assertAllClose(sess.run(retrace.loss), self.expected_result) def testNoOtherGradients(self): """Tests no gradient propagates through things other than q_tm1.""" static_args, _, retrace = self._get_retrace_core() gradients = tf.gradients([retrace.loss], static_args) self.assertEqual(gradients, [None] * len(gradients)) def testMovingNetworkGradientIsEvaluated(self): """Tests that gradients are evaluated w.r.t. q_tm1.""" _, diff_args, retrace = self._get_retrace_core() gradients = tf.gradients([retrace.loss], diff_args) for gradient in gradients: self.assertNotEqual(gradient, None) def testRetraceHatesBadlyRankedInputs(self): """Ensure Retrace notices inputs with the wrong rank.""" # No problems if we create a Retrace using correctly-ranked arguments. proper_args = [self.lambda_, self.qs, self.targnet_qs, self.actions, self.rewards, self.pcontinues, self.target_policy_probs, self.behaviour_policy_probs] retrace_ops.retrace(*proper_args) # Now make a local copy of the args and try modifying each element to have # an inappropriate rank. We should get an error each time. for i in xrange(len(proper_args)): bad_args = list(proper_args) bad_args[i] = [bad_args[i]] with self.assertRaises(ValueError): retrace_ops.retrace(*bad_args) if __name__ == '__main__': tf.test.main()
# Copyright (C) 2018 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions # and limitations under the License. # # # SPDX-License-Identifier: Apache-2.0 """ This module implements resource contention detection on one workload """ from __future__ import print_function from __future__ import division import subprocess import time from collections import deque from itertools import islice from datetime import datetime from enum import Enum from os.path import join as path_join from analyze.analyzer import Metric class Contention(Enum): """ This enumeration defines resource contention type """ UNKN = 1 CPU_CYC = 2 LLC = 3 MEM_BW = 4 TDP = 5 class Container(object): """ This class is the abstraction of one task, container metrics and contention detection method are encapsulated in this module """ def __init__( self, cgroup_driver, cid, name, pids, verbose, thresh=[], tdp_thresh=[], history_depth=5): self.cid = cid self.name = name self.pids = pids self.cpu_usage = 0 self.utils = 0 self.timestamp = 0.0 self.thresh = thresh self.tdp_thresh = tdp_thresh self.verbose = verbose self.metrics = dict() self.history_depth = history_depth + 1 self.metrics_history = deque([], self.history_depth) self.cpusets = [] if cgroup_driver == 'systemd': self.con_path = 'docker-' + cid + '.scope' self.parent_path = 'system.slice/' else: self.con_path = cid self.parent_path = 'docker/' def __str__(self): metrics = self.metrics cols = [ metrics['time'], self.cid, self.name, metrics[Metric.INST], metrics[Metric.CYC], metrics[Metric.CPI], metrics[Metric.L3MPKI], metrics[Metric.L3MISS], metrics[Metric.NF], self.utils, metrics[Metric.L3OCC], metrics[Metric.MBL], metrics[Metric.MBR], metrics[Metric.L2STALL], metrics[Metric.MEMSTALL], metrics[Metric.L2SPKI], metrics[Metric.MSPKI], ] return ','.join(str(col) for col in cols) + '\n' def update_metrics(self, row_tuple): key_mappings = [('time', str), (Metric.INST, int), (Metric.CYC, int), (Metric.CPI, float), (Metric.L3MPKI, float), (Metric.L3MISS, int), (Metric.NF, float), (Metric.L3OCC, int), (Metric.MBL, float), (Metric.MBR, float), (Metric.L2STALL, int), (Metric.MEMSTALL, int), (Metric.L2SPKI, float), (Metric.MSPKI, float)] for key, converter in key_mappings: self.metrics[key] = converter(row_tuple[1][key]) self.utils = float(row_tuple[1][Metric.UTIL]) self.update_metrics_history() def get_history_delta_by_type(self, column_name): length = len(self.metrics_history) if length == 0: return 0 if length == 1: return self.metrics_history[0][column_name] data_sum = sum(m[column_name] for m in list(islice(self.metrics_history, length - 1))) data_avg = float(data_sum) / (length - 1) data_delta = self.metrics_history[-1][column_name] - data_avg return data_delta def get_llcoccupany_delta(self): return self.get_history_delta_by_type(Metric.L3OCC) def get_freq_delta(self): return self.get_history_delta_by_type(Metric.NF) def get_latest_mbt(self): mbl = self.metrics.get(Metric.MBL, 0) mbr = self.metrics.get(Metric.MBR, 0) return mbl + mbr def get_full_metrics(self, timestamp, interval): """ retrieve container platform metrics """ self.update_cpu_usage() metrics = self.metrics if self.metrics: metrics['time'] = timestamp if metrics[Metric.INST] == 0: metrics[Metric.CPI] = 0 metrics[Metric.L3MPKI] = 0 metrics[Metric.L2SPKI] = 0 metrics[Metric.MSPKI] = 0 else: metrics[Metric.CPI] = metrics[Metric.CYC] /\ metrics[Metric.INST] metrics[Metric.L3MPKI] = metrics[Metric.L3MISS] * 1000 /\ metrics[Metric.INST] metrics[Metric.L2SPKI] = metrics[Metric.L2STALL] * 1000 /\ metrics[Metric.INST] metrics[Metric.MSPKI] = metrics[Metric.MEMSTALL] * 1000 /\ metrics[Metric.INST] if self.utils == 0: metrics[Metric.NF] = 0 else: metrics[Metric.NF] = int(metrics[Metric.CYC] / interval / 10000 / self.utils) return metrics def update_pids(self, pids): """ update process ids of one Container pids - pid list of Container """ self.pids = pids def update_cpu_usage(self): """ calculate cpu usage of container """ try: cur = time.time() * 1e9 filename = path_join('/sys/fs/cgroup/cpu/docker', self.cid, 'cpuacct.usage') with open(filename, 'r') as f: usage = int(f.read().strip()) if self.cpu_usage != 0: self.utils = (usage - self.cpu_usage) * 100 /\ (cur - self.timestamp) self.cpu_usage = usage self.timestamp = cur except (ValueError, IOError): pass def update_metrics_history(self): ''' add metric data to metrics history metrics history only contains the most recent metrics data, defined by self.historyDepth if histroy metrics data length exceeds the self.historyDepth, the oldest data will be erased ''' self.metrics_history.append(self.metrics.copy()) def __detect_in_bin(self, thresh): metrics = self.metrics contend_res = [] if metrics[Metric.CPI] > thresh['cpi']: unk_res = True if metrics[Metric.L3MPKI] > thresh['mpki']: print('Last Level Cache contention is detected at %s' % metrics['time']) print('Latency critical container %s, CPI = %f, threshold =\ %f, MPKI = %f, threshold = %f, L2SPKI = %f, threshold = %f' % (self.name, metrics[Metric.CPI], thresh['cpi'], metrics[Metric.L3MPKI], thresh['mpki'], metrics[Metric.L2SPKI], thresh['l2spki'])) unk_res = False contend_res.append(Contention.LLC) if metrics[Metric.MBL] + metrics[Metric.MBR] < thresh['mb'] or\ metrics[Metric.MSPKI] > thresh['mspki']: print('Memory Bandwidth contention detected at %s' % metrics['time']) print('Latency critical container %s, CPI = %f, threshold =\ %f, MBL = %f, MBR = %f, threshold = %f, MSPKI = %f, threshold = %f' % (self.name, metrics[Metric.CPI], thresh['cpi'], metrics[Metric.MBL], metrics[Metric.MBR], thresh['mb'], metrics[Metric.MSPKI], thresh['mspki'])) unk_res = False contend_res.append(Contention.MEM_BW) if unk_res: print('Performance is impacted at %s' % metrics['time']) print('Latency critical container %s, CPI = %f, threshold =\ %f' % (self.name, metrics[Metric.CPI], thresh['cpi'])) contend_res.append(Contention.UNKN) return contend_res def tdp_contention_detect(self): """ detect TDP contention in container """ if not self.tdp_thresh: return None if self.verbose: print(self.utils, self.metrics[Metric.NF], self.tdp_thresh['util'], self.tdp_thresh['bar']) if self.utils >= self.tdp_thresh['util'] and\ self.metrics[Metric.NF] < self.tdp_thresh['bar']: print('TDP Contention Alert!') return Contention.TDP return None def contention_detect(self): """ detect resouce contention after find proper utilization bin """ if not self.thresh: return [] for i in range(0, len(self.thresh)): thresh = self.thresh[i] if self.utils < thresh['util_start']: if i == 0: return [] return self.__detect_in_bin(self.thresh[i - 1]) if self.utils >= thresh['util_start']: if self.utils < thresh['util_end'] or\ i == len(self.thresh) - 1: return self.__detect_in_bin(thresh)
<reponame>niallrmurphy/twimp<filename>ships/ships.py #!/usr/bin/python # Ship simulator, updated for TW4. from __future__ import print_function import enum import pprint import random import dice class ShipType(enum.Enum): SPACEDOCK = 1 PDS = 2 FIGHTER = 3 CARRIER = 4 CRUISER = 5 DESTROYER = 6 DREADNOUGHT = 7 WARSUN = 8 FLAGSHIP = 9 class CombatUnit(object): def __init__(self, edition=None, verbosity=False): self.damage = 0 self.movement = 0 self.production_cost = 0 if edition == None or edition == 4: self.edition = 4 else: self.edition = 3 self.verbosity = verbosity class GroundUnit(CombatUnit): pass class SpaceVehicle(CombatUnit): def __init__(self, edition=None, verbosity=False): super(SpaceVehicle, self).__init__(edition) self.capacity_limit = 0 self.verbosity = verbosity def GenerateHits(self): pass def ReceiveHits(self, amount): """Receive an amount of points of damage. Args: amount: Integer number. Returns: integer of number of hits left. This is the generic, called by subclasses, therefore we presume one hit will destroy it. """ if self.verbosity: print ("NOTE: ship destroyed (%s)" % (self.__class__.__name__)) return 0 def TravelTo(self): pass def IsDamaged(self): return (self.damage > 0) def CanHandleDamage(self): """How much damage can this ship take?""" return 1 def WhereCanITravelTo(self): pass def ProductionSlotsTaken(self): pass def CanCarryGroundForces(self): return False def CanCarryPDSes(self): return False def CanCarryFighters(self): return False def CanGenerateAntiFighterBarrage(self): return False def CanSupportFighters(self): return False def ProvidePlanetaryShield(self): return False def AddToCargo(self, thing): if len(self.cargo) < self.capacity_limit: self.cargo.append(thing) return True else: if self.verbosity: print ("NOTE: cargo limit of %s exceeded" % self.capacity_limit) return False def RemoveFromCargo(self): thing = pop(self.cargo) return thing class Carrier(SpaceVehicle): def __init__(self, edition = None): super(Carrier, self).__init__(edition) self.movement = 1 self.max_produceable = 4 self.production_cost = 3 if self.edition == None or self.edition == 4: self.capacity_limit = 4 else: self.capacity_limit = 6 self.shiptype = ShipType.CARRIER self.cargo = [] def CanCarryFighters(self): return True def CanCarryPDSes(self): return True def CanCarryGroundForces(self): return True def UpgradeCapacity(self): self.capacity_limit = 6 def GenerateHits(self): return dice.Dice.RollWithTarget(9, 1) class Cruiser(SpaceVehicle): def __init__(self, edition = 4): super(Cruiser, self).__init__(edition) self.movement = 2 self.max_produceable = 8 self.production_cost = 2 self.shiptype = ShipType.CRUISER def GenerateHits(self): return dice.Dice.RollWithTarget(7, 1) class Destroyer(SpaceVehicle): def __init__(self, edition = 4): super(Destroyer, self).__init__(edition) self.movement = 2 self.max_produceable = 8 self.production_cost = 1 self.shiptype = ShipType.DESTROYER def GenerateHits(self): return dice.Dice.RollWithTarget(9, 1) def CanGenerateAntiFighterBarrage(self): return True def GenerateAntiFighterBarrage(self): return Dice.RollWithTarget(9, 2) class Dreadnought(SpaceVehicle): def __init__(self, edition = 4): super(Dreadnought, self).__init__(edition) self.movement = 2 self.production_cost = 4 if self.edition == 4 else 5 self.capacity_limit = 1 self.shiptype = ShipType.DREADNOUGHT def GenerateHits(self): return Dice.RollWithTarget(5, 1) def ReceiveHits(self, amount): amount_left = 2 - self.damage - amount if amount_left <= 0: if self.verbosity: print ("NOTE: ship destroyed (Dreadnought)") return 0 elif amount == 1: self.damage = 1 return 1 elif amount == 0: return 2 def CanHandleDamage(self): return 2 class Fighter(SpaceVehicle): def __init__(self, edition = 4): super(Fighter, self).__init__(edition) self.max_produceable = 10 self.production_cost = 0.5 self.shiptype = ShipType.FIGHTER def GenerateHits(self): return dice.Dice.RollWithTarget(9, 1) class Flagship(SpaceVehicle): def __init__(self, edition = 4): super(Fighter, self).__init__(edition) self.max_produceable = 1 self.production_cost = 5 self.shiptype = ShipType.FLAGSHIP def GenerateHits(self): return dice.Dice.RollWithTarget(9, 1) class Infantry(CombatUnit): pass class PDS(SpaceVehicle): def __init__(self, edition=4): super(PDS, self).__init__(edition) self.max_produceable = 6 self.production_cost = 2 self.shiptype = ShipType.PDS def GenerateHits(self): return dice.Dice.RollWithTarget(6, 1) def ProvidePlanetaryShield(self): return True class SpaceDock(SpaceVehicle): def __init__(self, edition=4): super(SpaceDock, self).__init__(edition) self.max_produceable = 6 self.production_cost = 4 self.shiptype = ShipType.SPACEDOCK class WarSun(SpaceVehicle): def __init__(self, edition = 4): super(WarSun, self).__init__(edition) self.movement = 2 self.max_produceable = 2 self.production_cost = 12 self.cargo = [] self.shiptype = ShipType.WARSUN def GenerateHits(self): return dice.Dice.RollWithTarget(3, 3) def ReceiveHits(self, amount): amount_left = 2 - self.damage - amount if amount_left <= 0: if self.verbosity: print ("NOTE: ship destroyed (WarSun)") return 0 elif amount == 1: self.damage = 1 return 1 elif amount == 0: return 2 def CanHandleDamage(self): return 2 if __name__ == '__main__': pass
from stats import * import glob as gl import pandas as pd import os import time def printProgressBar (iteration, total, prefix, suffix = "completo", decimals = 1, length = 50, fill = '█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r') # Print New Line on Complete if iteration == total: print("\n") def run ( ): caminho_dados = "ArtificialDataset/*" header = 0 sep = '\t' index_col = False dados = sorted(gl.glob(caminho_dados)) dataset = caminho_dados.split('/')[-2] nomes = [ ] for i, base in enumerate(dados): nomes.append( base.split( '/' )[ -1 ].split( '.' )[ 0 ] ) estatisticas = {'f1': f1_maximum_fisher_discriminating_ratio, 'f2': f2_volume_of_overlapping, 'f3': f3_maximum_individual_feat_efficiency, 'f4': f4_collective_reature_efficiency, 'l1': l1_sum_of_error_distance, 'l2': l2_rate_of_linear_classifier, 'n1': n1_fraction_borderline, 'n2': n2_ratio_intra_extra_class_nearest_neighbor_distance, 'n3': n3_error_rate_nearest_neighbor_classifier, 'l3': l3_non_linearity_of_linear_classifier, 'n4': n4_non_linearity_of_nearest_neighbor_classifier, 't1': t1_fraction_hyperspheres_covering_data, 't2': t2_average_number_of_examples_per_dimension} lista_stats = ['f1', 'f2', 'f3', 'f4', 'n1', 'n2', 'n3', 'n4', 'l1', 'l2', 'l3', 't1', 't2'] results = pd.DataFrame() results[ 'stats' ] = lista_stats n = len(lista_stats) * len(nomes) j = 0 # Output file, where the matched loglines will be copied to log_filename = os.path.normpath("logs/"+ dataset + ".log") output_filename = os.path.normpath("outputs/run_"+ dataset + ".csv") # Overwrites the file, ensure we're starting out with a blank file with open(log_filename, "w") as arquivo_log: arquivo_log.write("stat,base,time,done\n") with open(output_filename, "w") as arquivo_out: arquivo_out.write("bases") for stat in lista_stats: arquivo_out.write( ",{0}".format(stat)) arquivo_out.write( "\n" ) start_all = time.time() for i, base in enumerate(dados): data = pd.read_csv( base, sep=sep, index_col=index_col, header=header) with open(output_filename, "a") as arquivo_out: arquivo_out.write( "{0}".format(nomes[i]) ) stats = [ ] for k, stat in enumerate(lista_stats): with open(log_filename, "a") as arquivo_log: arquivo_log.write("{0},{1},".format(stat, nomes[i])) start = time.time() stats.append(estatisticas[stat](data)) end = time.time() with open(output_filename, "a") as arquivo_out: arquivo_out.write(",{0}".format(stats[k])) with open(log_filename, "a") as arquivo_log: arquivo_log.write("{0},OK\n".format(end - start)) j = j + 1 printProgressBar(j, n-1, prefix = "{0} de {1}:".format(j, n-1)) with open(output_filename, "a") as arquivo_out: arquivo_out.write("\n") results[ base ] = stats end_all = time.time() with open(log_filename, "a") as arquivo_log: arquivo_log.write("all,all,{0},OK\n".format(end_all - start_all)) return results if __name__ == "__main__": run()
#!/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import time import logging import os import json from multiprocessing import Process from common.utils import Util from common.file_collector import FileWatcher from multiprocessing import Pool from common.kafka_client import KafkaTopic class Collector(object): def __init__(self,hdfs_app_path,kafka_topic,conf_type): self._initialize_members(hdfs_app_path,kafka_topic,conf_type) def _initialize_members(self,hdfs_app_path,kafka_topic,conf_type): # getting parameters. self._logger = logging.getLogger('SPOT.INGEST.FLOW') self._hdfs_app_path = hdfs_app_path self._kafka_topic = kafka_topic # get script path self._script_path = os.path.dirname(os.path.abspath(__file__)) # read flow configuration. conf_file = "{0}/ingest_conf.json".format(os.path.dirname(os.path.dirname(self._script_path))) conf = json.loads(open(conf_file).read()) self._conf = conf["pipelines"][conf_type] # set configuration. self._collector_path = self._conf['collector_path'] self._dsource = 'flow' self._hdfs_root_path = "{0}/{1}".format(hdfs_app_path, self._dsource) self._supported_files = self._conf['supported_files'] # create collector watcher self._watcher = FileWatcher(self._collector_path,self._supported_files) # Multiprocessing. self._processes = conf["collector_processes"] self._ingestion_interval = conf["ingestion_interval"] self._pool = Pool(processes=self._processes) def start(self): self._logger.info("Starting FLOW ingest") self._watcher.start() try: while True: self._ingest_files_pool() time.sleep(self._ingestion_interval) except KeyboardInterrupt: self._logger.info("Stopping FLOW collector...") Util.remove_kafka_topic(self._kafka_topic.Zookeeper,self._kafka_topic.Topic,self._logger) self._watcher.stop() self._pool.terminate() self._pool.close() self._pool.join() SystemExit("Ingest finished...") def _ingest_files_pool(self): if self._watcher.HasFiles: for x in range(0,self._processes): file = self._watcher.GetNextFile() resutl = self._pool.apply_async(ingest_file,args=(file,self._kafka_topic.Partition,self._hdfs_root_path ,self._kafka_topic.Topic,self._kafka_topic.BootstrapServers,)) #resutl.get() # to debug add try and catch. if not self._watcher.HasFiles: break return True def ingest_file(file,partition,hdfs_root_path,topic,kafka_servers): logger = logging.getLogger('SPOT.INGEST.FLOW.{0}'.format(os.getpid())) try: # get file name and date. file_name_parts = file.split('/') file_name = file_name_parts[len(file_name_parts)-1] file_date = file_name.split('.')[1] file_date_path = file_date[0:8] file_date_hour = file_date[8:10] # hdfs path with timestamp. hdfs_path = "{0}/binary/{1}/{2}".format(hdfs_root_path,file_date_path,file_date_hour) Util.creat_hdfs_folder(hdfs_path,logger) # load to hdfs. hdfs_file = "{0}/{1}".format(hdfs_path,file_name) Util.load_to_hdfs(file,hdfs_file,logger) # create event for workers to process the file. logger.info("Sending file to worker number: {0}".format(partition)) KafkaTopic.SendMessage(hdfs_file,kafka_servers,topic,partition) logger.info("File {0} has been successfully sent to Kafka Topic to: {1}".format(file,topic)) except Exception as err: logger.error("There was a problem, please check the following error message:{0}".format(err.message)) logger.error("Exception: {0}".format(err))
#!/usr/bin/env python """ Utilities related to file handling """ from __future__ import print_function, division import io import os import stat import subprocess import time import zlib from Utils.Utilities import decodeBytesToUnicode from Utils.PythonVersion import PY3 def calculateChecksums(filename): """ _calculateChecksums_ Get the adler32 and crc32 checksums of a file. Return None on error Process line by line and adjust for known signed vs. unsigned issues http://docs.python.org/library/zlib.html The cksum UNIX command line tool implements a CRC32 checksum that is different than any of the python algorithms, therefore open cksum in a subprocess and feed it the same chunks of data that are used to calculate the adler32 checksum. """ adler32Checksum = 1 # adler32 of an empty string cksumProcess = subprocess.Popen("cksum", stdin=subprocess.PIPE, stdout=subprocess.PIPE) # the lambda basically creates an iterator function with zero # arguments that steps through the file in 4096 byte chunks with open(filename, 'rb') as f: for chunk in iter((lambda: f.read(4096)), b''): adler32Checksum = zlib.adler32(chunk, adler32Checksum) cksumProcess.stdin.write(chunk) cksumProcess.stdin.close() cksumProcess.wait() cksumStdout = cksumProcess.stdout.read().split() cksumProcess.stdout.close() # consistency check on the cksum output filesize = os.stat(filename)[stat.ST_SIZE] if len(cksumStdout) != 2 or int(cksumStdout[1]) != filesize: raise RuntimeError("Something went wrong with the cksum calculation !") if PY3: # using native-string approach. convert from bytes to unicode in # python 3 only. cksumStdout[0] = decodeBytesToUnicode(cksumStdout[0]) return (format(adler32Checksum & 0xffffffff, '08x'), cksumStdout[0]) def tail(filename, nLines=20): """ _tail_ A version of tail Adapted from code on http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail """ assert nLines >= 0 pos, lines = nLines + 1, [] # make sure only valid utf8 encoded chars will be passed along with io.open(filename, 'r', encoding='utf8', errors='ignore') as f: while len(lines) <= nLines: try: f.seek(-pos, 2) except IOError: f.seek(0) break finally: lines = list(f) pos *= 2 text = "".join(lines[-nLines:]) return text def getFileInfo(filename): """ _getFileInfo_ Return file info in a friendly format """ filestats = os.stat(filename) fileInfo = {'Name': filename, 'Size': filestats[stat.ST_SIZE], 'LastModification': time.strftime("%m/%d/%Y %I:%M:%S %p", time.localtime(filestats[stat.ST_MTIME])), 'LastAccess': time.strftime("%m/%d/%Y %I:%M:%S %p", time.localtime(filestats[stat.ST_ATIME]))} return fileInfo def findMagicStr(filename, matchString): """ _findMagicStr_ Parse a log file looking for a pattern string """ with io.open(filename, 'r', encoding='utf8', errors='ignore') as logfile: # TODO: can we avoid reading the whole file for line in logfile: if matchString in line: yield line def getFullPath(name, envPath="PATH"): """ :param name: file name :param envPath: any environment variable specified for path (PATH, PYTHONPATH, etc) :return: full path if it is under PATH env """ for path in os.getenv(envPath).split(os.path.pathsep): fullPath = os.path.join(path, name) if os.path.exists(fullPath): return fullPath return None
<filename>src/matching/games/hospital_resident.py """ The HR game class and supporting functions. """ import copy import warnings from matching import BaseGame, MultipleMatching from matching import Player as Resident from matching.algorithms import hospital_resident from matching.exceptions import ( MatchingError, PlayerExcludedWarning, PreferencesChangedWarning, ) from matching.players import Hospital class HospitalResident(BaseGame): """A class for solving instances of the hospital-resident assignment problem (HR). In this case, a blocking pair is any resident-hospital pair that satisfies **all** of the following: - They are present in each other's preference lists; - either the resident is unmatched, or they prefer the hospital to their current match; - either the hospital is under-subscribed, or they prefer the resident to at least one of their current matches. Parameters ---------- residents : list of Player The residents in the matching game. Each resident must rank a subset of those in :code:`hospitals`. hospitals : list of Hospital The hospitals in the matching game. Each hospital must rank all of (and only) the residents which rank it. clean : bool Indicator for whether the players of the game should be cleaned. Cleaning is reductive in nature, removing players from the game and/or other player's preferences if they do not meet the requirements of the game. Attributes ---------- matching : Matching or None Once the game is solved, a matching is available as a :code:`Matching` object with the hospitals as keys and their resident matches as values. Initialises as :code:`None`. blocking_pairs : list of (Player, Hospital) or None Initialises as `None`. Otherwise, a list of the resident-hospital blocking pairs. """ def __init__(self, residents, hospitals, clean=False): residents, hospitals = copy.deepcopy([residents, hospitals]) self.residents = residents self.hospitals = hospitals self.clean = clean self._all_residents = residents self._all_hospitals = hospitals super().__init__(clean) self.check_inputs() @classmethod def create_from_dictionaries( cls, resident_prefs, hospital_prefs, capacities, clean=False ): """Create an instance of :code:`HospitalResident` from two preference dictionaries and capacities. If :code:`clean=True` then remove players from the game and/or player preferences if they do not satisfy the conditions of the game.""" residents, hospitals = _make_players( resident_prefs, hospital_prefs, capacities ) game = cls(residents, hospitals, clean) return game def solve(self, optimal="resident"): """Solve the instance of HR using either the resident- or hospital-oriented algorithm. Return the matching.""" self.matching = MultipleMatching( hospital_resident(self.residents, self.hospitals, optimal) ) return self.matching def check_validity(self): """ Check whether the current matching is valid. """ unacceptable_issues = self._check_for_unacceptable_matches( "residents" ) + self._check_for_unacceptable_matches("hospitals") oversubscribed_issues = self._check_for_oversubscribed_players( "hospitals" ) if unacceptable_issues or oversubscribed_issues: raise MatchingError( unacceptable_matches=unacceptable_issues, oversubscribed_hospitals=oversubscribed_issues, ) return True def _check_for_unacceptable_matches(self, party): """Check that no player in `party` is matched to an unacceptable player.""" issues = [] for player in vars(self)[party]: issue = player.check_if_match_is_unacceptable(unmatched_okay=True) if isinstance(issue, list): issues.extend(issue) elif isinstance(issue, str): issues.append(issue) return issues def _check_for_oversubscribed_players(self, party): """ Check that no player in `party` is oversubscribed. """ issues = [] for player in vars(self)[party]: issue = player.check_if_oversubscribed() if issue: issues.append(issue) return issues def check_stability(self): """Check for the existence of any blocking pairs in the current matching, thus determining the stability of the matching.""" blocking_pairs = [] for resident in self.residents: for hospital in self.hospitals: if ( _check_mutual_preference(resident, hospital) and _check_resident_unhappy(resident, hospital) and _check_hospital_unhappy(resident, hospital) ): blocking_pairs.append((resident, hospital)) self.blocking_pairs = blocking_pairs return not any(blocking_pairs) def check_inputs(self): """Give out warnings if any of the conditions of the game have been broken. If the :code:`clean` attribute is :code:`True`, then remove any such situations from the game.""" self._check_inputs_player_prefs_unique("residents") self._check_inputs_player_prefs_unique("hospitals") self._check_inputs_player_prefs_all_in_party("residents", "hospitals") self._check_inputs_player_prefs_all_in_party("hospitals", "residents") self._check_inputs_player_prefs_all_reciprocated("hospitals") self._check_inputs_player_reciprocated_all_prefs( "hospitals", "residents" ) self._check_inputs_player_prefs_nonempty("residents", "hospitals") self._check_inputs_player_prefs_nonempty("hospitals", "residents") self._check_inputs_player_capacity("hospitals", "residents") def _check_inputs_player_prefs_all_reciprocated(self, party): """Make sure that each player in :code:`party` has ranked only those players that have ranked it.""" for player in vars(self)[party]: for other in player.prefs: if player not in other.prefs: warnings.warn( PreferencesChangedWarning( f"{player} ranked {other} but they did not." ) ) if self.clean: player._forget(other) def _check_inputs_player_reciprocated_all_prefs(self, party, other_party): """Make sure that each player in :code:`party` has ranked all those players in :code:`other_party` that have ranked it.""" players = vars(self)[party] others = vars(self)[other_party] for player in players: others_that_ranked = [ other for other in others if player in other.prefs ] for other in others_that_ranked: if other not in player.prefs: warnings.warn( PreferencesChangedWarning( f"{other} ranked {player} but they did not." ) ) if self.clean: other._forget(player) def _check_inputs_player_capacity(self, party, other_party): """Check that each player in :code:`party` has a capacity of at least one. If the :code:`clean` attribute is :code:`True`, remove any hospital that does not have such a capacity from the game.""" for player in vars(self)[party]: if player.capacity < 1: warnings.warn(PlayerExcludedWarning(player)) if self.clean: self._remove_player(player, party, other_party) def _check_mutual_preference(resident, hospital): """ Determine whether two players each have a preference of the other. """ return resident in hospital.prefs and hospital in resident.prefs def _check_resident_unhappy(resident, hospital): """Determine whether a resident is unhappy because they are unmatched, or they prefer the hospital to their current match.""" return resident.matching is None or resident.prefers( hospital, resident.matching ) def _check_hospital_unhappy(resident, hospital): """Determine whether a hospital is unhappy because they are under-subscribed, or they prefer the resident to at least one of their current matches.""" return len(hospital.matching) < hospital.capacity or any( [hospital.prefers(resident, match) for match in hospital.matching] ) def _make_players(resident_prefs, hospital_prefs, capacities): """Make a set of residents and hospitals from the dictionaries given, and add their preferences.""" resident_dict, hospital_dict = _make_instances( resident_prefs, hospital_prefs, capacities ) for resident_name, resident in resident_dict.items(): prefs = [hospital_dict[name] for name in resident_prefs[resident_name]] resident.set_prefs(prefs) for hospital_name, hospital in hospital_dict.items(): prefs = [resident_dict[name] for name in hospital_prefs[hospital_name]] hospital.set_prefs(prefs) residents = list(resident_dict.values()) hospitals = list(hospital_dict.values()) return residents, hospitals def _make_instances(resident_prefs, hospital_prefs, capacities): """Create ``Player`` (resident) and ``Hospital`` instances for the names in each dictionary.""" resident_dict, hospital_dict = {}, {} for resident_name in resident_prefs: resident = Resident(name=resident_name) resident_dict[resident_name] = resident for hospital_name in hospital_prefs: capacity = capacities[hospital_name] hospital = Hospital(name=hospital_name, capacity=capacity) hospital_dict[hospital_name] = hospital return resident_dict, hospital_dict
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.7.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] pycharm={"name": "#%% md\n"} # # P1 Edgar data client for REST API # %% [markdown] # ## Initialization # %% pycharm={"is_executing": false, "name": "#%%\n"} # %load_ext autoreload # %autoreload 2 import os import pprint import pandas as pd import edgar.mappers if False: import sys sys.path.append("/commodity_research/p1_data_client_python_private") print(sys.path) os.environ["P1_API_TOKEN"]='e44e7c6b04ef3ea1cfb7a8a67db74751c177259e' os.environ["P1_EDGAR_API_TOKEN"]='8c9c9458b145202c7a6b6cceaabd82023e957a46d6cf7061ed8e1c94a168f2fd' import edgar.edgar_client as p1_edg # Enter your token here. # You can get your token by signing up at `www.particle.one`. # P1_API_TOKEN = "YOUR_TOKEN_HERE" # An example token is like: P1_API_TOKEN = os.environ["P1_EDGAR_API_TOKEN"] print("P1_API_TOKEN=", P1_API_TOKEN) # %% [markdown] # ## Quick start # # There are 3 steps: # 1. Get information about company identifiers # 2. Get information about financial items available # 3. Download data # # ## Mappers # # ### GvkCikMapper # # It handles CIK <-> GVK transformation. # %% pycharm={"is_executing": false, "name": "#%%\n"} gvk_mapper = edgar.mappers.GvkCikMapper(token=P1_API_TOKEN) gvk_mapper.get_gvk_from_cik(cik=940800, as_of_date="2007-01-18") # %% pycharm={"is_executing": false, "name": "#%%\n"} gvk_mapper.get_cik_from_gvk(gvk=61411, as_of_date="2007-01-18") # %% [markdown] # ### ItemMapper # # It provides mapping between keywords and description of Compustat items. # %% pycharm={"is_executing": false, "name": "#%%\n"} item_mapper = edgar.mappers.ItemMapper(token=P1_API_TOKEN) item_mapper.get_item_from_keywords(keywords=["short-term", "short term"]) # %% pycharm={"is_executing": false, "name": "#%%\n"} item_mapper.get_mapping() # %% [markdown] # ## Metadata # %% client = p1_edg.EdgarClient(token=P1_API_TOKEN) # %% def display_df(df: pd.DataFrame) -> None: print("num_rows=%s" % df.shape[0]) display(df.head(3)) def print_payload(payload: str, n: int = 300) -> None: print(pprint.pformat(payload)[:n]) # %% # Get forms for a subset of forms and CIKs. headers = client.get_form_headers( form_type=['13F-HR', '10-K', '3', '4'], cik=[918504, 1048286, 5272, 947263, 1759760, 320193], start_date='2020-10-30', end_date='2020-10-30', ) display_df(headers) # %% # Get forms for a subset of forms and all CIKs for 1 year. headers = client.get_form_headers( form_type=['4'], cik=None, start_date='2020-01-01', end_date='2020-01-31', ) display_df(headers) # %% [markdown] # ## Payload data # %% [markdown] # ### Form8 # %% pycharm={"is_executing": false, "name": "#%%\n"} # Get all Form8 data for one CIK, one item in a range of time. payload = client.get_form8_payload( cik=18498, start_date="2020-01-04", end_date="2020-12-04", item="ACT_QUARTER", ) display_df(payload) # %% pycharm={"is_executing": false, "name": "#%%\n"} # Get all Form8 data for multiple CIK, all items, and entire period of time. payload = client.get_form8_payload(cik=[18498, 319201, 5768]) display_df(payload) # %% [markdown] # ### Form4 # # %% [markdown] # #### Examples of queries # %% pycharm={"is_executing": false} # Initalize the client. client = p1_edg.EdgarClient(token=P1_API_TOKEN) # %% pycharm={"name": "#%%\n"} # Get Form4 data for one CIK and one day, as dataframe. payload = client.get_form4_payload( cik=1524358, start_date="2015-10-23", end_date="2020-10-23", output_type="dataframes" ) # %% payload.keys() # %% display_df(payload['general_info']) # %% # Get Form4 data for one CIK and a week. payload = client.get_form4_payload( cik=1002910, start_date="2015-10-20", end_date="2015-10-27", ) # %% # Get Form4 data for multiple CIKs and a week. payload = client.get_form4_payload( cik=[910521, 883241, 80424], start_date="2020-12-10", end_date="2020-12-17", output_type="dataframes" ) # %% display_df(payload['metadata']) # %% pycharm={"name": "#%%\n"} # Get Form4 data for all companies and one day. payload = client.get_form4_payload( start_date="2020-12-17", end_date="2020-12-17", ) print_payload(payload) # %% [markdown] pycharm={"name": "#%% md\n"} # #### How to handle and show payload data # %% pycharm={"name": "#%%\n"} # Print out a length, and a table names inside a payload. print("len(payload)=%s" % len(payload)) print("payload.keys()=%s" % payload.keys()) # Show a metadata of a payload. print('payload["metadata"]=\n%s' % pprint.pformat(payload["metadata"][:2])) # Print prettified "general_info" table of a payload. print_payload(payload["general_info"]) # %% [markdown] # ### Form13 # %% [markdown] # #### Examples of queries # %% pycharm={"name": "#%%\n"} # Initalize the client. client = p1_edg.EdgarClient(token=<PASSWORD>API_TOKEN) # %% # Get Form13 data for one filer as CIK and one day. payload = client.get_form13_payload( cik=1259313, start_date="2015-11-16", end_date="2015-11-16", ) display_df(payload['metadata']) # %% pycharm={"is_executing": false, "name": "#%%\n"} # Get Form13 data for one filed company as CUSIP and one day. payload = client.get_form13_payload( cusip="01449J204", start_date="2015-11-16", end_date="2015-11-16" ) print_payload(payload) # %% pycharm={"name": "#%%\n"} # Get Form13 data for a list of CUSIPs and one day. payload = client.get_form13_payload( cusip=["002824100", "01449J204"], start_date="2016-11-15", end_date="2016-11-15", output_type="dataframes" ) print_payload(payload) # %% [markdown] # #### How to handle and show payload data # %% pycharm={"name": "#%%\n"} # Print out a length, and a table names inside a payload. print("len(payload)=%s" % len(payload)) print("payload.keys()=%s" % payload.keys()) # %% pycharm={"name": "#%%\n"} # Show a metadata of a payload. display_df(payload["metadata"]) # %% [markdown] # ### Form10 # %% # Get Form10 data for one CIK and 2 days. payload = client.get_form10_payload( cik=1002910, start_date="2020-05-11", end_date="2020-05-12", ) # %% print("len(payload)=%s" % len(payload)) print("payload[0].keys()=%s" % payload[0].keys()) # %% print('payload[0]["meta"]=\n%s' % pprint.pformat(payload[0]["meta"])) # %% json_str = payload[0]["data"] print(pprint.pformat(payload[0]["data"])[:2000])
<gh_stars>1000+ # Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import decorators from telemetry.internal.actions import page_action from telemetry.internal.actions import scroll from telemetry.internal.actions import utils from telemetry.testing import tab_test_case class ScrollActionTest(tab_test_case.TabTestCase): def _MakePageVerticallyScrollable(self): # Make page taller than window so it's scrollable vertically. self._tab.ExecuteJavaScript( 'document.body.style.height =' '(3 * __GestureCommon_GetWindowHeight() + 1) + "px";') def _MakePageHorizontallyScrollable(self): # Make page wider than window so it's scrollable horizontally. self._tab.ExecuteJavaScript( 'document.body.style.width =' '(3 * __GestureCommon_GetWindowWidth() + 1) + "px";') def setUp(self): tab_test_case.TabTestCase.setUp(self) self.Navigate('blank.html') utils.InjectJavaScript(self._tab, 'gesture_common.js') def _RunScrollDistanceTest(self, distance, speed, source, maxError): # TODO(bokan): Distance tests will fail on versions of Chrome that haven't # been fixed. The fixes landed at the same time as the # setBrowserControlsShown method was added so only run the test if that's # available. Once that rolls into ref builds we can remove this check. distanceFixedInChrome = self._tab.EvaluateJavaScript( "'setBrowserControlsShown' in chrome.gpuBenchmarking") if not distanceFixedInChrome: return # Hide the URL bar so we can measure scrolled distance without worrying # about the URL bar consuming delta. self._tab.ExecuteJavaScript( 'chrome.gpuBenchmarking.setBrowserControlsShown(false);') # Make the document tall enough to accomodate the requested distance but # also leave enough space so we can tell if the scroll overshoots the # target. screenHeight = self._tab.EvaluateJavaScript('window.visualViewport.height') documentHeight = (screenHeight + distance) * 2 self._tab.ExecuteJavaScript( 'document.body.style.height = "' + str(documentHeight) + 'px";') self.assertEquals( self._tab.EvaluateJavaScript('document.scrollingElement.scrollTop'), 0) # Allow for some visual viewport offset. For example, if the test doesn't # want any visual viewport offset due to animation handoff error between # the two viewports. start_offset = self._tab.EvaluateJavaScript('window.visualViewport.pageTop') i = scroll.ScrollAction( distance=distance, direction="down", speed_in_pixels_per_second=speed, synthetic_gesture_source=source) i.WillRunAction(self._tab) i.RunAction(self._tab) actual = self._tab.EvaluateJavaScript( 'window.visualViewport.pageTop') - start_offset # TODO(bokan): setBrowserControlsShown isn't quite enough. Chrome will hide # the browser controls but then they animate in after a timeout. We'll need # to add a way to lock them to hidden. Until then, just increase the # allowed error. urlBarError = 150 self.assertAlmostEqual(distance, actual, delta=maxError + urlBarError) def testScrollDistanceFastTouch(self): # Just pass the test on platforms that don't support touch (i.e. Mac) if not page_action.IsGestureSourceTypeSupported(self._tab, 'touch'): return # Scrolling distance for touch will have some error from the excess delta # of the event that crosses the slop threshold but isn't applied. self._RunScrollDistanceTest( 500000, 200000, page_action.GESTURE_SOURCE_TOUCH, 50) def testScrollDistanceFastWheel(self): # Wheel scrolling will have a much greater error than touch. There's 2 # reasons: 1) synthetic wheel gesture accumulate the sent deltas and use # that to determine how much delta to send at each event dispatch time. # This assumes that the entire sent delta is applied which is wrong due to # physical pixel snapping which accumulates over the gesture. # 2) We can only send delta as ticks of the wheel. If the total delta is # not a multiple of the tick size, we'll "lose" the remainder. self._RunScrollDistanceTest( 500000, 200000, page_action.GESTURE_SOURCE_MOUSE, 15000) def testScrollDistanceSlowTouch(self): # Just pass the test on platforms that don't support touch (i.e. Mac) if not page_action.IsGestureSourceTypeSupported(self._tab, 'touch'): return # Scrolling slowly produces larger error since each event will have a # smaller delta. Thus error from snapping in each event will be a larger # share of the total delta. self._RunScrollDistanceTest( 1000, 300, page_action.GESTURE_SOURCE_TOUCH, 10) def testScrollDistanceSlowWheel(self): self._RunScrollDistanceTest( 1000, 300, page_action.GESTURE_SOURCE_MOUSE, 100) @decorators.Disabled('chromeos', 'linux') # crbug.com/805523 @decorators.Disabled('win-reference') # crbug.com/805523 def testWheelScrollDistanceWhileZoomed(self): # TODO(bokan): This API was added recently so only run the test once it's # available. Remove this check once it rolls into stable builds. chromeSupportsSetPageScaleFactor = self._tab.EvaluateJavaScript( "'setPageScaleFactor' in chrome.gpuBenchmarking") if not chromeSupportsSetPageScaleFactor: return self._tab.EvaluateJavaScript('chrome.gpuBenchmarking.setPageScaleFactor(2)') # Wheel scrolling can cause animated scrolls. This is a problem here since # Chrome currently doesn't hand off the animation between the visual and # layout viewports. To account for this, scroll the visual viewport to it's # maximum extent so that the entire scroll goes to the layout viewport. screenHeight = self._tab.EvaluateJavaScript('window.visualViewport.height') i = scroll.ScrollAction( distance=screenHeight*2, direction="down", speed_in_pixels_per_second=5000, synthetic_gesture_source=page_action.GESTURE_SOURCE_MOUSE) i.WillRunAction(self._tab) i.RunAction(self._tab) # Ensure the layout viewport isn't scrolled but the visual is. self.assertGreater( self._tab.EvaluateJavaScript('window.visualViewport.offsetTop'), screenHeight / 2 - 1) self.assertEqual(self._tab.EvaluateJavaScript('window.scrollY'), 0) self._RunScrollDistanceTest( 2000, 2000, page_action.GESTURE_SOURCE_MOUSE, 60) def testTouchScrollDistanceWhileZoomed(self): # Just pass the test on platforms that don't support touch (i.e. Mac) if not page_action.IsGestureSourceTypeSupported(self._tab, 'touch'): return # TODO(bokan): This API was added recently so only run the test once it's # available. Remove this check once it rolls into stable builds. chromeSupportsSetPageScaleFactor = self._tab.EvaluateJavaScript( "'setPageScaleFactor' in chrome.gpuBenchmarking") if not chromeSupportsSetPageScaleFactor: return self._tab.EvaluateJavaScript('chrome.gpuBenchmarking.setPageScaleFactor(2)') self._RunScrollDistanceTest( 2000, 2000, page_action.GESTURE_SOURCE_TOUCH, 20) def testScrollAction(self): self._MakePageVerticallyScrollable() self.assertEquals( self._tab.EvaluateJavaScript('document.scrollingElement.scrollTop'), 0) i = scroll.ScrollAction() i.WillRunAction(self._tab) self._tab.ExecuteJavaScript(""" window.__scrollAction.beginMeasuringHook = function() { window.__didBeginMeasuring = true; }; window.__scrollAction.endMeasuringHook = function() { window.__didEndMeasuring = true; };""") i.RunAction(self._tab) self.assertTrue(self._tab.EvaluateJavaScript('window.__didBeginMeasuring')) self.assertTrue(self._tab.EvaluateJavaScript('window.__didEndMeasuring')) scroll_position = self._tab.EvaluateJavaScript( 'document.scrollingElement.scrollTop') self.assertTrue( scroll_position != 0, msg='scroll_position=%d;' % (scroll_position)) # https://github.com/catapult-project/catapult/issues/3099 @decorators.Disabled('android') def testDiagonalScrollAction(self): # Diagonal scrolling was not supported in the ScrollAction until Chrome # branch number 2332 branch_num = self._tab.browser._browser_backend.devtools_client \ .GetChromeBranchNumber() if branch_num < 2332: return self._MakePageVerticallyScrollable() self.assertEquals( self._tab.EvaluateJavaScript('document.scrollingElement.scrollTop'), 0) self._MakePageHorizontallyScrollable() self.assertEquals( self._tab.EvaluateJavaScript('document.scrollingElement.scrollLeft'), 0) i = scroll.ScrollAction(direction='downright') i.WillRunAction(self._tab) i.RunAction(self._tab) viewport_top = self._tab.EvaluateJavaScript( 'document.scrollingElement.scrollTop') self.assertTrue(viewport_top != 0, msg='viewport_top=%d;' % viewport_top) viewport_left = self._tab.EvaluateJavaScript( 'document.scrollingElement.scrollLeft') self.assertTrue(viewport_left != 0, msg='viewport_left=%d;' % viewport_left) def testBoundingClientRect(self): # Verify that the rect returned by getBoundingVisibleRect() in scroll.js is # completely contained within the viewport. Scroll events dispatched by the # scrolling API use the center of this rect as their location, and this # location needs to be within the viewport bounds to correctly decide # between main-thread and impl-thread scroll. If the scrollable area were # not clipped to the viewport bounds, then the instance used here (the # scrollable area being more than twice as tall as the viewport) would # result in a scroll location outside of the viewport bounds. self._MakePageVerticallyScrollable() self.assertEquals( self._tab.EvaluateJavaScript('document.scrollingElement.scrollTop'), 0) self._MakePageHorizontallyScrollable() self.assertEquals( self._tab.EvaluateJavaScript('document.scrollingElement.scrollLeft'), 0) self._tab.ExecuteJavaScript(""" window.scrollTo(__GestureCommon_GetWindowWidth(), __GestureCommon_GetWindowHeight());""") rect_top = int( self._tab.EvaluateJavaScript( '__GestureCommon_GetBoundingVisibleRect(document.body).top')) rect_height = int( self._tab.EvaluateJavaScript( '__GestureCommon_GetBoundingVisibleRect(document.body).height')) rect_bottom = rect_top + rect_height rect_left = int( self._tab.EvaluateJavaScript( '__GestureCommon_GetBoundingVisibleRect(document.body).left')) rect_width = int( self._tab.EvaluateJavaScript( '__GestureCommon_GetBoundingVisibleRect(document.body).width')) rect_right = rect_left + rect_width viewport_height = int( self._tab.EvaluateJavaScript('__GestureCommon_GetWindowHeight()')) viewport_width = int( self._tab.EvaluateJavaScript('__GestureCommon_GetWindowWidth()')) self.assertTrue(rect_top >= 0, msg='%s >= %s' % (rect_top, 0)) self.assertTrue(rect_left >= 0, msg='%s >= %s' % (rect_left, 0)) self.assertTrue( rect_bottom <= viewport_height, msg='%s + %s <= %s' % (rect_top, rect_height, viewport_height)) self.assertTrue( rect_right <= viewport_width, msg='%s + %s <= %s' % (rect_left, rect_width, viewport_width))
import random from classes.command import command from classes.module import Module from utils.getch import getch class Battle(Module): """ The battle begins... """ def __init__(self, handler): self.handler = handler @command(description="The deadly battle.", usage="battle <difficulty>") def battle(self, ctx, difficulty: int): """ The deadly battle begins... Choose a difficulty between 1 and 5. Get coins when you succeed! The more difficult, the more coins you get. """ if difficulty < 1 or difficulty > 5: return ctx.print("Please choose a difficulty between 1 and 5.") field = [ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], ] boss_row = random.randint(0, 4) boss_column = random.randint(0, 4) field[boss_row][boss_column] = 1 player_row = random.randint(0, 4) player_column = random.randint(0, 4) field[player_row][player_column] = 2 if player_row == boss_row and player_column == boss_column: ctx.print("Oh, it looks like the boss is eager to fight with you.") ctx.print("They have come to you...") else: def print_field(field): ctx.print_empty() for row in field: for column in row: if column == 0: ctx.print("•", end=" ") elif column == 1: ctx.print("X", end=" ") else: ctx.print("O", end=" ") ctx.print_empty() move_speed = 6 - difficulty ctx.print("Before the battle starts, you need to catch the boss.") ctx.print( f"The boss will move every {move_speed} times you move to a random location." ) ctx.print('You are represented "O" and the boss is represented by "X".') ctx.print(f"Use [w] [a] [s] [d] to move.") print_field(field) end = False moves = 0 while not end: ctx.print("\nEnter a move: ", end="") try: movement = getch().lower() except UnicodeDecodeError: return ctx.print( "Uh oh, you entered an invalid character. Battle ends..." ) ctx.print(f"{movement}") ctx.print_empty() if movement not in ["w", "a", "s", "d"]: return ctx.print( "Uh oh, you entered an invalid movement. Battle ends..." ) if ( (movement == "w" and player_row == 0) or (movement == "a" and player_column == 0) or (movement == "s" and player_row == 4) or (movement == "d" and player_column == 4) ): return ctx.print("Uh oh, you bumped into the wall. Battle ends...") field[player_row][player_column] = 0 if movement == "w": player_row -= 1 elif movement == "a": player_column -= 1 elif movement == "s": player_row += 1 elif movement == "d": player_column += 1 if field[player_row][player_column] == 1: end = True else: field[player_row][player_column] = 2 print_field(field) moves += 1 if moves == move_speed: moves = 0 ctx.print_empty() ctx.print("The boss is moving...") field[boss_row][boss_column] = 0 boss_row = random.randint(0, 4) boss_column = random.randint(0, 4) while boss_row == player_row and boss_column == player_column: boss_row = random.randint(0, 4) field[boss_row][boss_column] = 1 print_field(field) ctx.print("You caught the boss!") ctx.print_empty() ctx.print("THE DEADLY BATTLE BEGINS...") ctx.print_empty() character = self.handler.character sword = character.equipped_sword shield = character.equipped_shield boss_hp = difficulty * 100 player_hp = 100 + character.level * 10 while boss_hp > 0 and player_hp > 0: ctx.print(f"Boss HP: {boss_hp}") ctx.print(f"Player HP: {player_hp}") ctx.print_empty() boss_damage = random.randint(difficulty * 15, difficulty * 20) player_damage = random.randint(sword.level * 10, sword.level * 15) player_shield = random.randint(shield.level * 5, shield.level * 10) effective_damage = boss_damage - player_shield if effective_damage < 5: effective_damage = 5 ctx.print(f"The boss attacked and dealt {boss_damage} damage.") ctx.print( f"Because of your shield, effective damage was {effective_damage}." ) player_hp -= effective_damage if player_hp < 0: break ctx.print("Press any key to attack...") getch() boss_hp -= player_damage ctx.print(f"You dealt {player_damage} damage.") ctx.print_empty() if boss_hp < 0: ctx.print("The boss was defeated!") xp = random.randint(difficulty * 15, difficulty * 20) coins = random.randint(difficulty * 15, difficulty * 20) self.handler.character.add_xp(xp) self.handler.character.add_coins(coins) ctx.print(f"You received {xp} XP and {coins} coins.") else: ctx.print("You were defeated! Better luck next time...") def setup(handler): handler.add_module(Battle(handler))
<reponame>zeroos/infdist<filename>infdist/simulator/network.py from collections import defaultdict import json import ns.applications import ns.core import ns.internet import ns.network import ns.mobility import ns.point_to_point import ns.wifi from . import simulator from optimization.models import Message from optimization.network import BaseNetwork class DataTypesStore: def __init__(self): self.data_types = {} self.hashes = {} def get_hash(self, data_type_name): if data_type_name not in self.data_types: h = bytes([len(self.data_types)]) self.data_types[data_type_name] = h self.hashes[h] = data_type_name return self.data_types[data_type_name] def get_data_type_name(self, h): return self.hashes[h] class NS3Network(BaseNetwork): DATA_PORT = 4477 BACKGROUND_PORT = 8082 AVAILABLE_DATA_RATES = { 1: 'DsssRate1Mbps', 2: 'DsssRate2Mbps', 5.5: 'DsssRate5_5Mbps', 11: 'DsssRate11Mbps', } def __init__(self, nodes_num, data_rate=5.5): self.initialized = False self.known_data_types = DataTypesStore() self._message_received_callbacks = defaultdict(set) self.nodes = ns.network.NodeContainer() self.nodes.Create(nodes_num) self.set_data_rate(data_rate) self.background_noise_mode = 'tcp' self.background_noise_history = [] self._init_network() self.sockets = [ ns.network.Socket.CreateSocket( self.nodes.Get(i), ns.core.TypeId.LookupByName("ns3::UdpSocketFactory") ) for i in range(nodes_num) ] any_address = ns.network.InetSocketAddress( ns.network.Ipv4Address.GetAny(), self.DATA_PORT ) broadcast_address = ns.network.InetSocketAddress( ns.network.Ipv4Address.GetBroadcast(), self.DATA_PORT ) for i, socket in enumerate(self.sockets): socket.SetRecvCallback(self._gen_ns3_receive_callback(i)) socket.SetAllowBroadcast(True) socket.Bind(any_address) socket.Connect(broadcast_address) def serialize(self, native_message): return native_message def deserialize(self, message): return message def add_background_traffic_pattern( self, background_traffic_pattern, mode='tcp', ): for t_start, t_end, throughput in zip( background_traffic_pattern.ts[:-1], background_traffic_pattern.ts[1:], background_traffic_pattern.throughputs ): self.add_background_traffic(t_start, t_end, throughput, mode) def add_background_traffic(self, t_start, t_end, throughput, mode='tcp'): """ throughput in Mbps """ assert mode in ('tcp', 'udp') self.background_noise_mode = mode any_address = ns.network.InetSocketAddress( ns.network.Ipv4Address.GetAny(), self.BACKGROUND_PORT ) def source_rcvd(socket): packet = socket.Recv(2048, 0) self.background_noise_history.append( (simulator.now_float(), packet.GetSize()) ) def succeeded(a): # print("Connected") pass def not_succeeded(a): print("ERROR: not connected") def accept_callback(a, b): return True def new_connection(socket, address): socket.SetRecvCallback(source_rcvd) sockets = [] for i in range(1, 3): node = self.nodes.Get(i) socket = ns.network.Socket.CreateSocket( node, ns.core.TypeId.LookupByName( "ns3::TcpSocketFactory" if self.background_noise_mode == 'tcp' else "ns3::UdpSocketFactory" ) ) socket.Bind(any_address) socket.Listen() sockets.append(socket) if self.background_noise_mode != 'tcp': socket.SetRecvCallback(source_rcvd) socket.SetConnectCallback(succeeded, not_succeeded) socket.SetAcceptCallback(accept_callback, new_connection) self.reinit_background_source() self.background_packet_size = 2048 packets = int( throughput*10**6/8*(t_end-t_start)/self.background_packet_size ) for i in range(packets): simulator.schedule( t_start + i/packets * (t_end-t_start), self.send_background_packet ) def reinit_background_source(self): def send_callback(a, b): pass def succeeded(a): # print("Connected") pass def not_succeeded(a): print("ERROR: not connected") source = ns.network.Socket.CreateSocket( self.nodes.Get(0), ns.core.TypeId.LookupByName( "ns3::TcpSocketFactory" if self.background_noise_mode == 'tcp' else "ns3::UdpSocketFactory" ) ) source.SetConnectCallback(succeeded, not_succeeded) source.SetSendCallback(send_callback) self.background_source = source self.connect_background() def send_background_packet(self, size=None): if size is None: size = self.background_packet_size if(self.background_source.GetTxAvailable() < size): self.reinit_background_source() return packet = ns.network.Packet(size) self.background_source.Send(packet, 0) # print(self.background_source.GetErrno()) def connect_background(self): sink_address = ns.network.InetSocketAddress( ns.network.Ipv4Address("10.1.1.2"), self.BACKGROUND_PORT, ) self.background_source.Connect(sink_address) def set_data_rate(self, data_rate): assert not self.initialized, \ "Cannot change data rate after network initialization" assert data_rate in self.AVAILABLE_DATA_RATES, "Unsupported data rate" self.phy_mode = self.AVAILABLE_DATA_RATES[data_rate] def _init_network(self): self.initialized = True rss = -80 wifi = ns.wifi.WifiHelper() wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211g) wifi_phy = ns.wifi.YansWifiPhyHelper.Default() wifi_phy.Set("RxGain", ns.core.DoubleValue(0)) wifi_phy.SetPcapDataLinkType( ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11_RADIO ) wifi_channel = ns.wifi.YansWifiChannelHelper() wifi_channel.SetPropagationDelay( "ns3::ConstantSpeedPropagationDelayModel" ) # fixed RSS regardless of the distance and transmit power wifi_channel.AddPropagationLoss( "ns3::FixedRssLossModel", "Rss", ns.core.DoubleValue(rss) ) wifi_phy.SetChannel(wifi_channel.Create()) # disable rate control wifi.SetRemoteStationManager( "ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue(self.phy_mode), "ControlMode", ns.core.StringValue(self.phy_mode), ) wifi_mac = ns.wifi.WifiMacHelper() wifi_mac.SetType("ns3::AdhocWifiMac") # mobility mobility = ns.mobility.MobilityHelper() positions = ns.mobility.ListPositionAllocator() for i in range(self.nodes.GetN()): positions.Add(ns.mobility.Vector(5*i, int(i/5)*2, 0)) mobility.SetPositionAllocator(positions) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(self.nodes) devices = wifi.Install(wifi_phy, wifi_mac, self.nodes) self._init_ip(devices) def _init_ip(self, devices): stack = ns.internet.InternetStackHelper() stack.Install(self.nodes) address = ns.internet.Ipv4AddressHelper() address.SetBase(ns.network.Ipv4Address("10.1.1.0"), ns.network.Ipv4Mask("255.255.255.0")) address.Assign(devices) def add_message_received_callback(self, callback, node_id): self._message_received_callbacks[node_id].add(callback) def _message_received(self, message, node_id): for callback in self._message_received_callbacks[node_id]: callback(message) def _header2message(self, header, receivers, size): t_gen = header.GetTimestamp()/10**9 return Message( header.GetSender(), receivers=receivers, t_sent=t_gen, data_type_name=self.known_data_types.get_data_type_name( header.GetDataType()), size=size, data=json.loads(header.GetData()), t_gen=t_gen, t_rcv=simulator.now_float(), ) def _gen_ns3_receive_callback(self, node_id): def _ns3_receive_callback(socket): packet = socket.Recv() header = ns.network.InfDistHeader() packet.RemoveHeader(header) # print("rcvd", self._header_repr(header), ns.core.Simulator.Now()) self._message_received( self._header2message(header, {node_id}, packet.GetSize()), node_id, ) return _ns3_receive_callback @staticmethod def _header_repr(header): return '{}@{} from {}; data="{}"'.format( header.GetDataType(), header.GetTimestamp(), header.GetSender(), header.GetData(), ) def send(self, message): packet = ns.network.Packet(message.size) header = ns.network.InfDistHeader() header.SetDataType( self.known_data_types.get_hash(message.data_type_name) ) header.SetTimestamp(simulator.now()) header.SetSender(message.sender) data = json.dumps(vars(message.data)) header.SetData(len(data), data) packet.AddHeader(header) self.sockets[message.sender].Send(packet)
from unittest import TestCase from mockredis import MockRedis, mock_redis_client, mock_strict_redis_client class TestFactories(TestCase): def test_mock_redis_client(self): """ Test that we can pass kwargs to the Redis mock/patch target. """ self.assertFalse(mock_redis_client(host="localhost", port=6379).strict) def test_mock_strict_redis_client(self): """ Test that we can pass kwargs to the StrictRedis mock/patch target. """ self.assertTrue(mock_strict_redis_client(host="localhost", port=6379).strict) class TestRedis(TestCase): def setUp(self): self.redis = MockRedis() self.redis.flushdb() def test_get(self): self.assertEqual(None, self.redis.get('key')) self.redis.redis['key'] = 'value' self.assertEqual('value', self.redis.get('key')) def test_set(self): self.assertEqual(None, self.redis.redis.get('key')) self.redis.set('key', 'value') self.assertEqual('value', self.redis.redis.get('key')) def test_get_types(self): ''' testing type coversions for set/get, hset/hget, sadd/smembers Python bools, lists, dicts are returned as strings by redis-py/redis. ''' values = list([ True, False, [1, '2'], { 'a': 1, 'b': 'c' }, ]) self.assertEqual(None, self.redis.get('key')) for value in values: self.redis.set('key', value) self.assertEqual(str(value), self.redis.get('key'), "redis.get") self.redis.hset('hkey', 'item', value) self.assertEqual(str(value), self.redis.hget('hkey', 'item')) self.redis.sadd('skey', value) self.assertEqual(set([str(value)]), self.redis.smembers('skey')) self.redis.flushdb() def test_incr(self): ''' incr, hincr when keys exist ''' values = list([ (1, '2'), ('1', '2'), ]) for value in values: self.redis.set('key', value[0]) self.redis.incr('key') self.assertEqual(value[1], self.redis.get('key'), "redis.incr") self.redis.hset('hkey', 'attr', value[0]) self.redis.hincrby('hkey', 'attr') self.assertEqual(value[1], self.redis.hget('hkey', 'attr'), "redis.hincrby") self.redis.flushdb() def test_incr_init(self): ''' incr, hincr, decr when keys do NOT exist ''' self.redis.incr('key') self.assertEqual('1', self.redis.get('key')) self.redis.hincrby('hkey', 'attr') self.assertEqual('1', self.redis.hget('hkey', 'attr')) self.redis.decr('dkey') self.assertEqual('-1', self.redis.get('dkey')) def test_ttl(self): self.redis.set('key', 'key') self.redis.expire('key', 30) assert self.redis.ttl('key') <= 30 self.assertEqual(self.redis.ttl('invalid_key'), -1) def test_push_pop_returns_str(self): key = 'l' values = ['5', 5, [], {}] for v in values: self.redis.rpush(key, v) self.assertEquals(self.redis.lpop(key), str(v)) #### SET TESTS #### def test_sadd(self): key = "set" values = ["one", "uno", "two", "three"] for value in values: self.assertEquals(1, self.redis.sadd(key, value)) def test_sadd_multiple(self): key = "set" values = ["one", "uno", "two", "three"] self.assertEquals(4, self.redis.sadd(key, *values)) def test_sadd_duplicate_key(self): key = "set" self.assertEquals(1, self.redis.sadd(key, "one")) self.assertEquals(0, self.redis.sadd(key, "one")) def test_scard(self): key = "set" self.assertEquals(0, self.redis.scard(key)) self.assertFalse(key in self.redis.redis) values = ["one", "uno", "two", "three"] self.assertEquals(4, self.redis.sadd(key, *values)) self.assertEquals(4, self.redis.scard(key)) def test_sdiff(self): self.redis.sadd("x", "one", "two", "three") self.redis.sadd("y", "one") self.redis.sadd("z", "two") with self.assertRaises(Exception): self.redis.sdiff([]) self.assertEquals(set(), self.redis.sdiff("w")) self.assertEquals(set(["one", "two", "three"]), self.redis.sdiff("x")) self.assertEquals(set(["two", "three"]), self.redis.sdiff("x", "y")) self.assertEquals(set(["two", "three"]), self.redis.sdiff(["x", "y"])) self.assertEquals(set(["three"]), self.redis.sdiff("x", "y", "z")) self.assertEquals(set(["three"]), self.redis.sdiff(["x", "y"], "z")) def test_sdiffstore(self): self.redis.sadd("x", "one", "two", "three") self.redis.sadd("y", "one") self.redis.sadd("z", "two") with self.assertRaises(Exception): self.redis.sdiffstore("w", []) self.assertEquals(3, self.redis.sdiffstore("w", "x")) self.assertEquals(set(["one", "two", "three"]), self.redis.smembers("w")) self.assertEquals(2, self.redis.sdiffstore("w", "x", "y")) self.assertEquals(set(["two", "three"]), self.redis.smembers("w")) self.assertEquals(2, self.redis.sdiffstore("w", ["x", "y"])) self.assertEquals(set(["two", "three"]), self.redis.smembers("w")) self.assertEquals(1, self.redis.sdiffstore("w", "x", "y", "z")) self.assertEquals(set(["three"]), self.redis.smembers("w")) self.assertEquals(1, self.redis.sdiffstore("w", ["x", "y"], "z")) self.assertEquals(set(["three"]), self.redis.smembers("w")) def test_sinter(self): self.redis.sadd("x", "one", "two", "three") self.redis.sadd("y", "one") self.redis.sadd("z", "two") with self.assertRaises(Exception): self.redis.sinter([]) self.assertEquals(set(), self.redis.sinter("w")) self.assertEquals(set(["one", "two", "three"]), self.redis.sinter("x")) self.assertEquals(set(["one"]), self.redis.sinter("x", "y")) self.assertEquals(set(["two"]), self.redis.sinter(["x", "z"])) self.assertEquals(set(), self.redis.sinter("x", "y", "z")) self.assertEquals(set(), self.redis.sinter(["x", "y"], "z")) def test_sinterstore(self): self.redis.sadd("x", "one", "two", "three") self.redis.sadd("y", "one") self.redis.sadd("z", "two") with self.assertRaises(Exception): self.redis.sinterstore("w", []) self.assertEquals(3, self.redis.sinterstore("w", "x")) self.assertEquals(set(["one", "two", "three"]), self.redis.smembers("w")) self.assertEquals(1, self.redis.sinterstore("w", "x", "y")) self.assertEquals(set(["one"]), self.redis.smembers("w")) self.assertEquals(1, self.redis.sinterstore("w", ["x", "z"])) self.assertEquals(set(["two"]), self.redis.smembers("w")) self.assertEquals(0, self.redis.sinterstore("w", "x", "y", "z")) self.assertEquals(set(), self.redis.smembers("w")) self.assertEquals(0, self.redis.sinterstore("w", ["x", "y"], "z")) self.assertEquals(set(), self.redis.smembers("w")) def test_sismember(self): key = "set" self.assertEquals(0, self.redis.sismember(key, "one")) self.assertFalse(key in self.redis.redis) self.assertEquals(1, self.redis.sadd(key, "one")) self.assertEquals(1, self.redis.sismember(key, "one")) self.assertEquals(0, self.redis.sismember(key, "two")) def test_smembers(self): key = "set" self.assertEquals(set(), self.redis.smembers(key)) self.assertFalse(key in self.redis.redis) self.assertEquals(1, self.redis.sadd(key, "one")) self.assertEquals(set(["one"]), self.redis.smembers(key)) self.assertEquals(1, self.redis.sadd(key, "two")) self.assertEquals(set(["one", "two"]), self.redis.smembers(key)) def test_smove(self): self.assertEquals(0, self.redis.smove("x", "y", "one")) self.assertEquals(2, self.redis.sadd("x", "one", "two")) self.assertEquals(set(["one", "two"]), self.redis.smembers("x")) self.assertEquals(set(), self.redis.smembers("y")) self.assertEquals(0, self.redis.smove("x", "y", "three")) self.assertEquals(set(["one", "two"]), self.redis.smembers("x")) self.assertEquals(set(), self.redis.smembers("y")) self.assertEquals(1, self.redis.smove("x", "y", "one")) self.assertEquals(set(["two"]), self.redis.smembers("x")) self.assertEquals(set(["one"]), self.redis.smembers("y")) def test_spop(self): key = "set" self.assertEquals(None, self.redis.spop(key)) self.assertEquals(1, self.redis.sadd(key, "one")) self.assertEquals("one", self.redis.spop(key)) self.assertEquals(0, self.redis.scard(key)) self.assertEquals(1, self.redis.sadd(key, "one")) self.assertEquals(1, self.redis.sadd(key, "two")) first = self.redis.spop(key) self.assertTrue(first in ["one", "two"]) self.assertEquals(1, self.redis.scard(key)) second = self.redis.spop(key) self.assertEquals("one" if first == "two" else "two", second) self.assertEquals(0, self.redis.scard(key)) def test_srandmember(self): key = "set" # count is None self.assertEquals(None, self.redis.srandmember(key)) self.assertEquals(1, self.redis.sadd(key, "one")) self.assertEquals("one", self.redis.srandmember(key)) self.assertEquals(1, self.redis.scard(key)) self.assertEquals(1, self.redis.sadd(key, "two")) self.assertTrue(self.redis.srandmember(key) in ["one", "two"]) self.assertEquals(2, self.redis.scard(key)) # count > 0 self.assertEquals([], self.redis.srandmember("empty", 1)) self.assertTrue(self.redis.srandmember(key, 1)[0] in ["one", "two"]) self.assertEquals(set(["one", "two"]), set(self.redis.srandmember(key, 2))) # count < 0 self.assertEquals([], self.redis.srandmember("empty", -1)) self.assertTrue(self.redis.srandmember(key, -1)[0] in ["one", "two"]) members = self.redis.srandmember(key, -2) self.assertEquals(2, len(members)) for member in members: self.assertTrue(member in ["one", "two"]) def test_srem(self): key = "set" self.assertEquals(0, self.redis.srem(key, "one")) self.assertEquals(3, self.redis.sadd(key, "one", "two", "three")) self.assertEquals(0, self.redis.srem(key, "four")) self.assertEquals(2, self.redis.srem(key, "one", "three")) self.assertEquals(1, self.redis.srem(key, "two", "four")) def test_sunion(self): self.redis.sadd("x", "one", "two", "three") self.redis.sadd("y", "one") self.redis.sadd("z", "two") with self.assertRaises(Exception): self.redis.sunion([]) self.assertEquals(set(), self.redis.sunion("v")) self.assertEquals(set(["one", "two", "three"]), self.redis.sunion("x")) self.assertEquals(set(["one"]), self.redis.sunion("v", "y")) self.assertEquals(set(["one", "two"]), self.redis.sunion(["y", "z"])) self.assertEquals(set(["one", "two", "three"]), self.redis.sunion("x", "y", "z")) self.assertEquals(set(["one", "two", "three"]), self.redis.sunion(["x", "y"], "z")) def test_sunionstore(self): self.redis.sadd("x", "one", "two", "three") self.redis.sadd("y", "one") self.redis.sadd("z", "two") with self.assertRaises(Exception): self.redis.sunionstore("w", []) self.assertEquals(0, self.redis.sunionstore("w", "v")) self.assertEquals(set(), self.redis.smembers("w")) self.assertEquals(3, self.redis.sunionstore("w", "x")) self.assertEquals(set(["one", "two", "three"]), self.redis.smembers("w")) self.assertEquals(1, self.redis.sunionstore("w", "v", "y")) self.assertEquals(set(["one"]), self.redis.smembers("w")) self.assertEquals(2, self.redis.sunionstore("w", ["y", "z"])) self.assertEquals(set(["one", "two"]), self.redis.smembers("w")) self.assertEquals(3, self.redis.sunionstore("w", "x", "y", "z")) self.assertEquals(set(["one", "two", "three"]), self.redis.smembers("w")) self.assertEquals(3, self.redis.sunionstore("w", ["x", "y"], "z")) self.assertEquals(set(["one", "two", "three"]), self.redis.smembers("w")) #### SORTED SET TESTS #### def test_zadd(self): key = "zset" values = [("one", 1), ("uno", 1), ("two", 2), ("three", 3)] for member, score in values: self.assertEquals(1, self.redis.zadd(key, member, score)) def test_zadd_strict(self): """Argument order for zadd depends on strictness""" self.redis.strict = True key = "zset" values = [("one", 1), ("uno", 1), ("two", 2), ("three", 3)] for member, score in values: self.assertEquals(1, self.redis.zadd(key, score, member)) def test_zadd_duplicate_key(self): key = "zset" self.assertEquals(1, self.redis.zadd(key, "one", 1.0)) self.assertEquals(0, self.redis.zadd(key, "one", 2.0)) def test_zadd_wrong_type(self): key = "zset" self.redis.set(key, "value") with self.assertRaises(Exception): self.redis.zadd(key, "one", 2.0) def test_zadd_multiple_bad_args(self): key = "zset" args = ["one", 1, "two"] with self.assertRaises(Exception): self.redis.zadd(key, *args) def test_zadd_multiple_bad_score(self): key = "zset" with self.assertRaises(Exception): self.redis.zadd(key, "one", "two") def test_zadd_multiple_args(self): key = "zset" args = ["one", 1, "uno", 1, "two", 2, "three", 3] self.assertEquals(4, self.redis.zadd(key, *args)) def test_zadd_multiple_kwargs(self): key = "zset" kwargs = {"one": 1, "uno": 1, "two": 2, "three": 3} self.assertEquals(4, self.redis.zadd(key, **kwargs)) def test_zcard(self): key = "zset" self.assertEquals(0, self.redis.zcard(key)) self.redis.zadd(key, "one", 1) self.assertEquals(1, self.redis.zcard(key)) self.redis.zadd(key, "one", 2) self.assertEquals(1, self.redis.zcard(key)) self.redis.zadd(key, "two", 2) self.assertEquals(2, self.redis.zcard(key)) def test_zincrby(self): key = "zset" self.assertEquals(1.0, self.redis.zincrby(key, "member1")) self.assertEquals(2.0, self.redis.zincrby(key, "member2", 2)) self.assertEquals(-1.0, self.redis.zincrby(key, "member1", -2)) def test_zrange(self): key = "zset" self.assertEquals([], self.redis.zrange(key, 0, -1)) self.redis.zadd(key, "one", 1.5) self.redis.zadd(key, "two", 2.5) self.redis.zadd(key, "three", 3.5) # full range self.assertEquals(["one", "two", "three"], self.redis.zrange(key, 0, -1)) # withscores self.assertEquals([("one", 1.5), ("two", 2.5), ("three", 3.5)], self.redis.zrange(key, 0, -1, withscores=True)) # score_cast_func self.assertEquals([("one", 1), ("two", 2), ("three", 3)], self.redis.zrange(key, 0, -1, withscores=True, score_cast_func=int)) # positive ranges self.assertEquals(["one"], self.redis.zrange(key, 0, 0)) self.assertEquals(["one", "two"], self.redis.zrange(key, 0, 1)) self.assertEquals(["one", "two", "three"], self.redis.zrange(key, 0, 2)) self.assertEquals(["one", "two", "three"], self.redis.zrange(key, 0, 3)) self.assertEquals(["two", "three"], self.redis.zrange(key, 1, 2)) self.assertEquals(["three"], self.redis.zrange(key, 2, 3)) # negative ends self.assertEquals(["one", "two", "three"], self.redis.zrange(key, 0, -1)) self.assertEquals(["one", "two"], self.redis.zrange(key, 0, -2)) self.assertEquals(["one"], self.redis.zrange(key, 0, -3)) self.assertEquals([], self.redis.zrange(key, 0, -4)) # negative starts self.assertEquals([], self.redis.zrange(key, -1, 0)) self.assertEquals(["three"], self.redis.zrange(key, -1, -1)) self.assertEquals(["two", "three"], self.redis.zrange(key, -2, -1)) self.assertEquals(["one", "two", "three"], self.redis.zrange(key, -3, -1)) self.assertEquals(["one", "two", "three"], self.redis.zrange(key, -4, -1)) # desc self.assertEquals(["three", "two", "one"], self.redis.zrange(key, 0, 2, desc=True)) self.assertEquals(["two", "one"], self.redis.zrange(key, 1, 2, desc=True)) self.assertEquals(["three", "two"], self.redis.zrange(key, 0, 1, desc=True)) def test_zrem(self): key = "zset" self.assertFalse(self.redis.zrem(key, "two")) self.redis.zadd(key, "one", 1.0) self.assertEquals(1, self.redis.zcard(key)) self.assertTrue(self.redis.zrem(key, "one")) self.assertEquals(0, self.redis.zcard(key)) def test_zscore(self): key = "zset" self.assertEquals(None, self.redis.zscore(key, "one")) self.redis.zadd(key, "one", 1.0) self.assertEquals(1.0, self.redis.zscore(key, "one")) def test_zrank(self): key = "zset" self.assertEquals(None, self.redis.zrank(key, "two")) self.redis.zadd(key, "one", 1.0) self.redis.zadd(key, "two", 2.0) self.assertEquals(0, self.redis.zrank(key, "one")) self.assertEquals(1, self.redis.zrank(key, "two")) def test_zcount(self): key = "zset" self.assertEquals(0, self.redis.zcount(key, "-inf", "inf")) self.redis.zadd(key, "one", 1.0) self.redis.zadd(key, "two", 2.0) self.assertEquals(2, self.redis.zcount(key, "-inf", "inf")) self.assertEquals(1, self.redis.zcount(key, "-inf", 1.0)) self.assertEquals(1, self.redis.zcount(key, "-inf", 1.5)) self.assertEquals(2, self.redis.zcount(key, "-inf", 2.0)) self.assertEquals(2, self.redis.zcount(key, "-inf", 2.5)) self.assertEquals(1, self.redis.zcount(key, 0.5, 1.0)) self.assertEquals(1, self.redis.zcount(key, 0.5, 1.5)) self.assertEquals(2, self.redis.zcount(key, 0.5, 2.0)) self.assertEquals(2, self.redis.zcount(key, 0.5, 2.5)) self.assertEquals(2, self.redis.zcount(key, 0.5, "inf")) self.assertEquals(0, self.redis.zcount(key, "inf", "-inf")) self.assertEquals(0, self.redis.zcount(key, 2.0, 0.5)) def test_zrangebyscore(self): key = "zset" self.assertEquals([], self.redis.zrangebyscore(key, "-inf", "inf")) self.redis.zadd(key, "one", 1.5) self.redis.zadd(key, "two", 2.5) self.redis.zadd(key, "three", 3.5) self.assertEquals(["one", "two", "three"], self.redis.zrangebyscore(key, "-inf", "inf")) self.assertEquals([("one", 1.5), ("two", 2.5), ("three", 3.5)], self.redis.zrangebyscore(key, "-inf", "inf", withscores=True)) self.assertEquals([("one", 1), ("two", 2), ("three", 3)], self.redis.zrangebyscore(key, "-inf", "inf", withscores=True, score_cast_func=int)) self.assertEquals(["one"], self.redis.zrangebyscore(key, 1.0, 2.0)) self.assertEquals(["one", "two"], self.redis.zrangebyscore(key, 1.0, 3.0)) self.assertEquals(["one"], self.redis.zrangebyscore(key, 1.0, 3.0, start=0, num=1)) self.assertEquals(["two"], self.redis.zrangebyscore(key, 1.0, 3.0, start=1, num=1)) self.assertEquals(["two", "three"], self.redis.zrangebyscore(key, 1.0, 3.5, start=1, num=4)) self.assertEquals([], self.redis.zrangebyscore(key, 1.0, 3.5, start=3, num=4)) def test_zremrank(self): key = "zset" self.assertEquals(None, self.redis.zrevrank(key, "two")) self.redis.zadd(key, "one", 1.0) self.redis.zadd(key, "two", 2.0) self.assertEquals(1, self.redis.zrevrank(key, "one")) self.assertEquals(0, self.redis.zrevrank(key, "two")) def test_zrevrangebyscore(self): key = "zset" self.assertEquals([], self.redis.zrevrangebyscore(key, "inf", "-inf")) self.redis.zadd(key, "one", 1.5) self.redis.zadd(key, "two", 2.5) self.redis.zadd(key, "three", 3.5) self.assertEquals(["three", "two", "one"], self.redis.zrevrangebyscore(key, "inf", "-inf")) self.assertEquals([("three", 3.5), ("two", 2.5), ("one", 1.5)], self.redis.zrevrangebyscore(key, "inf", "-inf", withscores=True)) self.assertEquals([("three", 3), ("two", 2), ("one", 1)], self.redis.zrevrangebyscore(key, "inf", "-inf", withscores=True, score_cast_func=int)) self.assertEquals(["one"], self.redis.zrevrangebyscore(key, 2.0, 1.0)) self.assertEquals(["two", "one"], self.redis.zrevrangebyscore(key, 3.0, 1.0)) self.assertEquals(["two"], self.redis.zrevrangebyscore(key, 3.0, 1.0, start=0, num=1)) self.assertEquals(["one"], self.redis.zrevrangebyscore(key, 3.0, 1.0, start=1, num=1)) self.assertEquals(["two", "one"], self.redis.zrevrangebyscore(key, 3.5, 1.0, start=1, num=4)) self.assertEquals([], self.redis.zrevrangebyscore(key, 3.5, 1.0, start=3, num=4)) def test_zremrangebyrank(self): key = "zset" self.assertEquals(0, self.redis.zremrangebyrank(key, 0, -1)) self.redis.zadd(key, "one", 1.0) self.redis.zadd(key, "two", 2.0) self.redis.zadd(key, "three", 3.0) self.assertEquals(2, self.redis.zremrangebyrank(key, 0, 1)) self.assertEquals(["three"], self.redis.zrange(key, 0, -1)) self.assertEquals(1, self.redis.zremrangebyrank(key, 0, -1)) self.assertEquals([], self.redis.zrange(key, 0, -1)) def test_zremrangebyscore(self): key = "zset" self.assertEquals(0, self.redis.zremrangebyscore(key, "-inf", "inf")) self.redis.zadd(key, "one", 1.0) self.redis.zadd(key, "two", 2.0) self.redis.zadd(key, "three", 3.0) self.assertEquals(1, self.redis.zremrangebyscore(key, 0, 1)) self.assertEquals(["two", "three"], self.redis.zrange(key, 0, -1)) self.assertEquals(2, self.redis.zremrangebyscore(key, 2.0, "inf")) self.assertEquals([], self.redis.zrange(key, 0, -1)) def test_zunionstore(self): key = "zset" # no keys self.assertEquals(0, self.redis.zunionstore(key, ["zset1", "zset2"])) self.redis.zadd("zset1", "one", 1.0) self.redis.zadd("zset1", "two", 2.0) self.redis.zadd("zset2", "two", 2.5) self.redis.zadd("zset2", "three", 3.0) # sum (default) self.assertEquals(3, self.redis.zunionstore(key, ["zset1", "zset2"])) self.assertEquals([("one", 1.0), ("three", 3.0), ("two", 4.5)], self.redis.zrange(key, 0, -1, withscores=True)) self.redis.zadd("zset1", "one", 1.0) self.redis.zadd("zset1", "two", 2.0) self.redis.zadd("zset2", "two", 2.5) self.redis.zadd("zset2", "three", 3.0) # sum (explicit) self.assertEquals(3, self.redis.zunionstore(key, ["zset1", "zset2"], aggregate="sum")) self.assertEquals([("one", 1.0), ("three", 3.0), ("two", 4.5)], self.redis.zrange(key, 0, -1, withscores=True)) self.redis.zadd("zset1", "one", 1.0) self.redis.zadd("zset1", "two", 2.0) self.redis.zadd("zset2", "two", 2.5) self.redis.zadd("zset2", "three", 3.0) # min self.assertEquals(3, self.redis.zunionstore(key, ["zset1", "zset2"], aggregate="min")) self.assertEquals([("one", 1.0), ("two", 2.0), ("three", 3.0)], self.redis.zrange(key, 0, -1, withscores=True)) self.redis.zadd("zset1", "one", 1.0) self.redis.zadd("zset1", "two", 2.0) self.redis.zadd("zset2", "two", 2.5) self.redis.zadd("zset2", "three", 3.0) # max self.assertEquals(3, self.redis.zunionstore(key, ["zset1", "zset2"], aggregate="max")) self.assertEquals([("one", 1.0), ("two", 2.5), ("three", 3.0)], self.redis.zrange(key, 0, -1, withscores=True)) def test_zinterstore(self): key = "zset" # no keys self.assertEquals(0, self.redis.zinterstore(key, ["zset1", "zset2"])) self.redis.zadd("zset1", "one", 1.0) self.redis.zadd("zset1", "two", 2.0) self.redis.zadd("zset2", "two", 2.5) self.redis.zadd("zset2", "three", 3.0) # sum (default) self.assertEquals(1, self.redis.zinterstore(key, ["zset1", "zset2"])) self.assertEquals([("two", 4.5)], self.redis.zrange(key, 0, -1, withscores=True)) self.redis.zadd("zset1", "one", 1.0) self.redis.zadd("zset1", "two", 2.0) self.redis.zadd("zset2", "two", 2.5) self.redis.zadd("zset2", "three", 3.0) # sum (explicit) self.assertEquals(1, self.redis.zinterstore(key, ["zset1", "zset2"], aggregate="sum")) self.assertEquals([("two", 4.5)], self.redis.zrange(key, 0, -1, withscores=True)) self.redis.zadd("zset1", "one", 1.0) self.redis.zadd("zset1", "two", 2.0) self.redis.zadd("zset2", "two", 2.5) self.redis.zadd("zset2", "three", 3.0) # min self.assertEquals(1, self.redis.zinterstore(key, ["zset1", "zset2"], aggregate="min")) self.assertEquals([("two", 2.0)], self.redis.zrange(key, 0, -1, withscores=True)) self.redis.zadd("zset1", "one", 1.0) self.redis.zadd("zset1", "two", 2.0) self.redis.zadd("zset2", "two", 2.5) self.redis.zadd("zset2", "three", 3.0) # max self.assertEquals(1, self.redis.zinterstore(key, ["zset1", "zset2"], aggregate="max")) self.assertEquals([("two", 2.5)], self.redis.zrange(key, 0, -1, withscores=True))
""" SConsGnu.AcDirVarsTests Unit tests for SConsGnu.AcDirVars """ __docformat__ = "restructuredText" # # Copyright (c) 2012-2014 by <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE import unittest from mock import Mock, patch from SConsGnu import AcDirVars from SConsGnu import GVars from SConsGnu import Defaults class Test_default_env_key_transform(unittest.TestCase): def test_default_env_key_prefix(self): self.assertIs(AcDirVars.default_env_key_prefix, Defaults.gvar_env_key_prefix) def test_default_env_key_suffix(self): self.assertIs(AcDirVars.default_env_key_suffix, Defaults.gvar_env_key_suffix) def test_default_env_key_transform(self): self.assertIs(AcDirVars.default_env_key_transform, Defaults.gvar_env_key_transform) class Test_default_var_key_transform(unittest.TestCase): def test_default_var_key_prefix(self): self.assertIs(AcDirVars.default_var_key_prefix, Defaults.gvar_var_key_prefix) def test_default_var_key_suffix(self): self.assertIs(AcDirVars.default_var_key_suffix, Defaults.gvar_var_key_suffix) def test_default_var_key_transform(self): self.assertIs(AcDirVars.default_var_key_transform, Defaults.gvar_var_key_transform) class Test_default_opt_key_transform(unittest.TestCase): def test_default_opt_key_prefix(self): self.assertIs(AcDirVars.default_opt_key_prefix, Defaults.gvar_opt_key_prefix) def test_default_opt_key_suffix(self): self.assertIs(AcDirVars.default_opt_key_suffix, Defaults.gvar_opt_key_suffix) def test_default_opt_key_transform(self): self.assertIs(AcDirVars.default_opt_key_transform, Defaults.gvar_opt_key_transform) class Test_default_opt_name_transform(unittest.TestCase): def test_default_opt_prefix(self): self.assertIs(AcDirVars.default_opt_prefix, Defaults.gvar_opt_prefix) def test_default_opt_name_prefix(self): self.assertIs(AcDirVars.default_opt_name_prefix, Defaults.gvar_opt_name_prefix) def test_default_opt_name_suffix(self): self.assertIs(AcDirVars.default_opt_name_suffix, Defaults.gvar_opt_name_suffix) def test_default_opt_name_transform(self): self.assertIs(AcDirVars.default_opt_name_transform, Defaults.gvar_opt_name_transform) class Test_gvar_names(unittest.TestCase): def test_prefix_in_names(self): """AcDirVars.gvar_names() should contain 'prefix'""" self.assertIn('prefix', AcDirVars.gvar_names()) def test_exec_prefix_in_names(self): self.assertIn('exec_prefix', AcDirVars.gvar_names()) def test_bindir_in_names(self): """AcDirVars.gvar_names() should contain 'bindir'""" self.assertIn('bindir', AcDirVars.gvar_names()) def test_sbindir_in_names(self): """AcDirVars.gvar_names() should contain 'sbindir'""" self.assertIn('sbindir', AcDirVars.gvar_names()) def test_libexecdir_in_names(self): """AcDirVars.gvar_names() should contain 'libexecdir'""" self.assertIn('libexecdir', AcDirVars.gvar_names()) def test_datarootdir_in_names(self): """AcDirVars.gvar_names() should contain 'datarootdir'""" self.assertIn('datarootdir', AcDirVars.gvar_names()) def test_datadir_in_names(self): """AcDirVars.gvar_names() should contain 'datadir'""" self.assertIn('datadir', AcDirVars.gvar_names()) def test_sysconfdir_in_names(self): """AcDirVars.gvar_names() should contain 'sysconfdir'""" self.assertIn('sysconfdir', AcDirVars.gvar_names()) def test_sharedstatedir_in_names(self): """AcDirVars.gvar_names() should contain 'sharedstatedir'""" self.assertIn('sharedstatedir', AcDirVars.gvar_names()) def test_localstatedir_in_names(self): """AcDirVars.gvar_names() should contain 'localstatedir'""" self.assertIn('localstatedir', AcDirVars.gvar_names()) def test_includedir_in_names(self): """AcDirVars.gvar_names() should contain 'includedir'""" self.assertIn('includedir', AcDirVars.gvar_names()) def test_oldincludedir_in_names(self): """AcDirVars.gvar_names() should contain 'oldincludedir'""" self.assertIn('oldincludedir', AcDirVars.gvar_names()) def test_docdir_in_names(self): """AcDirVars.gvar_names() should contain 'docdir'""" self.assertIn('docdir', AcDirVars.gvar_names()) def test_infodir_in_names(self): """AcDirVars.gvar_names() should contain 'infodir'""" self.assertIn('infodir', AcDirVars.gvar_names()) def test_htmldir_in_names(self): """AcDirVars.gvar_names() should contain 'htmldir'""" self.assertIn('htmldir', AcDirVars.gvar_names()) def test_dvidir_in_names(self): """AcDirVars.gvar_names() should contain 'dvidir'""" self.assertIn('dvidir', AcDirVars.gvar_names()) def test_pdfdir_in_names(self): """AcDirVars.gvar_names() should contain 'pdfdir'""" self.assertIn('pdfdir', AcDirVars.gvar_names()) def test_psdir_in_names(self): """AcDirVars.gvar_names() should contain 'psdir'""" self.assertIn('psdir', AcDirVars.gvar_names()) def test_libdir_in_names(self): """AcDirVars.gvar_names() should contain 'libdir'""" self.assertIn('libdir', AcDirVars.gvar_names()) def test_lispdir_in_names(self): """AcDirVars.gvar_names() should contain 'lispdir'""" self.assertIn('lispdir', AcDirVars.gvar_names()) def test_localedir_in_names(self): """AcDirVars.gvar_names() should contain 'localedir'""" self.assertIn('localedir', AcDirVars.gvar_names()) def test_mandir_in_names(self): """AcDirVars.gvar_names() should contain 'mandir'""" self.assertIn('mandir', AcDirVars.gvar_names()) def test_pkgdatadir_in_names(self): """AcDirVars.gvar_names() should contain 'pkgdatadir'""" self.assertIn('pkgdatadir', AcDirVars.gvar_names()) def test_pkgincludedir_in_names(self): """AcDirVars.gvar_names() should contain 'pkgincludedir'""" self.assertIn('pkgincludedir', AcDirVars.gvar_names()) def test_pkglibdir_in_names(self): """AcDirVars.gvar_names() should contain 'pkglibdir'""" self.assertIn('pkglibdir', AcDirVars.gvar_names()) def test_pkglibexecdir_in_names(self): """AcDirVars.gvar_names() should contain 'pkglibexecdir'""" self.assertIn('pkglibexecdir', AcDirVars.gvar_names()) def test_manNdir_in_names(self): """AcDirVars.gvar_names() should contain 'man1dir' .. 'man9dir'""" for d in range(1,10): self.assertIn('man%sdir' % d, AcDirVars.gvar_names()) def test_manNext_in_names(self): """AcDirVars.gvar_names() should contain 'man1ext' .. 'man9ext'""" for d in range(1,10): self.assertIn('man%sext' % d, AcDirVars.gvar_names()) def test_gvar_names_filter(self): """AcDirVars.gvar_names(filter) should use the filter""" self.assertIn('datarootdir', AcDirVars.gvar_names(lambda x : x.startswith('data'))) self.assertIn('datarootdir', AcDirVars.gvar_names(lambda x : x.startswith('data'))) self.assertNotIn('bindir', AcDirVars.gvar_names(lambda x : x.startswith('data'))) self.assertNotIn('pkglibdir', AcDirVars.gvar_names(lambda x : x.startswith('data'))) class Test_declare_gvars(unittest.TestCase): def check_decl(self, name, val): gdecl = AcDirVars.declare_gvars()[name] self.assertEqual(gdecl.get_xxx_default(GVars.VAR), val) self.assertEqual(gdecl.get_xxx_key(GVars.ENV), name) self.assertEqual(gdecl.get_xxx_key(GVars.VAR), name) self.assertEqual(gdecl.get_xxx_key(GVars.OPT), name) def test_prefix(self): """test AcDirVars.declare_gvars()['prefix']""" self.check_decl('prefix', '/usr/local') def test_exec_prefix(self): """test AcDirVars.declare_gvars()['exec_prefix']""" self.check_decl('exec_prefix', '${prefix}') def test_bindir(self): """test AcDirVars.declare_gvars()['bindir']""" self.check_decl('bindir', '${exec_prefix}/bin') def test_sbindir(self): """test AcDirVars.declare_gvars()['sbindir']""" self.check_decl('sbindir', '${exec_prefix}/sbin') def test_libexecdir(self): """test AcDirVars.declare_gvars()['libexecdir']""" self.check_decl('libexecdir', '${exec_prefix}/libexec') def test_datarootdir(self): """test AcDirVars.declare_gvars()['datarootdir']""" self.check_decl('datarootdir', '${prefix}/share') def test_datadir(self): """test AcDirVars.declare_gvars()['datadir']""" self.check_decl('datadir', '${datarootdir}') def test_sysconfdir(self): """test AcDirVars.declare_gvars()['sysconfdir']""" self.check_decl('sysconfdir', '${prefix}/etc') def test_sharedstatedir(self): """test AcDirVars.declare_gvars()['sharedstatedir']""" self.check_decl('sharedstatedir', '${prefix}/com') def test_localstatedir(self): """test AcDirVars.declare_gvars()['localstatedir']""" self.check_decl('localstatedir', '${prefix}/var') def test_includedir(self): """test AcDirVars.declare_gvars()['includedir']""" self.check_decl('includedir', '${prefix}/include') def test_oldincludedir(self): """test AcDirVars.declare_gvars()['oldincludedir']""" self.check_decl('oldincludedir', '/usr/include') def test_docdir(self): """test AcDirVars.declare_gvars()['docdir']""" self.check_decl('docdir', '${datarootdir}/doc/${install_package}') def test_infodir(self): """test AcDirVars.declare_gvars()['infodir']""" self.check_decl('infodir', '${datarootdir}/info') def test_htmldir(self): """test AcDirVars.declare_gvars()['htmldir']""" self.check_decl('htmldir', '${docdir}') def test_dvidir(self): """test AcDirVars.declare_gvars()['dvidir']""" self.check_decl('dvidir', '${docdir}') def test_pdfdir(self): """test AcDirVars.declare_gvars()['pdfdir']""" self.check_decl('pdfdir', '${docdir}') def test_psdir(self): """test AcDirVars.declare_gvars()['psdir']""" self.check_decl('psdir', '${docdir}') def test_libdir(self): """test AcDirVars.declare_gvars()['libdir']""" self.check_decl('libdir', '${exec_prefix}/lib') def test_lispdir(self): """test AcDirVars.declare_gvars()['lispdir']""" self.check_decl('lispdir', '${datarootdir}/emacs/site-lisp') def test_localedir(self): """test AcDirVars.declare_gvars()['localedir']""" self.check_decl('localedir', '${datarootdir}/locale') def test_mandir(self): """test AcDirVars.declare_gvars()['mandir']""" self.check_decl('mandir', '${datarootdir}/man') def test_pkgdatadir(self): """test AcDirVars.declare_gvars()['pkgdatadir']""" self.check_decl('pkgdatadir', '${datadir}/${package}') def test_pkgincludedir(self): """test AcDirVars.declare_gvars()['pkgincludedir']""" self.check_decl('pkgincludedir', '${includedir}/${package}') def test_pkglibdir(self): """test AcDirVars.declare_gvars()['pkglibdir']""" self.check_decl('pkglibdir', '${libdir}/${package}') def test_pkglibexecdir(self): """test AcDirVars.declare_gvars()['pkglibexecdir']""" self.check_decl('pkglibexecdir', '${libexecdir}/${package}') class Test_GVarNames(unittest.TestCase): def test_GVarNames_1(self): """AcDirVars.GVarNames() should invoke AcDirVars.gvar_names() once""" with patch('SConsGnu.AcDirVars.gvar_names') as gvar_names: AcDirVars.GVarNames() try: gvar_names.assert_called_once_with() except AssertionError as e: self.fail(str(e)) def test_GVarNames_2(self): """AcDirVars.GVarNames(foo = 'FOO', name_filter = 'NAME_FILTER') should invoke AcDirVars.gvar_names(name_filter = 'NAME_FILTER') once""" with patch('SConsGnu.AcDirVars.gvar_names') as gvar_names: AcDirVars.GVarNames(foo = 'FOO', name_filter = 'NAME_FILTER') try: gvar_names.assert_called_once_with(name_filter = 'NAME_FILTER') except AssertionError as e: self.fail(str(e)) class Test_DeclareGVars(unittest.TestCase): def test_DeclareGVars_1(self): """AcDirVars.DeclareGVars() should invoke AcDirVars.declare_gvars() once""" with patch('SConsGnu.AcDirVars.declare_gvars', return_value = 'ok') as declare_gvars: decls = AcDirVars.DeclareGVars() try: declare_gvars.assert_called_once_with() except AssertionError as e: self.fail(str(e)) self.assertIs(decls, 'ok') def test_DeclareGVars_2(self): """AcDirVars.DeclareGVars(foo = 'FOO', name_filter = 'NF', env_key_transform = 'EKT', var_key_transform = 'VKT', opt_key_transform = 'OKT', opt_name_transform = 'ONT')""" with patch('SConsGnu.AcDirVars.declare_gvars', return_value = 'ok') as declare_gvars: decls = AcDirVars.DeclareGVars(foo = 'FOO', name_filter = 'NF', env_key_transform = 'EKT', var_key_transform = 'VKT', opt_key_transform = 'OKT', opt_name_transform = 'ONT') try: declare_gvars.assert_called_once_with(name_filter = 'NF', env_key_transform = 'EKT', var_key_transform = 'VKT', opt_key_transform = 'OKT', opt_name_transform = 'ONT') except AssertionError as e: self.fail(str(e)) self.assertIs(decls, 'ok') if __name__ == "__main__": ldr = unittest.TestLoader() suite = unittest.TestSuite() # Load tests to test suite tclasses = [ Test_default_env_key_transform , Test_default_var_key_transform , Test_default_opt_key_transform , Test_default_opt_name_transform , Test_gvar_names , Test_declare_gvars , Test_GVarNames , Test_DeclareGVars ] for tclass in tclasses: suite.addTests(ldr.loadTestsFromTestCase(tclass)) if not unittest.TextTestRunner(verbosity = 2).run(suite).wasSuccessful(): sys.exit(1) # Local Variables: # # tab-width:4 # # indent-tabs-mode:nil # # End: # vim: set syntax=python expandtab tabstop=4 shiftwidth=4:
<gh_stars>0 import time from typing import List, Optional import azure.cognitiveservices.speech as speechsdk from azure.cognitiveservices.speech import speech_py_impl as impl from azure.cognitiveservices.speech.languageconfig import SourceLanguageConfig from microphone import config as cfg class OwnAutoDetectSourceLanguageConfig( speechsdk.languageconfig.AutoDetectSourceLanguageConfig ): """ Superclass of AutoDetectSourceLanguageConfig to disable VSCode's Pylance `Code is unreachable` error. Represents auto detection source language configuration, allowing open range, specifying the potential source languages and corresponding customized endpoint The configuration can be initialized in different ways: - from open range: pass nothing, for source language auto detection in synthesis. - from languages: pass a list of potential source languages, for source language auto detection in recognition. - from sourceLanguageConfigs: pass a list of source language configurations, for source language auto detection in recognition. :param languages: The list of potential source languages. The language is specified in BCP-47 format :param sourceLanguageConfigs: The list of source language configurations """ def __init__( self, languages: List[str] = None, sourceLanguageConfigs: List[SourceLanguageConfig] = None, ) -> None: if languages is not None and sourceLanguageConfigs is not None: raise ValueError( """languages and sourceLanguageConfigs cannot be both specified to create AutoDetectSourceLanguageConfig""" ) self._impl = self._get_impl( impl.AutoDetectSourceLanguageConfig, languages, sourceLanguageConfigs, ) class AzureSpeech: def __init__(self, stream): stream_format = speechsdk.audio.AudioStreamFormat() speech_config = speechsdk.SpeechConfig( subscription=cfg.AZURE_KEY, region=cfg.AZURE_REGION ) audio_config = speechsdk.audio.AudioConfig(stream=stream) auto_lang = OwnAutoDetectSourceLanguageConfig(languages=cfg.AZURE_LANG) self.speech_recognizer = speechsdk.SpeechRecognizer( speech_config, audio_config, auto_detect_source_language_config=auto_lang, ) self.done = False self.speech_recognizer.recognized.connect(self.recognized_callback) self.speech_recognizer.session_started.connect( lambda evt: print("SESSION STARTED: {}".format(evt)) ) self.speech_recognizer.session_stopped.connect( lambda evt: print("SESSION STOPPED {}".format(evt)) ) self.speech_recognizer.canceled.connect( lambda evt: print("CANCELED {}".format(evt)) ) self.speech_recognizer.session_stopped.connect(self.stop_callback) self.speech_recognizer.canceled.connect(self.stop_callback) self.result_ready = False self.result = "" def save_result(self, result: str): self.result = result self.result_ready = True def read_result(self, check_ready=False) -> Optional[str]: """Returns last recognition result. If check_ready is True, returns None if the last results was already read.""" if check_ready and not self.result_ready: return None self.result_ready = False return self.result def start_recog_continuous(self): self.speech_recognizer.start_continuous_recognition() while not self.done: time.sleep(0.5) self.speech_recognizer.stop_continuous_recognition() def recognize_once(self): print("start talking") result = self.speech_recognizer.recognize_once() # Check the result if result.reason == speechsdk.ResultReason.RecognizedSpeech: print("Recognized: {}".format(result.text)) elif result.reason == speechsdk.ResultReason.NoMatch: print( "No speech could be recognized: {}".format( result.no_match_details ) ) elif result.reason == speechsdk.ResultReason.Canceled: cancellation_details = result.cancellation_details print( "Speech Recognition canceled: {}".format( cancellation_details.reason ) ) if ( cancellation_details.reason == speechsdk.CancellationReason.Error ): print( "Error details: {}".format( cancellation_details.error_details ) ) def recognized_callback(self, event): print("RECOGNIZED {}".format(event.result.text)) self.save_result(event.result.text) def stop_callback(self): self.speech_recognizer.stop_continuous_recognition() self.done = True
<filename>motor_driver.py #driver for adafruit PWM servo driver #derived from https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library #uses NXP PCA 9685 16-channel, 12-bit PWM controller #deal with nested file structure... import smbus2.smbus2.smbus2 as smbus2 import math import time #import matplotlib ##need to import this verbose = True #toggle to False to suppress debug output DEVICE_ADDRESS = 0x40 #default pwm driver address PCA9685_SUBADR1 = 0x2 PCA9685_SUBADR2 = 0x3 PCA9685_SUBADR3 = 0x4 PCA9685_MODE1 = 0x0 PCA9685_PRESCALE = 0xFE LED0_ON_L = 0x6 LED0_ON_H = 0x7 LED0_OFF_L = 0x8 LED0_OFF_H = 0x9 ALLLED_ON_L = 0xFA ALLLED_ON_H = 0xFB ALLLED_OFF_L = 0xFC ALLLED_OFF_H = 0xFD pwm_frequency = 500 #desired refresh rate; reset to exact value following setPWMfreq #make sure frequency results in window width that is greater than full_forward width #condition: 1/pwm_frequency*10**6 > full_forward (with some margin) full_reverse = 1100.0 #pulse width in microseconds for full reverse full_forward = 1940.0 #pulse width in microseconds for full forward neutral = 1520.0 #pulse width in microseconds for 0% throttle #resets PWM driver MODE1 registers to default def reset(): verbose_print(MODE1_status()) write_array(PCA9685_MODE1,[0x0, 0x6]) verbose_print('Device has been reset.') verbose_print(MODE1_status()) #given prescale, calculate effective refresh rate; return refresh rate (float) def calculate_refresh_rate(prescale): return 25000000.0 / 4096/(prescale + 1) #follows formula from table 5 of PCA9685 data sheet #given refresh rate, calculate prescale; return prescale (float) def calculate_prescale(refresh_rate): return 25000000.0 / 4096 / refresh_rate - 1 #follows formula from table 5 of PCA9685 data sheet #set refresh rate of PWM driver; return estimated refresh rate in Hz def setPWMfreq(desired_freq): #fix issue where requested frequency is overshot by factor of 1/0.9 frequency_scaling_factor = 0.97 verbose_print('Attempting to set frequency to {0} Hz'.format(desired_freq)) commanded_freq = frequency_scaling_factor*desired_freq prescale = calculate_prescale(commanded_freq) verbose_print('Exact pre-scale is {0}'.format(prescale)) #round to nearest integer value prescale = int(round(prescale)) verbose_print('Prescale rounded to {0}'.format(prescale)) #actual commanded frequency given rounded prescale value commanded_frequency = calculate_refresh_rate(prescale) verbose_print('Frequency to be commanded including correction factor and prescale rounding is {0:.2f} Hz.'.format(commanded_frequency)) estimated_output_frequency = commanded_frequency/frequency_scaling_factor verbose_print('Output frequency will be approximately {0:.2f} Hz'.format(estimated_output_frequency)) oldmode = read8(PCA9685_MODE1) verbose_print(MODE1_status()) newmode = oldmode | 0x10 #enable sleep bit (bit 4) #newmode = (oldmode & 0x7F) | 0x10 #sleep verbose_print("\nSetting newmode to {0:08b}. (Sleep mode)".format(newmode)) write8(PCA9685_MODE1, newmode) verbose_print(MODE1_status()) verbose_print("\nSetting PRESCALE to {0}".format(prescale)) write8(PCA9685_PRESCALE, prescale) verbose_print("PRESCALE now set to: {0}".format(read8(PCA9685_PRESCALE))) verbose_print("\nReverting MODE1 to old mode: {0:08b}".format(oldmode)) write8(PCA9685_MODE1, oldmode) verbose_print(MODE1_status()) time.sleep(0.005) #set MODE1 register to turn on auto increment verbose_print('\nEnabling auto-increment. (Bit 5)') write8(PCA9685_MODE1, oldmode | 0xa0) verbose_print(MODE1_status()) estimated_window_width = 1/estimated_output_frequency*10**6 verbose_print("Estimated window width = 1/estimated_pwm_frequency = {0:.2f}".format(1/estimated_output_frequency*10**6)) if estimated_window_width < full_forward + 50: print 'WARNING! Estimated pwm window width close to or less than 100%% forward throttle pulse duration.\n' print 'Reset PWM frequency to greater than (full forward throttle pulse with)^-1 to avoid issues.' return estimated_output_frequency #convert throttle required to pulse width in microseconds def return_pulse_width_from_counts(counts): return (counts+1)/(pwm_frequency*10.0**(-6)*4096) #convert throttle required to pulse width in microseconds def return_pulse_width_from_throttle(throttle): return (full_forward - full_reverse)/200*(throttle+100) + full_reverse #calculate on counts by linear interpolation between min and max throttle def return_on_counts(throttle): #convert throttle required to pulse width in microseconds pulse_width = return_pulse_width_from_throttle(throttle) #convert pulse width required to number of counts in pwm refresh window counts = pulse_width*pwm_frequency*10**(-6)*4096 - 1 counts = int(round(counts)) #confirm pulse width output after rounding counts to nearest value pulse_width = return_pulse_width_from_counts(counts) verbose_print("Calculated on counts for {0}% throttle: {1} counts".format(throttle, counts)) verbose_print("Approximate pulse width: {0:.0f} us".format(pulse_width)) return [counts, pulse_width] #function to set PWM output using either throttle or counts as input def setPWM(num, throttle = 0, counts = None): #if counts is defined, use this directly #otherwise, calculate counts from throttle if counts: if counts > 4095 or counts < 0: print 'Error: Counts input is {0}. Counts limited to 0 to 4095 inclusive.'.format(counts) return None pulse_width = return_pulse_width_from_counts(counts) else: counts, pulse_width= return_on_counts(throttle) #optional delay time until pulse width begins in binary #must be in 12-bit format on = 10 #in counts, decimal off = counts + on #shift off time by on delay time #verbose_print('Converting variable \'off\' to 12-bit binary representation.') #off = '{0:12b}'.format(off) #verbose_print('Variable \'on\' = {0}'.format(on)) #verbose_print('Variable \'off\' = {0}'.format(off)) verbose_print("Setting PWM {0}: {1}->{2}".format(num, on, off)) #verbose_print("Approximate pulse width: {0} us").format(pulse_width) #note: Each channel has 4 byte addresses for LED_ON_L, #LED_ON_H, LED_OFF_L, and LED_OFF_H. Shifting from LED0_ON_L #by 4*num gets to LED{num}_ON_L. 16-bit on time and off time #are written are written to each of the 4 registers in sequence. #See PCA9865 documentation for more details. start_register = LED0_ON_L + 4*num write_array = [on, on>>8, off, off>>8] #verbose_print('Start register is {0:#03x}'.format(start_register)) #verbose_print('Write Array = {0:012b}, {1:012b}, {2:012b}, {3:012b}'.format(*write_array)) #verbose_print('Writing on and off counts to channel {0}'.format(num)) bus = smbus2.SMBus(1) for i in xrange(4): #verbose_print('Writing write array element {0} = {1:#012b} to register {2:#03x}'.format(i,write_array[i],start_register+i)) bus.write_byte_data(DEVICE_ADDRESS, start_register+i, write_array[i]) #check values were written correctly new_value = bus.read_byte_data(DEVICE_ADDRESS, start_register+i) #verbose_print('Register {0:#03x} value is now {1:#08b}'.format(start_register+i,new_value)) bus.close() #startup routine to enable motor controllers def motor_startup(): #set all 3 channels to neutral setPWM(0,0) setPWM(1,0) setPWM(2,0) setPWM(4,0) #plug in the ESCs!! raw_input('Plug in the power supply. Press enter to continue...') #wait until motor controller starts up #time.sleep(2.0) #move throttle to slightly over 50% setPWM(0,70) setPWM(1,70) setPWM(2,70) setPWM(4,70) def write_array(addr, array): bus = smbus2.SMBus(1) for d in array: bus.write_byte_data(DEVICE_ADDRESS,addr,d) time.sleep(0.010) bus.close() #function to open comm, write data, close comm def write8(addr,d): bus = smbus2.SMBus(1) bus.write_byte_data(DEVICE_ADDRESS,addr,d) bus.close() #function to open comm, read data, close comm def read8(addr): bus = smbus2.SMBus(1) data = bus.read_byte_data(DEVICE_ADDRESS,addr) bus.close() return data #return formatted string of MODE1 register values def MODE1_status(): output = ["MODE1 Status:\n"] mode_1_status = list('{0:08b}'.format(read8(PCA9685_MODE1))) mode_1_registers = ['Restart (bit 7)', 'EXTCLK (bit 6)', 'AI (BIT 5)', 'SLEEP (BIT 4)', 'SUB1 (BIT 3)', 'SUB2 (BIT 2)', 'SUB3 (BIT 1)', 'ALLCALL (BIT 0)'] for b in mode_1_registers: output.append('{0}: {1}\n'.format(b,mode_1_status.pop(0))) output.append('\n') return ''.join(output) #prints debug info if 'verbose' set to True def verbose_print(*arg): if(verbose): for a in arg: print a return None MODE1_status() print '\n' reset() pwm_frequency = setPWMfreq(pwm_frequency) print 'PWM frequency before setting PWM: {0:.02f} Hz'.format(pwm_frequency) motor_startup() def wave(amp, phi, f, t): return amp*math.sin(f*t + phi) setPWM(0,-10) setPWM(1,0) setPWM(2,0) #setPWM(4,-10) ##while True: ## throttle = 80*math.sin(0.1*time.time()) ## setPWM(4,throttle) ## setPWM(0,throttle) #drive motors in wave pi = 3.14159 freq = 0 #wave frequency in Hz freq = 1.0 #wave frequency in radians/s nmotors = 3 while True: for pwmNum in xrange(nmotors): print 'PWM Num = {0}'.format(pwmNum) setPWM(pwmNum,wave(100, 2*pi/nmotors*pwmNum, freq, time.time())) #setPWM(pwmNum,0)
<reponame>ITRI-AIdea/CTSP-job-shop-scheduling # Copyright (c) 2020 Industrial Technology Research Institute. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from bisect import bisect_right import pandas as pd pd.set_option('display.max_rows', None) class Attend(object): """與 attendance 表格對應""" def __init__(self, working): self.routine = working self.routine_today = [] self.idle_today = [] self.total_today = 0 self.is_overnight = False self.routine_nextday = [] self.idle_nextday = [] self.total_nextday = 0 @staticmethod def compute_idle(routine, idle): last = 0 down = 0 if not routine: idle = [] return 0 for p in routine: down += p[0] - last idle.append(down) last = p[1] return routine[-1][1] - down def prepare(self): if self.routine_today: # 處理過 return self r = self.routine if not r: self.routine_today = self.routine self.total_today = Attend.compute_idle(self.routine_today, self.idle_today) return self if r[-1][1] > r[0][0]: # 下班在上班之後 self.routine_today = self.routine self.total_today = Attend.compute_idle(self.routine_today, self.idle_today) return self self.is_overnight = True stop_last = 0 # 最晚的時間點,下一個時間點是凌晨會變小 to_nextday = False for p in self.routine: if to_nextday: self.routine_nextday.append(p) continue if p[0] < stop_last: # 開工在隔天 to_nextday = True self.routine_nextday.append(p) continue stop_last = p[0] # 開工正常,更新最晚 if p[1] < stop_last: # 收工在隔天,分兩段 to_nextday = True self.routine_today.append((p[0], 1440)) self.routine_nextday.append((0, p[1])) continue self.routine_today.append(p) stop_last = p[1] # 收工正常,更新最晚 self.total_nextday = Attend.compute_idle(self.routine_nextday, self.idle_nextday) self.total_today = Attend.compute_idle(self.routine_today, self.idle_today) return self class ManHourOneDay(object): def __init__(self, today, yesterday): self.routine = yesterday.routine_nextday.copy() if yesterday.is_overnight else [] self.idle = yesterday.idle_nextday.copy() if yesterday.is_overnight else [] self.routine += today.routine_today self.idle += [i - yesterday.total_nextday for i in today.idle_today] self.total = yesterday.total_nextday + today.total_today self.sections = [t for p in self.routine for t in p] self.stops = [p[1] for p in self.routine] def valid(self, target): sect = bisect_right(self.sections, target) validity = False if target in self.stops: # last point of prior section validity = True return validity, sect-1 if sect % 2 == 1: validity = True return validity, sect return validity, sect def to_mh(self, minute_of_day): mh = MHCoord(self, minute_of_day) (mh.valid, mh.sect) = self.valid(minute_of_day) return mh class MHCoord(object): """工作時間座標相關""" def __init__(self, day_routine, minute_of_day): self.routine = day_routine self.target = minute_of_day self.valid = False self.sect = -1 self.mhcoord = -1 self.left = -1 def to_available_prev(self): if self.valid: return self.valid if self.sect == 0: return self.valid self.sect -= 1 self.target = self.routine.sections[self.sect] self.valid = True return self.valid def to_available_next(self): if self.valid: return self.valid if self.sect == len(self.routine.sections): return self.valid self.target = self.routine.sections[self.sect] self.sect += 1 self.valid = True return self.valid def get_mhcoord(self): if not self.valid: return self.mhcoord if self.mhcoord >= 0: return self.mhcoord self.mhcoord = self.target - self.routine.idle[self.sect//2] return self.mhcoord def get_leftover(self): if not self.valid: return self.left if self.left >= 0: return self.left self.left = self.routine.total - self.get_mhcoord() return self.left
import numpy as np from numpy import sqrt import scipy.constants as cs import datproc.print as dpr from cooling_unit import c_W, rho_W ## General output = __name__ == '__main__' ## Data I = 2.590 * 5 d_I = 0.010 * 5 U = 11.78 d_U = 0.03 J = 212.0 * cs.milli * cs.liter / cs.minute d_J = 2.0 * cs.milli * cs.liter / cs.minute f = np.array([353.0, 353.0, 353.0]) / cs.minute d_f = np.array([1.0, 1.0, 1.0]) / cs.minute T_out = 25.00 d_T_out = 0.10 T_in = 17.80 d_T_in = 0.10 A = np.array([15236, 15346, 15383]) * cs.hecto * cs.centi**3 ## Data procession f = np.mean(f) d_f = sqrt(np.sum(d_f**2)) / len(d_f) delta_T = T_out - T_in d_delta_T = sqrt(d_T_in**2 + d_T_out**2) d_A = np.std(A) / sqrt(len(A)) A = np.mean(A) ## Evaluation Q_el = I * U / f d_Q_el = Q_el * sqrt((d_I / I)**2 + (d_U / U)**2 + (d_f / f)**2) Q_out = c_W * rho_W * delta_T * J / f d_Q_out = Q_out * sqrt((d_delta_T / delta_T)**2 + (d_J / J)**2 + (d_f / f)**2) W_pV = A d_W_pV = d_A Q_V = Q_el - Q_out - W_pV d_Q_V = sqrt(d_Q_el**2 + d_Q_out**2 + d_W_pV**2) P_el = Q_el * f d_P_el = P_el * sqrt((d_Q_el / Q_el)**2 + (d_f / f)**2) P_out = Q_out * f d_P_out = P_out * sqrt((d_Q_out / Q_out)**2 + (d_f / f)**2) P_pV = W_pV * f d_P_pV = P_pV * sqrt((d_W_pV / W_pV)**2 + (d_f / f)**2) eta_th = W_pV / Q_el d_eta_th = eta_th * sqrt((d_W_pV / W_pV)**2 + (d_Q_el / Q_el)**2) if output: print(dpr.val(Q_el, d_Q_el, name='Q_el', unit='J')) print(dpr.val(Q_out, d_Q_out, name='Q_out', unit='J')) print(dpr.val(W_pV, d_W_pV, name='W_pV', unit='J')) print(dpr.val(Q_V, d_Q_V, name='Q_V', unit='J')) print() print(dpr.val(P_el, d_P_el, name='P_el', unit='W')) print(dpr.val(P_out, d_P_out, name='P_out', unit='W')) print(dpr.val(P_pV, d_P_pV, name='P_pV', unit='W')) print() print(dpr.val(eta_th, d_eta_th, name='eta_th', exp_to_fix=0)) print(dpr.val(eta_th * 100, d_eta_th * 100, name='eta_th', unit='%', exp_to_fix=0))
import os import numpy as np import re import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from math import radians, cos, sin, asin, sqrt def cal_distance_meter(lat1, lng1, lat2, lng2): lng1, lat1, lng2, lat2 = map(radians, [lng1, lat1, lng2, lat2]) d_lon = lng2-lng1 d_lat = lat2-lat1 a=sin(d_lat/2)**2 + cos(lat1) * cos(lat2) * sin(d_lon/2)**2 dis=2*asin(sqrt(a))*6371*1000 return dis def judge_dis(dis1, dis2): return dis1 < 2000 or dis2 < 2000 def judge_time(t1, t2): return abs(int(t1)-int(t2)) <= 1 def get_lat_lon(id, lonlat_dict): values = lonlat_dict.get(int(id)) if values == None: return 1.0, 1.0 else: return values[0],values[1] def cal_f1(filepath): print('------------------------------') print('dealing with file:', filepath) file = open(filepath,'r') our_error_lines = file.readlines() data_lines = open('./data/final_test/20111129.csv', 'r').readlines() test_line = open('./data/accident/n_11.29.csv', 'r',encoding="gb2312").readlines() lonlat_matrix = np.loadtxt(r'./data/map/beijing.csv', delimiter = '\t') lonlat_dict = {} for i in range(len(lonlat_matrix)): numbert = int(lonlat_matrix[i][0]) lat = lonlat_matrix[i][1] lon = lonlat_matrix[i][2] lonlat_dict[numbert] = [lon,lat] TP1 = 0 wrongset = set() for i in range(len(our_error_lines)): message1 = our_error_lines[i].split(',') road_id = int(message1[0]) time1 = message1[1] message2 = data_lines[road_id].split(',') road_osm1 = message2[0] road_osm2 = message2[1] X1,Y1 = get_lat_lon(road_osm1, lonlat_dict) X2,Y2 = get_lat_lon(road_osm2, lonlat_dict) for j in range(len(test_line)): message3 = test_line[j].split(',') time2 = message3[0].split(':')[0] X0 = float(message3[2]) Y0 = float(message3[3]) distance1 = cal_distance_meter(X0,Y0,X1,Y1) distance2 = cal_distance_meter(X0,Y0,X2,Y2) if judge_dis(distance1,distance2) and judge_time(time1,time2): TP1 += 1 wrongset.add(j) TP2 = len(wrongset) P = TP1 / len(our_error_lines) R = TP2 / len(test_line) F1 = 2*P*R/(P+R) return F1, TP1, TP2, P, R def show_matrix(mt): ax=plt.subplot(111,projection='3d') for i in range(len(mt)): for j in range(len(mt[0])): value = mt[i][j] ax.scatter(i, j, mt[i][j] ,c="r") plt.show() def get_b_s(filename): names = filename.split(',') return int(names[0][-1:]), int(names[1].split('.')[0]) def real_run(): root_dir = './data/result1' filelist = os.listdir(root_dir) best_F1 = 0 F1_matrix = [[0 for col in range(10)]for row in range(9)] for filename in filelist: filepath = os.path.join(root_dir, filename) F1, TP1, TP2, P, R = cal_f1(filepath) beta, suppose = get_b_s(filename) print(' beta = ', beta, 'sup = ', suppose) print(' F1:', F1) print(' TP1:', TP1) print(' TP2:', TP2) print(' P:', P) print(' R:', R) #save it to matrix 1-9 1-10 (9*10) F1_matrix[int(beta)-1][int(suppose)-1] = F1 if F1 > best_F1: best_F1 = F1 best_beta = beta best_suppose = suppose best_TP1 = TP1 best_TP2 = TP2 best_P = P best_R = R print('-----best result-----') print(' beta:', best_beta, ' suppose:', best_suppose) print(' F1 =', best_F1) print(' TP1:', best_TP1) print(' TP2:', best_TP2) print(' P:', best_P) print(' R:', best_R) show_matrix(F1_matrix) return def real_run_one(): #root_dir = './result' #filelist = os.listdir(root_dir) root_dir = './data/result' filelist = os.listdir(root_dir) filename = filelist[0] filepath = os.path.join(root_dir, filename) best_F1 = 0 #F1_matrix = [[0 for col in range(10)]for row in range(9)] #for filename in filelist: #filepath = os.path.join(root_dir, filename) F1, TP1, TP2, P, R = cal_f1(filepath) #beta, suppose = get_b_s(filename) beta, suppose =2,6 print(' beta = ', beta, 'sup = ', suppose) print(' F1:', F1) print(' TP1:', TP1) print(' TP2:', TP2) print(' P:', P) print(' R:', R) #save it to matrix 1-9 1-10 (9*10) #F1_matrix[int(beta)-1][int(suppose)-1] = F1 if F1 > best_F1: best_F1 = F1 best_beta = beta best_suppose = suppose best_TP1 = TP1 best_TP2 = TP2 best_P = P best_R = R print('-----best result-----') print(' beta:', best_beta, ' suppose:', best_suppose) print(' F1 =', best_F1) print(' TP1:', best_TP1) print(' TP2:', best_TP2) print(' P:', best_P) print(' R:', best_R) #show_matrix(F1_matrix) return def run(): real_flag = 2 if real_flag == 1: real_run() elif real_flag == 2: real_run_one() else: #do some test here and set real_flag = False ax=plt.subplot(111,projection='3d') ax.scatter(1, 2, 3 ,c="r") ax.scatter(5, 7, 9 ,c="r") plt.show() #beta = 1 #suppose = 1 #for i in range(9): #for j in range(10): #print() #result = ... #np.savetxt("....../result" + '.' + beta + '.' + suppose +'.txt',......) #suppose += 1 #beta += 1
# # Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import copy import math import queue import threading import warnings from collections import OrderedDict import numpy as np try: import cupy as cp except ImportError: cp = np from merlin.io import DataFrameIter, shuffle_df from merlin.schema import Tags from nvtabular.dispatch import ( HAS_GPU, annotate, concat, generate_local_seed, is_list_dtype, make_df, pull_apart_list, ) def _num_steps(num_samples, step_size): return math.ceil(num_samples / step_size) class ChunkQueue: """This class takes partitions (parts) from an NVTabular dataset and concatenates them into a cudf dataframe "chunk". This chunk is subsequently transformed into its tensor representation using the iterator's transform. Parameters ----------- qsize: int Max number of elements to hold in the buffer at once num_parts : int number of partitions from the iterator, an NVTabular Dataset to concatenate into a "chunk" shuffle : bool enable/disable chunk-level shuffling put_wait: float amount of timeout to wait for a full queue to open up before checking for errors and trying again """ def __init__(self, dataloader, qsize, num_parts=1, shuffle=False, put_wait=1e-6, epochs=1): self.num_parts = num_parts self.shuffle = shuffle self.put_wait = put_wait self.q_out = queue.Queue(qsize) self._stop_event = threading.Event() self.itr = dataloader._data_iter(epochs) self.dataloader = dataloader def __len__(self): return len(self.itr) @property def stopped(self): return self._stop_event.is_set() @property def empty(self): return self.q_out.empty() def get(self): return self.q_out.get() def put(self, packet): while True: if self.stopped: return True try: self.q_out.put(packet, timeout=self.put_wait) return False except queue.Full: continue @annotate("batch", color="darkgreen", domain="nvt_python") def batch(self, itr): """ iterates through gpu_mem_frac size chunks of dataset and concatenates every `num_parts` of them. """ current = [] while True: try: value = next(itr) except StopIteration: if len(current) > 0: yield current break current.append(value) if len(current) == self.num_parts: yield current current = [] @annotate("chunk_logic", color="darkgreen", domain="nvt_python") def chunk_logic(self, itr): spill = None for chunks in self.batch(itr): if self.stopped: return if spill is not None and not spill.empty: chunks.insert(0, spill) chunks = concat(chunks) chunks.reset_index(drop=True, inplace=True) chunks, spill = self.get_batch_div_chunk(chunks, self.dataloader.batch_size) if self.shuffle: chunks = shuffle_df(chunks) if len(chunks) > 0: chunks = self.dataloader.make_tensors(chunks, self.dataloader._use_nnz) # put returns True if buffer is stopped before # packet can be put in queue. Keeps us from # freezing on a put on a full queue if self.put(chunks): return chunks = None # takes care final batch, which is less than batch size if not self.dataloader.drop_last and spill is not None and not spill.empty: spill = self.dataloader.make_tensors(spill, self.dataloader._use_nnz) self.put(spill) @annotate("load_chunks", color="darkgreen", domain="nvt_python") def load_chunks(self, dev): try: itr = iter(self.itr) if self.dataloader.device != "cpu": with self.dataloader._get_device_ctx(dev): self.chunk_logic(itr) else: self.chunk_logic(itr) except Exception as e: # pylint: disable=broad-except self.put(e) # For when an iterator is stopped before iteration is complete. def stop(self): self._stop_event.set() # TODO: should we be clearing? I can imagine a world where # you want the thread to stop but still want to grab # data out of the buffer self.q_out.queue.clear() def start(self): self._stop_event.clear() def get_batch_div_chunk(self, chunks, batch_size): # TODO: is there a way to do this using cupy? spill_idx = int(chunks.shape[0] / batch_size) * batch_size spill = make_df(chunks.iloc[spill_idx:]) chunks = make_df(chunks.iloc[:spill_idx]) if not chunks.empty: chunks.reset_index(drop=True, inplace=True) if not spill.empty: spill.reset_index(drop=True, inplace=True) return chunks, spill def _get_dataset_schema(dataset): return dataset.schema if hasattr(dataset, "schema") else None # TODO: implement as metaclass and assign methods to children # to avoid having to do Dataset.<method> calls? class DataLoader: _use_nnz = False def __init__( self, dataset, batch_size, shuffle, cat_names=None, cont_names=None, label_names=None, seed_fn=None, parts_per_chunk=1, device=None, global_size=None, global_rank=None, drop_last=False, sparse_names=None, sparse_max=None, sparse_as_dense=False, ): self.data = dataset self.schema = _get_dataset_schema(dataset) # self.data is ddf format self.indices = cp.arange(self.data.npartitions) self.drop_last = drop_last self.device = (device or 0) if HAS_GPU else "cpu" self.sparse_names = sparse_names or [] self.sparse_max = sparse_max or {} self.sparse_as_dense = sparse_as_dense self.global_size = global_size or 1 self.global_rank = global_rank or 0 self._epochs = 1 self.cat_names = cat_names or ( self.schema.select_by_tag(Tags.CATEGORICAL).column_names if self.schema else [] ) self.cont_names = cont_names or ( self.schema.select_by_tag(Tags.CONTINUOUS).column_names if self.schema else [] ) self.label_names = label_names or ( self.schema.select_by_tag(Tags.TARGET).column_names if self.schema else [] ) if not self.cat_names and not self.cont_names: raise ValueError( "Neither Categorical or Continuous columns were found by the dataloader. " "You must either specify the cat_names, cont_names and " "label_names properties or supply a schema.pbtxt file in dataset directory." ) self.batch_size = batch_size self.shuffle = shuffle self.seed_fn = seed_fn self.num_rows_processed = 0 self.parts_per_chunk = parts_per_chunk self.shuffle = shuffle self.__buff = None self.__buff_len = None self._batch_itr = None self._workers = None @property def _buff(self): if self.__buff is None: # we set size of chunk queue to 1 we only want one chunk in queue at a time. self.__buff = ChunkQueue( self, 1, num_parts=self.parts_per_chunk, shuffle=self.shuffle, epochs=self._epochs ) return self.__buff @property def _buff_len(self): if self.__buff_len is None: # run once instead of every time len called self.__buff_len = len(self._buff) return self.__buff_len def epochs(self, epochs=1): if epochs == self._epochs: return self new_dataloader = copy.copy(self) new_dataloader._set_epochs(epochs) return new_dataloader def _set_epochs(self, epochs): self.stop() self.__buff = None self.__buff_len = None self._epochs = epochs def __len__(self): batches = _num_steps(self._buff_len, self.batch_size) if self.drop_last and self._buff_len % self.batch_size > 0: batches = batches - 1 return batches @property def _working(self): if self._workers is not None: return any(t.is_alive() for t in self._workers) return False def stop(self): # TODO: raise warning or even error if condition # isn't met? if self._workers is not None: if not self._buff.stopped: self._buff.stop() for t in self._workers: t.join() # remove joined threads from list self._workers = None self._buff.q_out.queue.clear() self._batch_itr = None def _gather_indices_for_dev(self, dev): # this should be self.indices divided by total processes, global set if len(self.indices) < self.global_size: warnings.warn( f"""You have more processes({self.global_size}) than dataset partitions({len(self.indices)}), reduce the number of processes.""" ) raise IndexError per_worker = _num_steps(len(self.indices), self.global_size) # identify process rank out of all processes (not local rank) start = self.global_rank * per_worker return self.indices[start : start + per_worker].tolist() @annotate("_shuffle_indices", color="darkgreen", domain="nvt_python") def _shuffle_indices(self): generate_local_seed(self.global_rank, self.global_size) if self.seed_fn: new_seed = self.seed_fn() cp.random.seed(new_seed) cp.random.shuffle(self.indices) generate_local_seed(self.global_rank, self.global_size) def __iter__(self): self.stop() self.num_rows_processed = 0 if self._buff.stopped: self._buff.start() # shuffle partition indices to bring disparate # parts of the dataset "close" to one another if self.shuffle: self._shuffle_indices() # build and start new threads for loading and # concatenating data self._workers = [] t = threading.Thread(target=self._buff.load_chunks, args=(self.device,)) t.daemon = True t.start() self._workers.append(t) return self def __next__(self): return self._get_next_batch() def _data_iter(self, epochs): indices = self._gather_indices_for_dev(0) if hasattr(self.data, "to_iter"): return self.data.to_iter(indices=indices, epochs=epochs) return DataFrameIter(self.data, epochs=epochs) def _fetch_chunk(self): chunks = self._buff.get() if isinstance(chunks, Exception): self.stop() raise chunks self._batch_itr = iter(chunks) def _get_next_batch(self): """ adding this cheap shim so that we can call this step without it getting overridden by the framework-specific parent class's `__next__` method. TODO: can this be better solved with a metaclass implementation? My gut is that we don't actually necessarily *want*, in general, to be overriding __next__ and __iter__ methods """ # we've never initialized, do that now # need this because tf.keras.Model.fit will # call next() cold if self._workers is None: DataLoader.__iter__(self) # get the first chunks if self._batch_itr is None: self._fetch_chunk() # try to iterate through existing batches try: batch = next(self._batch_itr) except StopIteration: # anticipate any more chunks getting created # if not, raise the StopIteration if not self._working and self._buff.empty: self._workers = None self._batch_itr = None raise # otherwise get the next chunks and return # the first batch self._fetch_chunk() batch = next(self._batch_itr) # if batch[0] is empty but other exist for sub in batch: if sub is not None and len(sub) > 0: self.num_rows_processed += len(sub) break return batch @annotate("make_tensors", color="darkgreen", domain="nvt_python") def make_tensors(self, gdf, use_nnz=False): split_idx = self._get_segment_lengths(len(gdf)) # map from big chunk to framework-specific tensors chunks = self._create_tensors(gdf) # if we have any offsets, calculate nnzs up front if len(chunks) == 4: offsets = chunks[-1] if use_nnz: nnzs = offsets[1:] - offsets[:-1] chunks = chunks[:-1] # split them into batches and map to the framework-specific output format batches = [[] for _ in range(len(split_idx))] offset_idx = 0 for chunk in chunks: lists = None if isinstance(chunk, tuple): chunk, lists = chunk if len(split_idx) > 1 and chunk is not None: chunk = self._split_fn(chunk, split_idx) else: chunk = [chunk for _ in split_idx] if lists is not None: num_list_columns = len(lists) # grab the set of offsets and nnzs corresponding to # the list columns from this chunk chunk_offsets = offsets[:, offset_idx : offset_idx + num_list_columns] if use_nnz: chunk_nnzs = nnzs[:, offset_idx : offset_idx + num_list_columns] offset_idx += num_list_columns # split them into batches, including an extra 1 on the offsets # so we know how long the very last element is batch_offsets = self._split_fn(chunk_offsets, split_idx + [1]) if use_nnz and len(split_idx) > 1: batch_nnzs = self._split_fn(chunk_nnzs, split_idx) elif use_nnz: batch_nnzs = [chunk_nnzs] else: batch_nnzs = [None] * (len(batch_offsets) - 1) # group all these indices together and iterate through # them in batches to grab the proper elements from each # values tensor chunk = zip(chunk, batch_offsets[:-1], batch_offsets[1:], batch_nnzs) for n, c in enumerate(chunk): if isinstance(c, tuple): c, off0s, off1s, _nnzs = c offsets_split_idx = [1 for _ in range(num_list_columns)] off0s = self._split_fn(off0s, offsets_split_idx, axis=1) off1s = self._split_fn(off1s, offsets_split_idx, axis=1) if use_nnz: _nnzs = self._split_fn(_nnzs, offsets_split_idx, axis=1) # TODO: does this need to be ordereddict? batch_lists = {} for k, (column_name, values) in enumerate(lists.items()): off0, off1 = off0s[k], off1s[k] if use_nnz: nnz = _nnzs[k] # need to grab scalars for TF case if len(off0.shape) == 1: start, stop = off0[0], off1[0] elif len(off0.shape) == 2: start, stop = off0[0, 0], off1[0, 0] else: print(off0, off1) raise ValueError value = values[int(start) : int(stop)] index = off0 - start if not use_nnz else nnz batch_lists[column_name] = (value, index) c = (c, batch_lists) batches[n].append(c) return [self._handle_tensors(*batch) for batch in batches] def _get_segment_lengths(self, num_samples): """ Helper function to build indices to pass to <torch|tf>.split functions for breaking up into batches """ num_full_batches = _num_steps(num_samples, self.batch_size) - 1 idx = [self.batch_size for _ in range(num_full_batches)] idx.append(num_samples - num_full_batches * self.batch_size) return idx def _to_sparse_tensor(self, values_offset, column_name): """ Create a sparse representation of the input tensor. values_offset is either a tensor or a tuple of tensor, offset. """ seq_limit = self.sparse_max[column_name] values, offsets, diff_offsets, num_rows = self._pull_values_offsets(values_offset) max_seq_len = self._get_max_seq_len(diff_offsets) if max_seq_len > seq_limit: raise ValueError( "The default sequence length has been configured " + f"to {seq_limit} but the " + f"largest sequence in this batch have {max_seq_len} length" ) return self._build_sparse_tensor(values, offsets, diff_offsets, num_rows, seq_limit) def _to_tensor(self, gdf, dtype=None): """ One of the mandatory functions a child class needs to implement. Maps from a cudf DataFrame to a tensor in the appropriate library, with an optional dtype kwarg to do explicit casting if need be """ raise NotImplementedError def _get_device_ctx(self, dev): """ One of the mandatory functions a child class needs to implement. Maps from a GPU index to a framework context object for placing tensors on specific GPUs """ raise NotImplementedError def _split_fn(self, tensor, idx, axis=0): raise NotImplementedError @property def _LONG_DTYPE(self): raise NotImplementedError @property def _FLOAT32_DTYPE(self): raise NotImplementedError def _separate_list_columns(self, gdf): lists, scalars = [], [] for col in gdf.columns: if is_list_dtype(gdf[col]): lists.append(col) else: scalars.append(col) return scalars, lists @annotate("_create_tensors", color="darkgreen", domain="nvt_python") def _create_tensors(self, gdf): """ Breaks a dataframe down into the relevant categorical, continuous, and label tensors. Can be overrideen """ workflow_nodes = (self.cat_names, self.cont_names, self.label_names) dtypes = (self._LONG_DTYPE, self._FLOAT32_DTYPE, self._FLOAT32_DTYPE) tensors = [] offsets = make_df(device=self.device) for column_names, dtype in zip(workflow_nodes, dtypes): if len(column_names) == 0: tensors.append(None) continue gdf_i = gdf[column_names] gdf.drop(columns=column_names, inplace=True) scalars, lists = self._separate_list_columns(gdf_i) x = None if scalars: # should always return dict column_name: values, offsets (optional) x = self._to_tensor(gdf_i[scalars], dtype) if lists: list_tensors = OrderedDict() for column_name in lists: column = gdf_i.pop(column_name) leaves, col_offsets = pull_apart_list(column, device=self.device) if isinstance(leaves[0], list): leaves, nest_offsets = pull_apart_list(leaves, device=self.device) col_offsets = nest_offsets.iloc[col_offsets[:]] offsets[column_name] = col_offsets.reset_index(drop=True) list_tensors[column_name] = self._to_tensor(leaves, dtype) x = x, list_tensors tensors.append(x) if not offsets.empty: offsets_tensor = self._to_tensor(offsets, self._LONG_DTYPE) if len(offsets_tensor.shape) == 1: offsets_tensor = offsets_tensor[:, None] tensors.append(offsets_tensor) del gdf, offsets return tensors @annotate("_handle_tensors", color="darkgreen", domain="nvt_python") def _handle_tensors(self, cats, conts, labels): X = {} for tensor, names in zip([cats, conts], [self.cat_names, self.cont_names]): lists = {} if isinstance(tensor, tuple): tensor, lists = tensor names = [i for i in names if i not in lists] # now add in any scalar tensors if len(names) > 1: tensors = self._tensor_split(tensor, len(names), axis=1) lists.update(zip(names, tensors)) elif len(names) == 1: lists[names[0]] = tensor X.update(lists) for column_name in X: if column_name in self.sparse_names: if column_name not in self.sparse_max: raise ValueError( f"Did not convert {column_name} to sparse due to missing sparse_max entry" ) X[column_name] = self._to_sparse_tensor(X[column_name], column_name) # TODO: use dict for labels as well? # would require output layers to match naming if len(self.label_names) > 1: labels = self._tensor_split(labels, len(self.label_names), axis=1) return X, labels
# coding: utf-8 from __future__ import division, print_function, unicode_literals, absolute_import import os import unittest from fireworks import FWorker from fireworks.core.rocket_launcher import rapidfire from atomate.vasp.powerups import use_fake_vasp from atomate.vasp.workflows.base.adsorption import get_wf_surface from atomate.utils.testing import AtomateTest from pymatgen import Structure, Molecule, Lattice from pymatgen.core.surface import generate_all_slabs __author__ = '<NAME>, <NAME>' __email__ = '<EMAIL>' module_dir = os.path.join(os.path.dirname(os.path.abspath(__file__))) db_dir = os.path.join(module_dir, "..", "..", "..", "common", "test_files") ref_dir = os.path.join(module_dir, "..", "..", "test_files") DEBUG_MODE = False # If true, retains the database and output dirs at the end of the test VASP_CMD = None # If None, runs a "fake" VASP. Otherwise, runs VASP with this command... class TestAdsorptionWorkflow(AtomateTest): def setUp(self): super(TestAdsorptionWorkflow, self).setUp() self.struct_ir = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.875728), ["Ir"], [[0, 0, 0]]) sgp = {"max_index": 1, "min_slab_size": 7.0, "min_vacuum_size": 20.0} slabs = generate_all_slabs(self.struct_ir, **sgp) slabs = [slab for slab in slabs if slab.miller_index==(1, 0, 0)] sgp.pop("max_index") self.wf_1 = get_wf_surface(slabs, [Molecule("H", [[0, 0, 0]])], self.struct_ir, sgp, db_file=os.path.join(db_dir, "db.json")) def _simulate_vasprun(self, wf): reference_dir = os.path.abspath(os.path.join(ref_dir, "adsorbate_wf")) ir_ref_dirs = {"Ir-structure optimization": os.path.join(reference_dir, "1"), "Ir-Ir_(1, 0, 0) slab optimization": os.path.join(reference_dir, "2"), "Ir-H1-Ir_(1, 0, 0) adsorbate optimization 0": os.path.join(reference_dir, "3"), "Ir-H1-Ir_(1, 0, 0) adsorbate optimization 1": os.path.join(reference_dir, "4"), "Ir-H1-Ir_(1, 0, 0) adsorbate optimization 2": os.path.join(reference_dir, "5")} return use_fake_vasp(wf, ir_ref_dirs, params_to_check=["ENCUT", "ISIF", "IBRION"]) def _check_run(self, d, mode): if mode not in ["H1-Ir_(1, 0, 0) adsorbate optimization 1"]: raise ValueError("Invalid mode!") if "adsorbate" in mode: self.assertEqual(d["formula_reduced_abc"], "H1 Ir16") # Check relaxation of adsorbate # Check slab calculations # Check structure optimization def test_wf(self): wf = self._simulate_vasprun(self.wf_1) self.assertEqual(len(self.wf_1.fws), 5) # check vasp parameters for ionic relaxation ads_vis = [fw.tasks[1]['vasp_input_set'] for fw in self.wf_1.fws if "adsorbate" in fw.name] assert all([vis.incar['EDIFFG']==-0.02 for vis in ads_vis]) assert all([vis.incar['ISIF']==2 for vis in ads_vis]) self.lp.add_wf(wf) rapidfire(self.lp, fworker=FWorker(env={"db_file": os.path.join(db_dir, "db.json")})) # check relaxation d = self.get_task_collection().find_one({"task_label": "H1-Ir_(1, 0, 0) adsorbate optimization 1"}) self._check_run(d, mode="H1-Ir_(1, 0, 0) adsorbate optimization 1") wf = self.lp.get_wf_by_fw_id(1) self.assertTrue(all([s == 'COMPLETED' for s in wf.fw_states.values()])) if __name__ == "__main__": unittest.main()
""" Created on September 29th, 2020 @author: urikotlicki """ # Based on code taken from: https://github.com/YanWei123/Pytorch-implementation-of-FoldingNet-encoder-and-decoder-with-graph-pooling-covariance-add-quanti # import system modules from __future__ import print_function import argparse import os import os.path as osp import sys import random import numpy as np import torch.optim as optim import torch.utils.data from torch.autograd import Variable import time import matplotlib.pyplot as plt # add paths parent_dir = osp.dirname(osp.dirname(osp.dirname(osp.abspath(__file__)))) if parent_dir not in sys.path: sys.path.append(parent_dir) from transfer.foldingnet.foldingnet import FoldingNet_graph from transfer.foldingnet.foldingnet import ChamferLoss from transfer.foldingnet.prepare_graph import build_graph from src.general_utils import plot_3d_point_cloud parser = argparse.ArgumentParser() parser.add_argument('--training_set', type=str, default='log/autoencoder_victim/eval_train/point_clouds_train_set_13l.npy', help='Path to training set examples [default: log/autoencoder_victim/eval_train/point_clouds_train_set_13l.npy]') parser.add_argument('--validation_set', type=str, default='log/autoencoder_victim/eval_val/point_clouds_val_set_13l.npy', help='Path to validation set examples [default: log/autoencoder_victim/eval_val/point_clouds_val_set_13l.npy]') parser.add_argument('--batchSize', type=int, default=8, help='Input batch size [default: 8]') parser.add_argument('--num_points', type=int, default=2048, help='Input batch size [default: 2048]') parser.add_argument('--workers', type=int, default=4, help='Number of data loading workers [default: 4]') parser.add_argument('--nepoch', type=int, default=25, help='Number of epochs to train for [default: 25]') parser.add_argument('--outf', type=str, default='log/foldingnet', help='Output folder [default: log/foldingnet]') parser.add_argument('--checkpoint_num', type=int, default=0, help='Checkpoint number to be loaded [default: 0]') parser.add_argument('-md', '--mode', type=str, default="M", help="Mode used to compute graphs: M, P") parser.add_argument('-m', '--metric', type=str, default='euclidean', help="Metric for distance calculation (manhattan/euclidean)") opt = parser.parse_args() opt.knn = 16 print(opt) blue = lambda x: '\033[94m' + x + '\033[0m' opt.manualSeed = random.randint(1, 10000) # fix seed print("Random seed: ", opt.manualSeed) random.seed(opt.manualSeed) torch.manual_seed(opt.manualSeed) point_clouds = torch.tensor(np.load(osp.join(parent_dir, opt.training_set))) train_dataset = torch.utils.data.TensorDataset(point_clouds) train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=opt.batchSize, shuffle=True, num_workers=int(opt.workers)) point_clouds_val = torch.tensor(np.load(parent_dir + '/' + opt.validation_set)) val_dataset = torch.utils.data.TensorDataset(point_clouds_val) val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=opt.batchSize, shuffle=True, num_workers=int(opt.workers)) print('Training set: %d examples\nValidation set: %d examples' % (len(train_dataset), len(val_dataset))) try: os.makedirs(osp.join(parent_dir, opt.outf)) except OSError: pass foldingnet = FoldingNet_graph() optimizer = optim.Adam(foldingnet.parameters(), lr=0.0001, betas=(0.9, 0.999), weight_decay=1e-6) foldingnet.cuda() if opt.checkpoint_num > 0: checkpoint = torch.load(osp.join(parent_dir, opt.outf, 'checkpoint_%d.pth' % opt.checkpoint_num)) start_epoch = checkpoint['epoch'] + 1 foldingnet.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) print('Checkpoint successfully loaded') else: start_epoch = 0 print('Start training from epoch 0') num_batch = len(train_dataset)/opt.batchSize chamferloss = ChamferLoss() chamferloss.cuda() start_time = time.time() time_p, loss_p, loss_m = [], [], [] for epoch in range(start_epoch, opt.nepoch): sum_loss = 0 sum_step = 0 sum_mid_loss = 0 for i, data in enumerate(train_dataloader, 0): points = data[0] batch_graph, Cov = build_graph(points, opt) Cov = Cov.transpose(2, 1) Cov = Cov.cuda() points = points.transpose(2, 1) points = points.cuda() optimizer.zero_grad() foldingnet = foldingnet.train() recon_pc, mid_pc, _ = foldingnet(points, Cov, batch_graph) loss = chamferloss(points.transpose(2, 1), recon_pc.transpose(2, 1)) loss.backward() optimizer.step() mid_loss = chamferloss(points.transpose(2, 1), mid_pc.transpose(2, 1)) # store loss and step sum_loss += loss.item()*points.size(0) sum_mid_loss += mid_loss.item()*points.size(0) sum_step += points.size(0) print('[%d: %d/%d] train loss: %f middle loss: %f' % (epoch, i, num_batch, loss.item(), mid_loss.item())) if i % 100 == 0: j, data = next(enumerate(val_dataloader, 0)) # points, target = data points = data[0] # build graph batch_graph, Cov = build_graph(points, opt) Cov = Cov.transpose(2, 1) Cov = Cov.cuda() # points, target = Variable(points), Variable(target[:,0]) points = Variable(points) points = points.transpose(2, 1) # points, target = points.cuda(), target.cuda() points = points.cuda() foldingnet = foldingnet.eval() recon_pc, mid_pc, _ = foldingnet(points, Cov, batch_graph) loss = chamferloss(points.transpose(2, 1), recon_pc.transpose(2,1)) mid_loss = chamferloss(points.transpose(2, 1), mid_pc.transpose(2,1)) # prepare show result points_show = points.cpu().detach().numpy() recon_show = recon_pc.cpu().detach().numpy() fig_orig = plt.figure() a1 = fig_orig.add_subplot(111, projection='3d') a1.scatter(points_show[0, 0, :], points_show[0, 1, :], points_show[0, 2, :]) plt.savefig(osp.join(parent_dir, opt.outf, 'orig_pc_example.png')) fig_recon = plt.figure() a2 = fig_recon.add_subplot(111,projection='3d') a2.scatter(recon_show[0, 0, :], recon_show[0, 1, :], recon_show[0, 2, :]) plt.savefig(osp.join(parent_dir, opt.outf, 'recon_pc_example.png')) # plot results time_p.append(time.time()-start_time) loss_p.append(sum_loss/sum_step) loss_m.append(sum_mid_loss/sum_step) print('[%d: %d/%d] %s val loss: %f middle val loss: %f' % (epoch, i, num_batch, blue('validation'), loss.item(), mid_loss.item())) sum_step = 0 sum_loss = 0 sum_mid_loss = 0 checkpoint = { 'epoch': epoch, 'model': foldingnet.state_dict(), 'optimizer': optimizer.state_dict()} torch.save(checkpoint, osp.join(parent_dir, opt.outf, 'checkpoint_%d.pth' % epoch))
<gh_stars>0 import aiohttp class Tracking: def __init__(self, company: str = None, delivery_code: int = None): self.company = company self.delivery_code = delivery_code self.company_list = [ { "id": "de.dhl", "name": "DHL", "tel": "+8215880001" }, { "id": "kr.chunilps", "name": "천일택배", "tel": "+8218776606" }, { "id": "kr.cjlogistics", "name": "CJ대한통운", "tel": "+8215881255" }, { "id": "kr.cupost", "name": "CU 편의점택배", "tel": "+8215771287" }, { "id": "kr.cvsnet", "name": "GS Postbox 택배", "tel": "+8215771287" }, { "id": "kr.cway", "name": "CWAY (Woori Express)", "tel": "+8215884899" }, { "id": "kr.daesin", "name": "대신택배", "tel": "+82314620100" }, { "id": "kr.epost", "name": "우체국 택배", "tel": "+8215881300" }, { "id": "kr.hanips", "name": "한의사랑택배", "tel": "+8216001055" }, { "id": "kr.hanjin", "name": "한진택배", "tel": "+8215880011" }, { "id": "kr.hdexp", "name": "합동택배", "tel": "+8218993392" }, { "id": "kr.homepick", "name": "홈픽", "tel": "+8218000987" }, { "id": "kr.honamlogis", "name": "한서호남택배", "tel": "+8218770572" }, { "id": "kr.ilyanglogis", "name": "일양로지스", "tel": "+8215880002" }, { "id": "kr.kdexp", "name": "경동택배", "tel": "+8218995368" }, { "id": "kr.kunyoung", "name": "건영택배", "tel": "+82533543001" }, { "id": "kr.logen", "name": "로젠택배", "tel": "+8215889988" }, { "id": "kr.lotte", "name": "롯데택배", "tel": "+8215882121" }, { "id": "kr.slx", "name": "SLX", "tel": "+82316375400" }, { "id": "kr.swgexp", "name": "성원글로벌카고", "tel": "+82327469984" }, { "id": "un.upu.ems", "name": "EMS" }, { "id": "us.fedex", "name": "Fedex" }, { "id": "us.ups", "name": "UPS" }, { "id": "us.usps", "name": "USPS" } ] self.url = "https://apis.tracker.delivery/carriers/{carrier_id}/tracks/{track_id}" self.data:dict = {} super().__init__() async def get_info(self): async with aiohttp.ClientSession() as session: async with session.get(url=self.url.format(carrier_id=self.company, track_id=self.delivery_code)) as resp: if resp.status == 200: return {"status": resp.status, "message": "조회완료.", "data": await resp.json()} else: return {"status": resp.status, "message": "운송장이 등록되어있지않거나 운송장번호와 일치하지않는 배송사입니다.", "data": None} def get_company_list(self): return self.company_list
<filename>tests/test_bicing.py # -*- coding: utf-8 -*- """ Copyright 2016 <NAME>. This file is part of BicingBot. Licensed under the Apache License, Version 2.0 (the 'License'); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import logging import mock import pytest import requests_mock from requests import ConnectionError from bicingbot.bicing import Bicing, GET_STATION_URL, StationNotFoundError logger = logging.getLogger(__name__) # Bicing mock responses generic_response = '{"parametros_filtro": {"station": ["text", "%d", "station"]}, ' \ '"estacions_icon": "/modules/custom/mapa_disponibilitat/assets/icons/estacions.png", ' \ '"stations": %s, ' \ '"url_icon4": "/modules/custom/mapa_disponibilitat/assets/icons/ubicacio4.png", ' \ '"url_icon5": "/modules/custom/mapa_disponibilitat/assets/icons/ubicacio5.png", ' \ '"url_icon2": "/modules/custom/mapa_disponibilitat/assets/icons/ubicacio2.png", ' \ '"url_icon3": "/modules/custom/mapa_disponibilitat/assets/icons/ubicacio3.png", ' \ '"url_icon": "/modules/custom/mapa_disponibilitat/assets/icons/ubicacio.png"}' mock_found_station = '[{"status": 1, "transition_end": "", "disponibilidad": 50, "longitude": ' \ '2.201656, "transition_start": "", "electrical_bikes": 0, "type_bicing": 2, "bikes": 15, ' \ '"mechanical_bikes": 15, "streetNumber": "", "latitude": 41.402454, "slots": 17, "type": ' \ '"BIKE", "id": "154", "streetName": "154 - C/ PUJADES, 191", ' \ '"icon": "/modules/custom/mapa_disponibilitat/assets/icons/ubicacio4-50.png"}]' mock_error_station = '{"error":"unknown error"}' @requests_mock.Mocker(kw='mock') def test_get_station(**kwargs): station_id = 172 expected_station = {'status': 1, 'transition_end': '', 'disponibilidad': 50, 'longitude': 2.201656, 'transition_start': '', 'electrical_bikes': 0, 'type_bicing': 2, 'bikes': 15, 'mechanical_bikes': 15, 'streetNumber': '', 'latitude': 41.402454, 'slots': 17, 'type': 'BIKE', 'id': '154', 'streetName': '154 - C/ PUJADES, 191', 'icon': '/modules/custom/mapa_disponibilitat/assets/icons/ubicacio4-50.png'} mock_found_response = generic_response % (station_id, mock_found_station) kwargs['mock'].post(GET_STATION_URL.format(station_id), text=mock_found_response) station = Bicing().get_station(station_id) assert station == expected_station @requests_mock.Mocker(kw='mock') def test_get_station_not_found(**kwargs): station_id = 9999 mock_not_found_response = generic_response % (station_id, []) kwargs['mock'].post(GET_STATION_URL.format(station_id), text=mock_not_found_response) with pytest.raises(StationNotFoundError) as excinfo: Bicing().get_station(station_id) assert str(excinfo.value) == 'Station {} not found'.format(station_id) @mock.patch('bicingbot.bicing.requests.post') def test_get_station_url_error(req_post_mock): station_id = 154 req_post_mock.side_effect = ConnectionError('exception error') with pytest.raises(Exception) as excinfo: Bicing().get_station(station_id) assert str(excinfo.value) == "Error requesting station {}: exception error".format(station_id) @requests_mock.Mocker(kw='mock') def test_get_station_error(**kwargs): station_id = 8888 kwargs['mock'].post(GET_STATION_URL.format(station_id), text=mock_error_station) with pytest.raises(Exception) as excinfo: Bicing().get_station(station_id) assert str(excinfo.value) == "Error requesting station {}: 'stations'".format(station_id)
def connect(field,doct): for i in range(14): c=int(i/2) if i%2==0: for b in range(14): a=int(b/2) if b!=13: if b%2==0: print(field[a][c],end='') else: print('|',end='') else: print('') else: print('--------------') for i in range(7): if doct[i][0]==doct[i][1]==doct[i][2]==doct[i][3]=='X'or doct[i][4]==doct[i][1]==doct[i][2]==doct[i][3]=='X' or doct[i][5]==doct[i][4]==doct[i][2]==doct[i][3]=='X'or doct[i][5]==doct[i][4]==doct[i][6]==doct[i][3]=='X': print('player 1 winner') elif doct[i][0]==doct[i][1]==doct[i][2]==doct[i][3]=='O'or doct[i][4]==doct[i][1]==doct[i][2]==doct[i][3]=='O' or doct[i][5]==doct[i][4]==doct[i][2]==doct[i][3]=='O'or doct[i][5]==doct[i][4]==doct[i][6]==doct[i][3]=='O': print('player 2 winner') for i in range(7): if doct[0][i]==doct[i][1]==doct[2][i]==doct[3][i]=='X'or doct[4][i]==doct[1][i]==doct[2][i]==doct[3][i]=='X' or doct[5][i]==doct[4][i]==doct[2][i]==doct[3][i]=='X'or doct[5][i]==doct[4][i]==doct[6][i]==doct[3][i]=='X': print('player 1 winner') elif doct[0][i]==doct[i][1]==doct[2][i]==doct[3][i]=='O'or doct[4][i]==doct[1][i]==doct[2][i]==doct[3][i]=='O' or doct[5][i]==doct[4][i]==doct[2][i]==doct[3][i]=='O'or doct[5][i]==doct[4][i]==doct[2][i]==doct[3][i]=='O': print('player 2 winner') player=1 standardvalues=[[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' '],[' ',' ',' ',' ',' ',' ',' ']] print(standardvalues) dictionary={} dictionary=standardvalues print(dictionary) print(dictionary[2][1]) while(True): print('player turn is ',player) column=int(input('enter column= ')) p=column if player==1: if standardvalues[column][0]==' ': x=6 for y in range(7): if standardvalues[column][x]==' ': standardvalues[column][x]='X' dictionary[column][x]='X' break else: x-=1 player=2 else: if standardvalues[column][0]==' ': x=6 for y in range(7): if standardvalues[column][x]==' ': standardvalues[column][x]='O' dictionary[column][x]='O' break else: x-=1 player=1 connect(standardvalues,dictionary)
# -*- encoding: utf-8 -*- ''' @Filename : utils_workflow.py @Datetime : 2020/05/11 09:13:36 @Author : Joe-Bu @version : 1.0 @description : 提取工具 ''' import os import sys import calendar import traceback from copy import deepcopy from datetime import datetime, timedelta import numpy as np import pandas as pd import psycopg2 def checkdir(path: str): ''' 根据给定路径,判断是否存在目前,不存在则创建该目录; path -> abspath; ''' if not os.path.exists(path): os.makedirs(path) assert os.path.exists(path) return path def get_cursor(db): ''' 获取数据库连接connect、coursor ''' connet = psycopg2.connect( database=db['database'], user=db['user'], password=db['password'], host=db['host'], port=db['port']) cursor = connet.cursor() return connet, cursor def sql_qc_stats() -> str: ''' 获取某个月份表下站点质控类型数据分布 ''' sql = ''' SELECT b."name", a.* from ( SELECT DISTINCT qccode, count(value) FROM data_{0} GROUP BY qccode) as a LEFT JOIN qccode as b on a.qccode=b.qccode; '''.format('201912') return sql def get_site_local(filename: str): ''' Open local file by pandas read_csv ''' assert os.path.exists(filename) data = pd.read_csv(filename, sep=',', encoding='utf-8') return data def get_month_range(start, t_delta: int=None): ''' 给定当月开始时间(当月第一天零点) 返回下个月第一天零点 ''' _, days = calendar.monthrange(start.year, start.month) if t_delta: end = start + timedelta(hours=24) else: end = start + timedelta(days=days) return end def fetch_data(db, sql): ''' 根据sql实现取数据,返回生成的dataframe. 最主要sql工具 db 数据库信息 sql 查询语句 ''' try: connet, cursor = get_cursor(db) sql = sql cursor.execute(sql) data = cursor.fetchall() cols = cursor.description except Exception as e_db: traceback.print_exc(e_db) else: if data: col = [i.name for i in cols] df = pd.DataFrame(data, columns=col) return True, df else: print("No Data!") # cursor.rollback() return False, None finally: cursor.close() connet.close() def sql_active_station(month: str) -> str: ''' 获取每月有数据记录的站点及数据量信息 ''' sql = ''' SELECT DISTINCT stationcode, count(value) from data_{} GROUP BY stationcode; '''.format(month) return sql def get_code_from(db_info, month, localfile=None, src='local'): ''' 根据src不同选择基于本地文件或者分月表实际情况的站点; month: for src='db'; localfile: for scr='local; return: stationcode list; ''' assert src in ['local', 'db'] if localfile: assert os.path.exists(localfile) if src == 'local': data = get_site_local(localfile) elif src == 'db': sql = sql_active_station(month) if fetch_data(db_info, sql)[0]: _, data = fetch_data(db_info, sql) else: pass return data
<gh_stars>1-10 import re from docxtpl import DocxTemplate, R, InlineImage, RichText, Listing, Document, Subdoc from docx.shared import Mm, Inches, Pt import docx.opc.constants from docassemble.base.functions import server import docassemble.base.filter from xml.sax.saxutils import escape as html_escape from types import NoneType from docassemble.base.logger import logmessage def image_for_docx(number, question, tpl, width=None): file_info = server.file_finder(number, convert={'svg': 'png'}, question=question) if 'fullpath' not in file_info: return '[FILE NOT FOUND]' if width is not None: m = re.search(r'^([0-9\.]+) *([A-Za-z]*)', str(width)) if m: amount = float(m.group(1)) units = m.group(2).lower() if units in ['in', 'inches', 'inch']: the_width = Inches(amount) elif units in ['pt', 'pts', 'point', 'points']: the_width = Pt(amount) elif units in ['mm', 'millimeter', 'millimeters']: the_width = Mm(amount) else: the_width = Pt(amount) else: the_width = Inches(2) else: the_width = Inches(2) return InlineImage(tpl, file_info['fullpath'], the_width) def transform_for_docx(text, question, tpl, width=None): if type(text) in (int, float, bool, NoneType): return text text = unicode(text) m = re.search(r'\[FILE ([^,\]]+), *([0-9\.]) *([A-Za-z]+) *\]', text) if m: amount = m.group(2) units = m.group(3).lower() if units in ['in', 'inches', 'inch']: the_width = Inches(amount) elif units in ['pt', 'pts', 'point', 'points']: the_width = Pt(amount) elif units in ['mm', 'millimeter', 'millimeters']: the_width = Mm(amount) else: the_width = Pt(amount) file_info = server.file_finder(m.group(1), convert={'svg': 'png'}, question=question) if 'fullpath' not in file_info: return '[FILE NOT FOUND]' return InlineImage(tpl, file_info['fullpath'], the_width) m = re.search(r'\[FILE ([^,\]]+)\]', text) if m: file_info = server.file_finder(m.group(1), convert={'svg': 'png'}, question=question) if 'fullpath' not in file_info: return '[FILE NOT FOUND]' return InlineImage(tpl, file_info['fullpath'], Inches(2)) return docassemble.base.filter.docx_template_filter(text) def create_hyperlink(url, anchor_text, tpl): return InlineHyperlink(tpl, url, anchor_text) class InlineHyperlink(object): def __init__(self, tpl, url, anchor_text): self.tpl = tpl self.url = url self.anchor_text = anchor_text def _insert_link(self): ref = self.tpl.docx._part.relate_to(self.url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True) return '</w:t></w:r><w:hyperlink r:id="%s"><w:r><w:rPr><w:rStyle w:val="InternetLink"/></w:rPr><w:t>%s</w:t></w:r></w:hyperlink><w:r><w:rPr></w:rPr><w:t xml:space="preserve">' % (ref, html_escape(self.anchor_text)) def __unicode__(self): return self._insert_link() def __str__(self): return self._insert_link()
<gh_stars>100-1000 from sqlalchemy.orm import Session from sqlalchemy import func import datetime import db.models as models import schemas.schemas as schemas def create_new_stack( db: Session, stack: schemas.StackCreate, user_id: int, task_id: str, var_json: str, var_list: str, squad_access: str): db_stack = models.Stack( stack_name=stack.stack_name, git_repo=stack.git_repo, tf_version=stack.tf_version, description=stack.description, branch=stack.branch, user_id=user_id, created_at=datetime.datetime.now(), var_json=var_json, var_list=var_list, squad_access=squad_access, task_id=task_id) try: db.add(db_stack) db.commit() db.refresh(db_stack) return db_stack except Exception as err: raise err def update_stack( db: Session, stack: schemas.StackCreate, stack_id: int, user_id: int, task_id: str, var_json: str, var_list: str, squad_access: str): db_stack = db.query(models.Stack).filter( models.Stack.id == stack_id).first() db_stack.user_id = user_id db_stack.task_id = task_id db_stack.var_json = var_json db_stack.var_list = var_list db_stack.updated_at = datetime.datetime.now() check_None = ["string", ""] if db_stack.stack_name not in check_None: db_stack.stack_name = stack.stack_name if db_stack.git_repo not in check_None: db_stack.git_repo = stack.git_repo if db_stack.branch not in check_None: db_stack.branch = stack.branch if db_stack.tf_version not in check_None: db_stack.tf_version = stack.tf_version if db_stack.description not in check_None: db_stack.description = stack.description if db_stack.squad_access not in check_None: db_stack.squad_access = squad_access try: db.add(db_stack) db.commit() db.refresh(db_stack) return db_stack except Exception as err: raise err def get_all_stacks_by_squad(db: Session, squad_access: str, skip: int = 0, limit: int = 100): try: filter_all = db.query(models.Stack).filter(models.Stack.squad_access.contains("*")).offset(skip).limit(limit).all() from sqlalchemy import func result = [] for i in squad_access: a = f'["{i}"]' result.extend(db.query(models.Stack).filter(func.json_contains(models.Stack.squad_access, a) == 1).all()) merge_query = result + filter_all return set(merge_query) except Exception as err: raise err def get_all_stacks(db: Session, squad_access: str, skip: int = 0, limit: int = 100): try: return db.query(models.Stack).offset(skip).limit(limit).all() except Exception as err: raise err def get_stack_by_id(db: Session, stack_id: int): try: return db.query( models.Stack).filter( models.Stack.id == stack_id).first() except Exception as err: raise err def delete_stack_by_id(db: Session, stack_id: int): db.query(models.Stack).filter(models.Stack.id == stack_id).delete() try: db.commit() return {"result": "deleted", "stack_id": stack_id} except Exception as err: raise err def get_stack_by_name(db: Session, stack_name: str): try: return db.query( models.Stack).filter( models.Stack.stack_name == stack_name).first() except Exception as err: raise err def delete_stack_by_name(db: Session, stack_name: str): db.query(models.Stack).filter( models.Stack.stack_name == stack_name).delete() try: db.commit() return {"result": "deleted", "stack_name": stack_name} except Exception as err: raise err
# -*- coding: utf-8 -*- import numpy as np from waldis.dynamic_graph import Edge from waldis.random_walker import edge_similarity def check_pattern_in_instance(graph, pattern_edges, pattern_attributes, pattern_timestamps, pattern_directions, graph_starting_vertices, graph_starting_timestamp, secondary_time_unit, edge_weights, use_vertex_attributes=True, num_of_random_walks=100): """ Looks into the graph, whether there is the given pattern on with respect to the given vertices and timestamp. :param graph: :param pattern_edges: list of pairs (src, dst) :param pattern_attributes: :param pattern_timestamps: :param graph_starting_vertices: :param graph_starting_timestamp: assumed event time in the graph :param secondary_time_unit: time (epoch) that represents common time unit for selecting the primary edge :return: """ if len(pattern_edges) == 0: # return full score because empty pattern can be everywhere return 1.0 else: number_of_instances_in_pattern = len(pattern_attributes[0]) # prepare adjacency list from pattern edges adjacency_list = dict() # we also remember which edge is linked to each such adjacency information - it is necessary for score computation adjacency_links_to_edges = dict() # whether this is the original direction or the added (opposite) one: adjacency_list_is_opposite = dict() for i in range(len(pattern_edges)): src = pattern_edges[i][0] dst = pattern_edges[i][1] if src not in adjacency_list: adjacency_list[src] = [dst] adjacency_links_to_edges[src] = [i] adjacency_list_is_opposite[src] = [False] else: adjacency_list[src].append(dst) adjacency_links_to_edges[src].append(i) adjacency_list_is_opposite[src].append(False) if dst not in adjacency_list: adjacency_list[dst] = [src] adjacency_links_to_edges[dst] = [i] adjacency_list_is_opposite[dst] = [True] else: adjacency_list[dst].append(src) adjacency_links_to_edges[dst].append(i) adjacency_list_is_opposite[dst].append(True) # not all starting vertices occur in the pattern, so use 0 selection probability for those missing # starting_vertices_probs = np.repeat(0.0, len(starting_vertices)) starting_vertices_usable = np.repeat(False, len(graph_starting_vertices)) for pattern_edge in pattern_edges: if pattern_edge[0] < len(graph_starting_vertices): # starting_vertices_probs[pattern_edge[0]] = 1.0 starting_vertices_usable[pattern_edge[0]] = True if pattern_edge[1] < len(graph_starting_vertices): # starting_vertices_probs[pattern_edge[1]] = 1.0 starting_vertices_usable[pattern_edge[1]] = True # starting_vertices_probabilities = starting_vertices_probs / starting_vertices_probs.sum() all_total_scores = [] # go through all pattern instances for pattern_instance_index in range(number_of_instances_in_pattern): walks_scores = list() for i in range(num_of_random_walks): # try one mapping of the pattern # what is the score of this walk and how many steps we did walk_score = 0.0 walk_length = 0.0 # we don't allow to use one pattern edge many times (both in pattern and graph) in one random walk already_visited_pattern_edges = set() # here we keep the original ids used in the graph in this single random walk already_visited_graph_edges = set() # first, choose the starting vertices (for the pattern and the corresponding one from graph) # here we keep the vertices from which we can go one edge available_vertices = set() # here we keep the vertices that have been already added to available_vertices # so that we do not add them there again (once they are removed) already_tried_vertices = set() # keep the mapping from pattern vertices to graph vertices and use it to check the vertex consistency: vertex_mapping = dict() for pattern_vertex in range(len(graph_starting_vertices)): # but add only those that are in the pattern if starting_vertices_usable[pattern_vertex]: available_vertices.add(pattern_vertex) already_tried_vertices.add(pattern_vertex) vertex_mapping[pattern_vertex] = graph_starting_vertices[pattern_vertex] # if walking in the graph goes wrong, we continue only in the pattern # walking_pattern_only = False # now perform the occupation of the graph by the pattern while len(available_vertices) > 0: # while we have some available vertices (i.e. available edges) # pick one edge randomly current_pattern_vertex = np.random.choice(list(available_vertices)) current_graph_vertex = vertex_mapping[current_pattern_vertex] # which pattern edges can be used to move forward which_adjacent_edges_could_be_used = [i for i, x in enumerate(adjacency_links_to_edges[current_pattern_vertex]) if x not in already_visited_pattern_edges] if len(which_adjacent_edges_could_be_used) == 0: # if there are no available pattern edges going from this vertex, # remove it from our set and try another round available_vertices.remove(current_pattern_vertex) continue # if there are some usable edges, select one at random index_in_adjacency_list = np.random.choice(which_adjacent_edges_could_be_used, 1)[0] pattern_edge_index = adjacency_links_to_edges[current_pattern_vertex][index_in_adjacency_list] # increase the counts # edges_counts[pattern_edge_index] += 1 # OLD if pattern_attributes[pattern_edge_index][pattern_instance_index] is not None: # NEW - don't count walk length if there None here walk_length += 1 # NEW already_visited_pattern_edges.add(pattern_edge_index) pattern_to_vertex = adjacency_list[current_pattern_vertex][index_in_adjacency_list] if pattern_to_vertex not in already_tried_vertices: # if the vertex is not in the available_vertices, add it there # available_vertices.add(pattern_to_vertex) already_tried_vertices.add(pattern_to_vertex) graph_edges = graph.adjacency_list[current_graph_vertex] graph_allowed_edges = [e for e in graph_edges if e.original_edge_id not in already_visited_graph_edges] # remove edges that have inconsistent vertices (we check dst vertex) if pattern_to_vertex in vertex_mapping: graph_allowed_edges = [e for e in graph_allowed_edges if e.to_vertex_id == vertex_mapping[pattern_to_vertex]] if len(graph_allowed_edges) == 0: # update available vertices and continue by selecting another edge available_vertices.remove(current_pattern_vertex) continue else: # select the edge in the graph and move forward both in the graph and pattern # only attributes and direction are necessary for edge similarity function if pattern_attributes[pattern_edge_index][pattern_instance_index] is not None: # don't count walk length if there None here primary_edge = Edge(0, 0, 0, timestamp=0, attributes=pattern_attributes[pattern_edge_index][pattern_instance_index], direction=pattern_directions[pattern_edge_index], original_edge_id=None) # now check whether we should take the opposite: if adjacency_list_is_opposite[current_pattern_vertex][index_in_adjacency_list]: # take the opposite: primary_edge = primary_edge.create_opposite_edge(graph.undirected, 0) probs = np.array( [edge_similarity(graph, primary_edge, secondary_edge, secondary_event_start_time=graph_starting_timestamp, secondary_edge_expected_timestamp=( graph_starting_timestamp - pattern_timestamps[pattern_edge_index][ pattern_instance_index]), time_unit=secondary_time_unit, edge_schema=graph.edge_schema, use_vertex_attributes=use_vertex_attributes) for secondary_edge in graph_allowed_edges]) else: # if the pattern edge is None, you can use any edge from the graph probs = np.repeat(1.0, len(graph_allowed_edges)) probs_sum = probs.sum() if probs_sum == 0: # we cannot select anything, so continue by selecting another edge # also update the available vertices available_vertices.remove(current_pattern_vertex) continue else: # we are able to select an edge in the graph, so select one and compute the similarity new_probs = probs / probs.sum() selected_graph_edge_index = np.random.choice(np.arange(len(new_probs)), 1, p=new_probs)[0] selected_graph_edge = graph_allowed_edges[selected_graph_edge_index] computed_similarity = probs[selected_graph_edge_index] already_visited_graph_edges.add(selected_graph_edge.original_edge_id) # edges_scores[pattern_edge_index] += computed_similarity # OLD if pattern_attributes[pattern_edge_index][pattern_instance_index] is not None: # NEW - update score only if the edge wasn't None # walk_score += computed_similarity * edge_weights[pattern_edge_index] # NEW walk_score += computed_similarity # NEW # current_graph_vertex = selected_graph_edge.to_vertex_id # available_vertices.add(pattern_to_vertex) if pattern_to_vertex not in already_tried_vertices: # if the vertex is not in vertex_mapping, it means that it is not in the available_vertices, # so add it there available_vertices.add(pattern_to_vertex) # already_tried_vertices.add(pattern_to_vertex) # add the dst vertices to he mapping (from pattern dst vertex to graph dst vertex) vertex_mapping[pattern_to_vertex] = selected_graph_edge.to_vertex_id # after walk is done, save the walk score divided by the walk length if walk_length > 0: walks_scores.append(walk_score / walk_length) else: walks_scores.append(0.0) # now take the maximum walk score and save it as a score of this pattern instance: all_total_scores.append(max(walks_scores)) # NOW RETURN mean across all pattern instances return np.array(all_total_scores).mean()
import logging # connecting assisting functions, wrappers around psycopg def QueryDatabase(query, SETTINGS=None, SCHEMA=None, SSH=None): """! Query either the 'data lake' postgres db, or the heap-rs3 'data warehouse'. """ if SSH: try: prod_tunnel except NameError: prod_tunnel = CreateSSHTunnel() prod_tunnel.start() import mysql.connector try: mydb = mysql.connector.connect( user=SETTINGS.user, password=<PASSWORD>, host='127.0.0.1', database=SETTINGS.database, port=prod_tunnel.local_bind_port) mycursor = mydb.cursor() mycursor.execute(query) res = mycursor.fetchall() mycursor.close() mydb.close() return res except mysql.connector.errors.ProgrammingError: logging.error(query, exc_info=True) exit() finally: mycursor.close() mydb.close() else: mydb = _getDBConnector(SETTINGS=SETTINGS, SCHEMA=SCHEMA) mycursor = mydb.cursor() mycursor.execute(query) res = mycursor.fetchall() mycursor.close() mydb.close() return res def UpdateTable(query, SETTINGS=None): """! Execute a command on the specified database (DATABASE). Does not return any results. """ if query == '' or query is None: return None import psycopg2 try: mydb = _getDBConnector(SETTINGS=SETTINGS) mycursor = mydb.cursor() mycursor.execute(query) mydb.commit() except (Exception, psycopg2.Error) as error: logging.warning("Error in update operation: {}".format(error), exc_info=True) finally: # closing database connection. if (mydb): mycursor.close() mydb.close() class ConnectionSettings(): host_name = '' password = '' database = '' user = '' options = '' port = 5432 def _getDbConnectionSettings(DATABASE="store", SCHEMA=None): global rs_tunnel connectionSettings = ConnectionSettings() if DATABASE == "warehouse": connectionSettings.host_name = os.environ.get('WAREHOUSE_DB') connectionSettings.password = os.environ.get('POSTGRE_WAREHOUSE_P') connectionSettings.database = 'main_production' connectionSettings.user='postgres' elif DATABASE == "dev": connectionSettings.host_name = 'localhost' connectionSettings.password = '<PASSWORD>' connectionSettings.database = 'postgres' connectionSettings.user='postgres' elif DATABASE == "staging": connectionSettings.host_name = os.environ.get('STAGING_DB') connectionSettings.password = os.environ.get('POSTGRE_P2') connectionSettings.database = 'postgres' connectionSettings.user='postgres' elif DATABASE == "segment": connectionSettings.host_name = os.environ.get('SEGMENT_DB') connectionSettings.password = os.environ.get('SEGMENT_PW') connectionSettings.database = 'segment' connectionSettings.user = os.environ.get('SEGMENT_USER') connectionSettings.port = os.environ.get('SEGMENT_PORT') elif DATABASE == "redshift" or DATABASE == "heap" or DATABASE == "stitch": if os.environ.get('SSH_HOST'): try: rs_tunnel except NameError: rs_tunnel = CreateSSHTunnel(REMOTE=os.environ.get('REDSHIFT_HOST'), PORT=int(os.environ.get('REDSHIFT_PORT'))) rs_tunnel.start() connectionSettings.port = rs_tunnel.local_bind_port connectionSettings.host_name = '127.0.0.1' else: connectionSettings.host_name = os.environ.get('REDSHIFT_HOST') connectionSettings.port = int(os.environ.get('REDSHIFT_PORT')) connectionSettings.user = os.environ.get('REDSHIFT_USER') connectionSettings.password = os.<PASSWORD>.get('REDSHIFT_PASS') if DATABASE == "redshift": connectionSettings.database = os.environ.get('REDSHIFT_DB') elif DATABASE == "stitch": connectionSettings.database = "stitch_data" connectionSettings.options = "-c search_path=hubspot" # set schema for stitch data. At the moment hardcoded to hubspot else: connectionSettings.database = "heap_db" connectionSettings.options = "-c search_path=main_production_clean" if not SCHEMA is None: connectionSettings.options = "-c search_path={}".format(SCHEMA) else: connectionSettings.host_name = os.environ.get('DATASTORE_DB') connectionSettings.password = <PASSWORD>('POST<PASSWORD>') connectionSettings.database = 'postgres' connectionSettings.user='postgres' return connectionSettings def _getDBConnector(DATABASE="store", SCHEMA=None, SETTINGS=None): """! Connect to AWS postgres db""" import psycopg2 # for PostgreSQL connections if not SETTINGS is None: connectionSettings = SETTINGS else: connectionSettings = GetDbConnectionSettings(DATABASE, SCHEMA=SCHEMA) mydb = psycopg2.connect( host=connectionSettings.host_name, user=connectionSettings.user, password=<PASSWORD>Settings.password, database=connectionSettings.database, port=connectionSettings.port, options=connectionSettings.options ) return mydb #### SSH functions def CreateSSHTunnel(REMOTE=None, PORT=3306): global tunnel import os import paramiko import sshtunnel if REMOTE is None: REMOTE = os.getenv("DBHOST") logging.debug('creating SSH tunnel to {}'.format(REMOTE)) mypkey = paramiko.RSAKey.from_private_key_file('/Users/benjaminsmith/.ssh/' + 'id_rsa', password=os.getenv("SSH_PW")) tunnel = sshtunnel.SSHTunnelForwarder( (os.environ.get('SSH_HOST'), 22), ssh_username=os.getenv("SSH_USER"), ssh_password=os.getenv("SSH_PW"), ssh_pkey=mypkey, remote_bind_address=(REMOTE, PORT)) tunnel.daemon_forward_servers = True # this was an idea to fix a connection hang, but it doesn't seem to matter. return tunnel def CleanUpSSHTunnel(): logging.debug('checking for SSH tunnels to cleanup...') global rs_tunnel, prod_tunnel try: tunnel tunnel.stop(force=True) except: pass try: prod_tunnel.stop(force=True) except: pass try: rs_tunnel.stop(force=True) except: pass # hack here: if we somehow lose a handle to an SSH tunnel it won't get shut down. So we look for paramiko transport threads and close them. import threading [t.close() for t in threading.enumerate() if t.__class__.__name__ == "Transport"]
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Standard library from __future__ import absolute_import, division, print_function import argparse import ConfigParser import io import re import time default_iterations = 100 default_old_config = "../wtop.cfg" default_new_config = "robots_excerpt.ini" file_user_agents = "robot_user_agents.txt" def parser_setup(): """Instantiate, configure, and return an argarse instance.""" ap = argparse.ArgumentParser(description=__doc__) # unable to define default for files due to # http://bugs.python.org/issue16399 ap.add_argument("-o", "--old-config", metavar="OLD_CONFIG", type=file, help="Old config file (default: %s)" % default_old_config) ap.add_argument("-n", "--new-config", metavar="NEW_CONFIG", type=file, help="New config file (default: %s)" % default_new_config) ap.add_argument("-i", "--iterations", metavar="INT", type=int, default=default_iterations, help="Number of benchmarking iterations (default: " "%(default)s)") args = ap.parse_args() if not args.old_config: args.old_config = default_old_config if not args.new_config: args.new_config = default_new_config return args def read_and_compile_pattern_from_file(config_file): """Read INI config file and compile robots regex from robots key in patterns section. """ config = ConfigParser.ConfigParser() config.readfp(open(config_file)) re_robots = re.compile(config.get("patterns", "robots"), re.I) return re_robots def evalute_robots_pattern(re_robots): """Evalute robots regex for hits and misses against robots user agents file. """ matched = 0 missed = 0 i = 1 with io.open(file_user_agents, "r", encoding="utf8") as fh: for line in fh: if re_robots.search(line): matched += 1 # print("+%s:" % i, line.strip()) else: missed += 1 # print("-%s:" % i, line.strip()) i += 1 return matched, missed def evaluate_config(config_file, iterations): """Evalute config's robots pattern and benchmark duration.""" # Reading the pattern and compling is not included in the duration. As the # data is quickly supplied by the file system cache, it becomes irrelevent. re_robots = read_and_compile_pattern_from_file(config_file) matched = int() missed = int() duration_total = float() for i in xrange(0, iterations): start = time.clock() matched, missed = evalute_robots_pattern(re_robots) end = time.clock() duration = end - start duration_total += duration return matched, missed, duration_total / iterations def display_results(name, config_file, data, old_data=None): """Display results of config evaluation.""" matched, missed, duration = data msg = "%s Config (%s)" % (name, config_file) print(msg) print("=" * len(msg)) if old_data is None: print("matched: %5d" % matched) print("missed: %5d" % missed) print("duration:%9.3fs" % duration) print else: old_matched, old_missed, old_duration = old_data print("matched: %5d" % matched,) if matched > old_matched: adj = "more" else: adj = "less" diff_abs = abs(old_matched - matched) diff_percent = diff_abs / float(old_matched) * 100 print(" (%.0f%% %s)" % (diff_percent, adj)) print("missed: %5d" % missed) print("duration:%9.3fs" % duration,) if duration < old_duration: adj = "faster" else: adj = "slower" diff_abs = abs(old_duration - duration) diff_percent = diff_abs / float(old_duration) * 100 print("(%.0f%% %s)" % (diff_percent, adj)) def main(): # Command Line Options args = parser_setup() # Old config old_data = evaluate_config(args.old_config, args.iterations) display_results("Old", args.old_config, old_data) # New config new_data = evaluate_config(args.new_config, args.iterations) display_results("New", args.new_config, new_data, old_data) if __name__ == "__main__": main()
from datetime import datetime from glob import glob from asyncio import sleep import os from dotenv import load_dotenv from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger from discord import Embed, File from discord.errors import HTTPException, Forbidden from discord.ext.commands import Bot as BotBase from discord.ext.commands import Context, when_mentioned_or from discord.ext.commands import (CommandNotFound, BadArgument, MissingRequiredArgument, CommandOnCooldown) from ..db import db load_dotenv() PREFIX = "!" COGS = [os.path.split(path)[1][:-3] for path in glob("./lib/cogs/*.py")] # COGS = [path.split("\\")[-1][:-3] for path in glob("./lib/cogs/*.py")] IGNORE_EXCEPTIONS = (CommandNotFound, BadArgument) def get_prefix(bot, message): return when_mentioned_or(PREFIX)(bot, message) class Ready(object): def __init__(self): for cog in COGS: setattr(self, cog, False) def ready_up(self, cog): setattr(self, cog, True) print(f" {cog} cog ready") def all_ready(self): return all([getattr(self,cog) for cog in COGS]) class Bot(BotBase): def __init__(self): self.PREFIX = PREFIX self.ready = False self.cogs_ready = Ready() self.guild = None self.scheduler = AsyncIOScheduler() db.autosave(self.scheduler) OWNER_ID=os.getenv("OWNER_ID") super().__init__(command_prefix=get_prefix, owner_ids=OWNER_ID) #intents=Intents.all() def setup(self): for cog in COGS: self.load_extension(f"lib.cogs.{cog}") print(f" {cog} cog loaded") print("- set up complete!") def run(self, version): self.VERSION = version print("running setup. . .") self.setup() self.TOKEN = os.getenv("BOT_TOKEN") print("running bot. . .") super().run(self.TOKEN, reconnect=True) async def process_commands(self, message): ctx = await self.get_context(message, cls=Context) if ctx.command is not None and ctx.guild is not None: if not self.ready: await ctx.send("Healbot is charging up. Please wait to use commands.") else: await self.invoke(ctx) async def rules_reminder(self): await self.stdout.send("Please follow the rules!") async def on_command(ctx, error): print("-- Bot connected!") async def on_disconnect(): print("-- Bot disconnected!") async def on_error(self, err, *args, **kwargs): if err == "on_command_error": await args[0].send(":x: Incorrect command") raise async def on_command_error(self, ctx, exc): if any([isinstance(exc, error) for error in IGNORE_EXCEPTIONS]): pass elif isinstance(exc, MissingRequiredArgument): await ctx.send(":x: One or more required arguments are missing!") elif isinstance(exc, CommandOnCooldown): await ctx.send(f":x: Wait ``{exc.retry_after:,.0f} seconds`` to use this command again.") elif hasattr(exc, "original"): if isinstance(exc.original, Forbidden): await ctx.send(":x: I do not have the permissions to perform that command.") else: raise exc.original else: raise exc async def on_ready(self): if not self.ready: GUILD=os.getenv("GUILD_ID") CHANNEL=os.getenv("CHANNEL_ID") self.guild = self.get_guild(int(GUILD)) self.stdout = self.get_channel(int(CHANNEL)) self.scheduler.add_job(self.rules_reminder, CronTrigger(day_of_week=0, hour=1, minute=0, second=0)) self.scheduler.start() while not self.cogs_ready.all_ready(): await sleep(0.5) embed = Embed(title="Feel... Hear... Think...", description=f"Always ready to help the Warrior of Light, kupo!", colour=0x16C77D) await self.stdout.send(embed=embed, delete_after=5) self.ready = True print("-- bot ready") else: print("-- bot reconnected") async def on_message(self,message): if not message.author.bot: await self.process_commands(message) bot = Bot()
# ------------------------------------------------------------------------------ # Unit tests for FactIndex and FactMap. # ------------------------------------------------------------------------------ import unittest import operator from .support import check_errmsg from clingo import Control, Number, String, Function, SymbolType # Official Clorm API imports for the core complements from clorm.orm import IntegerField, StringField, ConstantField, \ Predicate, ComplexTerm, path, hashable_path # Implementation imports from clorm.orm.factcontainers import FactIndex, FactMap, FactSet from clorm.orm.core import notcontains #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ __all__ = [ 'FactIndexTestCase', 'FactMapTestCase', ] #------------------------------------------------------------------------------ # #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # Test the FactIndex class #------------------------------------------------------------------------------ class FactIndexTestCase(unittest.TestCase): def setUp(self): class Afact(Predicate): num1=IntegerField() str1=StringField() class Bfact(Predicate): num1=IntegerField() str1=StringField() self.Afact = Afact self.Bfact = Bfact #-------------------------------------------------------------------------- # Alternative for accessing elements - this looks at some performance # differences # -------------------------------------------------------------------------- def _test_getter_performance(self): import timeit testsetup=''' from clorm import Predicate, IntegerField import random from operator import attrgetter class F(Predicate): anum = IntegerField randlist=[] for i in range(0,10000): randlist.append(F(random.randint(1,100))) ''' teststmt1=''' randlist.sort(key=lambda x: x.anum) ''' teststmt2=''' randlist.sort(key=F.anum) ''' teststmt3=''' randlist.sort(key=F.anum.meta.attrgetter) ''' teststmt4=''' randlist.sort(key=attrgetter('anum')) ''' repeat=1000 print("Lambda: {}".format( timeit.timeit(stmt=teststmt1,setup=testsetup,number=repeat))) print("Path: {}".format( timeit.timeit(stmt=teststmt2,setup=testsetup,number=repeat))) print("PathAttrGetter: {}".format( timeit.timeit(stmt=teststmt3,setup=testsetup,number=repeat))) print("RawAttrGetter: {}".format( timeit.timeit(stmt=teststmt4,setup=testsetup,number=repeat))) #-------------------------------------------------------------------------- # #-------------------------------------------------------------------------- def test_create(self): Afact = self.Afact fi1 = FactIndex(Afact.num1) self.assertTrue(type(fi1), FactIndex) self.assertFalse(fi1) # Should only accept fields with self.assertRaises(TypeError) as ctx: f2 = FactIndex(1) with self.assertRaises(TypeError) as ctx: f2 = FactIndex(Afact) def test_add(self): Afact = self.Afact Bfact = self.Bfact fi1 = FactIndex(Afact.num1) fi2 = FactIndex(Afact.str1) self.assertEqual(fi1.keys, []) fi1.add(Afact(num1=1, str1="c")) fi2.add(Afact(num1=1, str1="c")) self.assertEqual(fi1.keys, [1]) self.assertEqual(fi2.keys, ["c"]) fi1.add(Afact(num1=2, str1="b")) fi2.add(Afact(num1=2, str1="b")) self.assertEqual(fi1.keys, [1,2]) self.assertEqual(fi2.keys, ["b","c"]) fi1.add(Afact(num1=3, str1="b")) fi2.add(Afact(num1=3, str1="b")) self.assertEqual(fi1.keys, [1,2,3]) self.assertEqual(fi2.keys, ["b","c"]) def test_remove(self): Afact = self.Afact Bfact = self.Bfact af1a = Afact(num1=1, str1="a") af2a = Afact(num1=2, str1="a") af2b = Afact(num1=2, str1="b") af3a = Afact(num1=3, str1="a") af3b = Afact(num1=3, str1="b") fi = FactIndex(Afact.num1) for f in [ af1a, af2a, af2b, af3a, af3b ]: fi.add(f) self.assertEqual(fi.keys, [1,2,3]) fi.remove(af1a) self.assertEqual(fi.keys, [2,3]) fi.discard(af1a) with self.assertRaises(KeyError) as ctx: fi.remove(af1a) fi.remove(af2a) self.assertEqual(fi.keys, [2,3]) fi.remove(af3a) self.assertEqual(fi.keys, [2,3]) fi.remove(af2b) self.assertEqual(fi.keys, [3]) fi.remove(af3b) self.assertEqual(fi.keys, []) def test_find(self): Afact = self.Afact af1a = Afact(num1=1, str1="a") af2a = Afact(num1=2, str1="a") af2b = Afact(num1=2, str1="b") af3a = Afact(num1=3, str1="a") af3b = Afact(num1=3, str1="b") fi = FactIndex(Afact.num1) allfacts = [ af1a, af2a, af2b, af3a, af3b ] for f in allfacts: fi.add(f) self.assertEqual(set(fi.find(operator.eq, 1)), set([af1a])) self.assertEqual(set(fi.find(operator.eq, 2)), set([af2a, af2b])) self.assertEqual(set(fi.find(operator.ne, 5)), set(allfacts)) self.assertEqual(set(fi.find(operator.ne, 0)), set(allfacts)) self.assertEqual(set(fi.find(operator.ne, 3)), set([af1a,af2a,af2b])) self.assertEqual(set(fi.find(operator.eq, 5)), set([])) self.assertEqual(set(fi.find(operator.lt, 1)), set([])) self.assertEqual(set(fi.find(operator.lt, 2)), set([af1a])) self.assertEqual(set(fi.find(operator.le, 2)), set([af1a, af2a, af2b])) self.assertEqual(set(fi.find(operator.gt, 2)), set([af3a, af3b])) self.assertEqual(set(fi.find(operator.ge, 3)), set([af3a, af3b])) self.assertEqual(set(fi.find(operator.gt, 3)), set([])) self.assertEqual(set(fi.find(operator.gt, 0)), set(allfacts)) self.assertEqual(set(fi.find(operator.ge, 0)), set(allfacts)) def test_find_ordering(self): Afact = self.Afact af1 = Afact(num1=1, str1="a") af3 = Afact(num1=3, str1="a") af5 = Afact(num1=5, str1="a") af7 = Afact(num1=7, str1="a") af9 = Afact(num1=9, str1="a") fi = FactIndex(Afact.num1) allfacts = [ af1, af3, af5, af7, af9 ] for f in allfacts: fi.add(f) # Checking ordering of standard operators self.assertEqual(list(fi.find(operator.ne, 6)), allfacts) self.assertEqual(list(fi.find(operator.ne, 0)), allfacts) self.assertEqual(list(fi.find(operator.ne, 3)), [af1,af5,af7,af9]) self.assertEqual(list(fi.find(operator.lt, 3)), [af1]) self.assertEqual(list(fi.find(operator.lt, 4)), [af1,af3]) self.assertEqual(list(fi.find(operator.le, 3)), [af1, af3]) self.assertEqual(list(fi.find(operator.gt, 2)), [af3, af5,af7,af9]) self.assertEqual(list(fi.find(operator.ge, 0)), allfacts) # The contains/notcontains operator self.assertEqual(list(fi.find(operator.contains,[])), []) self.assertEqual(list(fi.find(operator.contains,[3])), [af3]) self.assertEqual(list(fi.find(operator.contains,[4])), []) self.assertEqual(list(fi.find(operator.contains,[4,7])), [af7]) self.assertEqual(list(fi.find(operator.contains,[3,7])), [af3,af7]) self.assertEqual(list(fi.find(notcontains,[])), allfacts) self.assertEqual(list(fi.find(notcontains,[4])), allfacts) self.assertEqual(list(fi.find(notcontains,[5,6])), [af1,af3,af7,af9]) self.assertEqual(list(fi.find(notcontains,[3,7])), [af1,af5,af9]) # Checking reverse ordering for standard operators allfacts.reverse() self.assertEqual(list(fi.find(operator.ne, 6,reverse=True)), allfacts) self.assertEqual(list(fi.find(operator.ne, 0,reverse=True)), allfacts) self.assertEqual(list(fi.find(operator.ne, 3,reverse=True)), [af9,af7,af5,af1]) self.assertEqual(list(fi.find(operator.lt, 4,reverse=True)), [af3,af1]) self.assertEqual(list(fi.find(operator.le, 3,reverse=True)), [af3, af1]) self.assertEqual(list(fi.find(operator.gt, 2,reverse=True)), [af9, af7,af5,af3]) self.assertEqual(list(fi.find(operator.ge, 0,reverse=True)), allfacts) def test_clear(self): Afact = self.Afact fi = FactIndex(Afact.num1) fi.add(Afact(num1=1, str1="a")) fi.clear() self.assertEqual(fi.keys,[]) #-------------------------------------------------------------------------- # Test the support for indexes of subfields #-------------------------------------------------------------------------- def test_subfields(self): class CT(ComplexTerm): num1=IntegerField() str1=StringField() class Fact(Predicate): ct1=CT.Field() ct2=(IntegerField(),IntegerField()) fi1 = FactIndex(Fact.ct1.num1) fi2 = FactIndex(Fact.ct2[1]) fi3 = FactIndex(Fact.ct1) f1=Fact(CT(10,"a"),(1,4)) f2=Fact(CT(20,"b"),(2,3)) f3=Fact(CT(30,"c"),(5,2)) f4=Fact(CT(40,"d"),(6,1)) fi1.add(f1); fi2.add(f1); fi3.add(f1) fi1.add(f2); fi2.add(f2); fi3.add(f2) fi1.add(f3); fi2.add(f3); fi3.add(f3) fi1.add(f4); fi2.add(f4); fi3.add(f4) self.assertEqual(fi1.keys, [10,20,30,40]) self.assertEqual(fi2.keys, [1,2,3,4]) self.assertEqual(set(fi3.keys), set([CT(10,"a"),CT(20,"b"),CT(30,"c"),CT(40,"d")])) #------------------------------------------------------------------------------ # Test FactMap #------------------------------------------------------------------------------ class FactMapTestCase(unittest.TestCase): def setUp(self): class Afact(Predicate): anum=IntegerField aconst=ConstantField self.Afact = Afact def tearDown(self): pass #-------------------------------------------------------------------------- # #-------------------------------------------------------------------------- def test_factmap_basics(self): Afact = self.Afact hp = hashable_path af1 = Afact(1,"bbb") af2 = Afact(2,"ccc") fm = FactMap(Afact, [Afact.anum]) self.assertFalse(fm) self.assertEqual(fm.predicate, Afact) self.assertEqual(list(fm.path2factindex.keys()), [hp(Afact.anum)]) fm.add_fact(af1) self.assertTrue(fm) self.assertEqual(set(fm.factset), set([af1])) self.assertEqual(set(fm.path2factindex[hp(Afact.anum)]), set([af1])) fm.pop() self.assertFalse(fm) self.assertFalse(set(fm.factset)) self.assertFalse(set(fm.path2factindex[hp(Afact.anum)])) fm.add_facts([af1,af2]) self.assertTrue(fm) self.assertEqual(set(fm.factset), set([af1,af2])) fm.discard(af1) self.assertTrue(fm) self.assertEqual(set(fm.factset), set([af2])) fm.clear() self.assertFalse(fm) self.assertFalse(set(fm.factset)) #-------------------------------------------------------------------------- # #-------------------------------------------------------------------------- def test_set_ops(self): def fm2set(fm): return set(fm.factset) Afact = self.Afact af1 = Afact(anum=1, aconst="a") af2 = Afact(anum=2, aconst="a") af3 = Afact(anum=3, aconst="c") af4 = Afact(anum=4, aconst="c") # Test union fm1 = FactMap(Afact, [Afact.anum]) fm2 = FactMap(Afact, [Afact.aconst]) fm1.add_facts([af1,af2]) fm2.add_facts([af3]) r=fm1.union(fm1); self.assertEqual(fm2set(r),set([af1,af2])) r=fm1.union(fm2); self.assertEqual(fm2set(r),set([af1,af2,af3])) r=fm1.union(fm2,[af4]); self.assertEqual(fm2set(r),set([af1,af2,af3,af4])) # Test intersection fm1 = FactMap(Afact, [Afact.anum]) fm2 = FactMap(Afact, [Afact.aconst]) fm1.add_facts([af1,af2]) fm2.add_facts([af2,af3]) r=fm1.intersection(fm1); self.assertEqual(fm2set(r),set(fm2set(fm1))) r=fm1.intersection(fm2); self.assertEqual(fm2set(r),set([af2])) r=fm1.intersection(fm2,[af2,af3,af4]); self.assertEqual(fm2set(r),set([af2])) r=fm1.intersection(fm2,[af3,af4]); self.assertEqual(fm2set(r),set()) # Test difference fm1 = FactMap(Afact, [Afact.anum]) fm2 = FactMap(Afact, [Afact.aconst]) fm1.add_facts([af1,af2]) fm2.add_facts([af2,af3]) r=fm1.difference(fm1); self.assertEqual(fm2set(r),set([])) r=fm1.difference([af1]); self.assertEqual(fm2set(r),set([af2])) r=fm1.difference(fm2); self.assertEqual(fm2set(r), set([af1])) # Test symmetric difference fm1 = FactMap(Afact, [Afact.anum]) fm2 = FactMap(Afact, [Afact.aconst]) fm1.add_facts([af1,af2]) fm2.add_facts([af2,af3]) r=fm1.symmetric_difference(fm1); self.assertEqual(fm2set(r),set()) r=fm1.symmetric_difference(fm2); self.assertEqual(fm2set(r),set([af1,af3])) # Test update() fm1 = FactMap(Afact, [Afact.anum]) fm2 = FactMap(Afact, [Afact.aconst]) fm1.add_facts([af1,af2]) fm2.add_facts([af2,af3]) fm1.update([af3],[af4]) self.assertEqual(fm2set(fm1), set([af1,af2,af3,af4])) # Test intersection() fm1 = FactMap(Afact, [Afact.anum]) fm2 = FactMap(Afact, [Afact.aconst]) fm1.add_facts([af1,af2]) fm2.add_facts([af2,af3]) fm1.intersection_update(fm2) self.assertEqual(fm2set(fm1), set([af2])) fm1.add_facts([af1,af2]) fm1.intersection_update([af3]) self.assertEqual(fm2set(fm1), set()) # Test difference_update() fm1 = FactMap(Afact, [Afact.anum]) fm2 = FactMap(Afact, [Afact.aconst]) fm1.add_facts([af1,af2]) fm2.add_facts([af2,af3]) fm1.difference_update(fm2) self.assertEqual(fm2set(fm1), set([af1])) # Test symmetric_difference_update() fm1 = FactMap(Afact, [Afact.anum]) fm2 = FactMap(Afact, [Afact.aconst]) fm1.add_facts([af1,af2]) fm2.add_facts([af2,af3]) fm1.symmetric_difference_update(fm2) self.assertEqual(fm2set(fm1), set([af1,af3])) #-------------------------------------------------------------------------- # Test that subclass factbase works and we can specify indexes #-------------------------------------------------------------------------- def test_factmap_copy(self): Afact = self.Afact hp = hashable_path af1 = Afact(anum=1, aconst="a") af2 = Afact(anum=2, aconst="a") af3 = Afact(anum=3, aconst="c") af4 = Afact(anum=4, aconst="c") fm1 = FactMap(Afact,[Afact.anum]) fm1.add_facts([af1,af2,af3,af4]) fm2 = fm1.copy() self.assertTrue(not fm1 is fm2) self.assertTrue(not fm1.factset is fm2.factset) self.assertTrue(not fm1.path2factindex is fm2.path2factindex) self.assertTrue(not fm1.path2factindex[hp(Afact.anum)] \ is fm2.path2factindex[hp(Afact.anum)]) self.assertEqual(fm1.path2factindex, fm2.path2factindex) #------------------------------------------------------------------------------ # main #------------------------------------------------------------------------------ if __name__ == "__main__": raise RuntimeError('Cannot run modules')
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import sys import yaml_util class InstallationParameters(object): """Describes a standard release installation layout. Contains constants for where different parts of the release are installed. Attributes: USER_CONFIG_DIR: Path to directory containing installation configuration files for the indivual subsystems. LOG_DIR: Path to directory where individual log files are written. SUBSYSTEM_ROOT_DIR: Path to directory containing spinnaker subsystem installation directories. SPINNAKER_INSTALL_DIR: Path to the root spinnaker installation directory. UTILITY_SCRIPT_DIR: Path to directory containing spinnaker maintainence and other utility scripts. EXTERNAL_DEPENDENCY_SCRIPT_DIR: Path to directory containing maintainence and utility scripts for managing dependencies outside spinnaker itself. INSTALLED_CONFIG_DIR: Path to directory containing the master configuration files for the release. These are intended to be read-only. DECK_INSTALL_DIR: Path to directory where deck is installed, which is typically different from the other spinnaker subsystems. HACK_DECK_SETTINGS_FILENAME: The name of the settings file for deck is non-standard and recorded here for the time being. """ USER_CONFIG_DIR = '/root/.spinnaker' LOG_DIR = '/opt/spinnaker/logs' SUBSYSTEM_ROOT_DIR = '/opt' SPINNAKER_INSTALL_DIR = '/opt/spinnaker' UTILITY_SCRIPT_DIR = '/opt/spinnaker/scripts' EXTERNAL_DEPENDENCY_SCRIPT_DIR = '/opt/spinnaker/scripts' INSTALLED_CONFIG_DIR = SPINNAKER_INSTALL_DIR + '/config' DECK_INSTALL_DIR = '/var/www' HACK_DECK_SETTINGS_FILENAME = 'settings.js' ENVIRONMENT_VARIABLE_PATH = '/etc/default/spinnaker' class Configurator(object): """Defines methods for manipulating spinnaker configuration data.""" @property def bindings(self): """Returns the system level yaml bindings. This is spinnaker.yml with spinnaker-local imposed on top of it. """ if self.__bindings is None: self.__bindings = yaml_util.load_bindings( self.installation_config_dir, self.user_config_dir) return self.__bindings @property def installation(self): """Returns the installation configuration (directory locations).""" return self.__installation @property def installation_config_dir(self): """Returns the location of the system installed config directory.""" return self.__installation.INSTALLED_CONFIG_DIR @property def deck_install_dir(self): """Returns the location of the deck directory for the active settings.js""" if not self.__installation.DECK_INSTALL_DIR: pwd = os.environ.get('PWD', '.') deck_path = os.path.join(pwd, 'deck') if not os.path.exists(deck_path): error = ('To operate on deck, this program must be run from your' ' build directory containing the deck project subdirectory' ', not "{pwd}".'.format(pwd=pwd)) raise RuntimeError(error) self.__installation.DECK_INSTALL_DIR = deck_path return self.__installation.DECK_INSTALL_DIR @property def user_config_dir(self): """Returns the user (or system's) .spinnaker directory for overrides.""" return self.__installation.USER_CONFIG_DIR def __init__(self, installation_parameters=None, bindings=None): """Constructor Args: installation_parameters [InstallationParameters] if None then use default bindings [YamlBindings] Allows bindings to be explicitly injected for testing. Otherwise they are loaded on demand. """ if not installation_parameters: installation_parameters = InstallationParameters() if os.geteuid(): # If we are not running as root and there is an installation on # this machine as well as a user/.spinnaker directory then it is # ambguous which we are validating. For saftey we'll force this # to be the normal system installation. Warn that we are doing this. user_config = os.path.join(os.environ['HOME'], '.spinnaker') deck_dir = installation_parameters.DECK_INSTALL_DIR if os.path.exists('/root/.spinnaker'): user_config = '/root/.spinnaker' if os.path.exists(user_config): sys.stderr.write( 'WARNING: You have both personal and system Spinnaker' ' configurations on this machine. Assuming the system' ' configuration.\n') else: # Discover it from build directory if needed. deck_dir = None # If we arenot root, allow for a non-standard installation location. installation_parameters.INSTALLED_CONFIG_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), '../../config')) installation_parameters.USER_CONFIG_DIR = user_config installation_parameters.DECK_INSTALL_DIR = deck_dir self.__installation = installation_parameters self.__bindings = bindings # Either injected or loaded on demand. self.load_environment_variables() @staticmethod def export_environment_variables(content): for match in re.finditer('^([^\s]+?)=([^\n]*)(?:\#.+)?', content, re.MULTILINE): os.environ[match.group(1)] = match.group(2) def load_environment_variables(self, path=None): if not path: path = self.__installation.ENVIRONMENT_VARIABLE_PATH try: with open(path, 'r') as f: content = f.read() self.export_environment_variables(content) except IOError: pass def update_deck_settings(self): """Update the settings.js file from configuration info.""" source_path = os.path.join(self.installation_config_dir, 'settings.js') with open(source_path, 'r') as f: source = f.read() settings = self.process_deck_settings(source) target_path = os.path.join(self.deck_install_dir, 'settings.js') print 'Rewriting deck settings in "{path}".'.format(path=target_path) with open(target_path, 'w') as f: f.write(''.join(settings)) def process_deck_settings(self, source): offset = source.find('// BEGIN reconfigure_spinnaker') if offset < 0: raise ValueError( 'deck settings file does not contain a' ' "# BEGIN reconfigure_spinnaker" marker.') end = source.find('// END reconfigure_spinnaker') if end < 0: raise ValueError( 'deck settings file does not contain a' ' "// END reconfigure_spinnaker" marker.') original_block = source[offset:end] # Remove all the explicit declarations in this block # Leaving us with just comments block = re.sub('\n\s*let\s+\w+\s*=(.+)\n', '\n', original_block) settings = [source[:offset]] # Now iterate over the comments looking for let specifications offset = 0 for match in re.finditer('//\s*let\s+(\w+)\s*=\s*(.+?);?\n', block) or []: settings.append(block[offset:match.end()]) offset = match.end() name = match.group(1) value = self.bindings.replace(match.group(2)) settings.append('let {name} = {value!r};\n'.format( name=name, value=value)) settings.append(block[offset:]) settings.append(source[end:]) return ''.join(settings)
<reponame>youngqqcn/QBlockChainNotes #!coding:utf8 #author:yqq #date:2020/5/11 0011 10:10 #description: from binascii import hexlify from eth_account.datastructures import SignedTransaction from eth_typing import URI, Address, HexStr, BlockNumber, HexAddress, ChecksumAddress from eth_utils import to_checksum_address from web3.exceptions import TimeExhausted from web3.types import TxReceipt, BlockData from src.config.constant import ETH_FULL_NODE_RPC_URL, WithdrawStatus, ETH_CHAIN_ID, \ ERC20_GAS_LIMIT from src.consumers.consumer_base import TransferFuncResponse from src.lib.token_abi.abi import EIP20_ABI from web3 import Web3, HTTPProvider # from web3.auto import w3 from src.lib.pg_utils import timestamp_to_datatime def sign_and_sendtransaction(myweb3, unsigned_tranaction, private_key : str ) -> TransferFuncResponse: signed_tx = myweb3.eth.account.sign_transaction(transaction_dict=unsigned_tranaction, private_key=private_key) assert isinstance(signed_tx, SignedTransaction) print(hexlify(signed_tx.rawTransaction)) print(hexlify(signed_tx.hash)) txhash_ret = myweb3.eth.sendRawTransaction(signed_tx.rawTransaction) print( f'tx_hash: {hexlify( txhash_ret)}' ) rsp = TransferFuncResponse() rsp.transaction_status = WithdrawStatus.transaction_status.PENDING # 广播出去了, 就是pending rsp.confirmations = 0 rsp.block_height = 0 rsp.tx_hash = '0x' + hexlify(txhash_ret).decode('latin1') # hexlify(signed_tx.hash) # try: # receipt = myweb3.eth.waitForTransactionReceipt( # transaction_hash=txhash_ret, # timeout=1, # 超时时间 秒 , 没查到就抛异常 web3.exceptions.TimeExhausted # poll_latency=0.5 # 每隔多少秒 请求一次 # ) # # print(receipt) # assert isinstance(receipt, TxReceipt) # # if receipt['status'] == 1: # rsp.transaction_status = WithdrawStatus.transaction_status.SUCCESS # else: # rsp.transaction_status = WithdrawStatus.transaction_status.FAIL # # rsp.block_height = receipt['blockNumber'] # # block_data = myweb3.eth.getBlock(block_identifier=BlockNumber(rsp.block_height), full_transactions=False) # # assert isinstance(block_data, BlockData) # rsp.block_time = timestamp_to_datatime(block_data.timestamp) # # except TimeExhausted as e: # print(f'{e}') # pass return rsp def eth_transfer(priv_key : str, from_addr : str, to_addr : str, amount : float ) -> TransferFuncResponse: myweb3 = Web3(provider=HTTPProvider(endpoint_uri=ETH_FULL_NODE_RPC_URL)) # https://web3py.readthedocs.io/en/stable/web3.eth.account.html?highlight=transaction # https://web3py.readthedocs.io/en/stable/web3.eth.account.html?highlight=transaction#sign-a-transaction from_address = to_checksum_address(from_addr) #必须使用 checksum addres block_identifier = HexStr('pending') nonce = myweb3.eth.getTransactionCount(from_address, block_identifier=block_identifier) cur_gas_price = myweb3.eth.gasPrice #获取实时手续费 if cur_gas_price > Web3.toWei(500, 'gwei'): #防止手续费过高 cur_gas_price = Web3.toWei(500, 'gwei') elif cur_gas_price < Web3.toWei(50, 'gwei'): #防止手续费过小 cur_gas_price = Web3.toWei(50, 'gwei') private_key = priv_key chksum_to_address = to_checksum_address(to_addr) transaction = { 'to': to_checksum_address( chksum_to_address) , #必须使用 checksum 'value': Web3.toWei(number=amount, unit='ether'), 'gas': 21000, 'gasPrice': cur_gas_price, 'nonce': nonce } print(transaction) return sign_and_sendtransaction(myweb3=myweb3, unsigned_tranaction=transaction, private_key=private_key ) def erc20_transfer(priv_key : str, from_addr : str, contract_addr: str, token_recipient_addr : str, token_amount : float) \ -> TransferFuncResponse: myweb3 = Web3(provider=HTTPProvider(endpoint_uri=URI(ETH_FULL_NODE_RPC_URL))) # https://web3py.readthedocs.io/en/stable/web3.eth.account.html?highlight=transaction#sign-a-contract-transaction chksum_contract_address = to_checksum_address(contract_addr) contract = myweb3.eth.contract(address=chksum_contract_address, abi=EIP20_ABI) symbol = contract.functions.symbol().call() print(symbol) #判断是否是 USDT assert str(symbol) == 'USDT', 'only support USDT' decimals = contract.functions.decimals().call() print(decimals) # myweb3.eth.gasPriceStrategy # myweb3.eth.generateGasPrice() # myweb3.eth.setGasPriceStrategy() from_address = to_checksum_address(from_addr) block_identifier = HexStr('pending') nonce = myweb3.eth.getTransactionCount(from_address, block_identifier=block_identifier) cur_gas_price = myweb3.eth.gasPrice # 获取实时手续费 if cur_gas_price > Web3.toWei(500, 'gwei'): # 防止手续费过高 cur_gas_price = Web3.toWei(500, 'gwei') elif cur_gas_price < Web3.toWei(50, 'gwei'): # 防止手续费过小 cur_gas_price = Web3.toWei(50, 'gwei') # assert isinstance(contract.functions, ContractFunctions) chksum_token_recipient = to_checksum_address( token_recipient_addr ) erc20_unsigned_tx = contract.functions.transfer( chksum_token_recipient, # !!! 注意 : 只支持 ERC20_USDT myweb3.toWei(token_amount, 'mwei')) \ .buildTransaction({ 'chainId': ETH_CHAIN_ID, 'gas': ERC20_GAS_LIMIT, 'gasPrice': cur_gas_price, 'nonce': nonce }) print(erc20_unsigned_tx) private_key = priv_key return sign_and_sendtransaction(myweb3=myweb3, unsigned_tranaction=erc20_unsigned_tx, private_key=private_key)
<reponame>babraham123/tigrinya_ocr<filename>HornMorpho/l3/morpho/am_lang.py """ This file is part of L3Morpho. L3Morpho is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. L3Morpho is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with L3Morpho. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------- Author: <NAME> <<EMAIL>> Create Language, Morphology, and POSMorphology objects for Amharic. All functions specific to Amharic morphology are here (or imported from geez.py). """ from . import language from .geez import * ### Various functions that will be values of attributes of Amharic Morphology ### and POSMorphology objects. def vb_get_citation(root, fs, simplified=False, guess=False, vc_as=False): '''Return the canonical (prf, 3sm) form for the root and featstructs in featstruct set fss. If vc_as is True, preserve the voice and aspect of the original word. ''' if root == 'al_e': return "'ale" # Return root if no citation is found result = root # Unfreeze the feature structure fs = fs.unfreeze() # Update the feature structure to incorporate default (with or without vc and as) fs.update(AM.morphology['v'].citationFS if vc_as else AM.morphology['v'].defaultFS) # Refreeze the feature structure fs.freeze() # Find the first citation form compatible with the updated feature structure citation = AM.morphology['v'].gen(root, fs, from_dict=False, simplified=simplified, guess=guess) if citation: result = citation[0][0] elif not vc_as: # Verb may not occur in simplex form; try passive fs = fs.unfreeze() fs.update({'vc': 'ps'}) fs.freeze() citation = AM.morphology['v'].gen(root, fs, from_dict=False, simplified=simplified, guess=guess) if citation: result = citation[0][0] return result def n_get_citation(root, fs, simplified=False, guess=False, vc_as=False): '''Return the canonical (prf, 3sm) form for the root and featstructs in featstruct set fss. If vc_as is True, preserve the voice and aspect of the original word. ''' if fs.get('v'): # It's a deverbal noun return vb_get_citation(root, fs, simplified=simplified, guess=guess, vc_as=vc_as) else: return root def simplify(word): """Simplify Amharic orthography.""" word = word.replace("`", "'").replace('H', 'h').replace('^', '').replace('_', '') return word def orthographize(word): '''Convert phonological romanization to orthographic.''' word = word.replace('_', '').replace('I', '') return word def cop_anal2string(anal): '''Convert a copula analysis to a string. anal is ("cop", "new", "new", gramFS) ''' s = 'POS: copula' if anal[1]: s += ', root: <' + anal[1] + '>' s += '\n' fs = anal[3] if fs: sb = fs['sb'] s += ' subj:' s += arg2string(sb) if fs.get('neg'): s += ' negative\n' cj = fs.get('cj2') if cj: s += ' conjunctive suffix: ' + cj + '\n' return s def n_anal2string(anal): '''Convert a noun analysis to a string. anal is ("(*)n", root, citation, gramFS) ''' root = anal[1] citation = anal[2] fs = anal[3] deverbal = fs and fs.get('v') POS = '?POS: ' if '?' in anal[0] else 'POS: ' s = POS if deverbal: if deverbal == 'agt': s += 'agentive noun' elif deverbal == 'man': s += 'manner noun' elif deverbal == 'inf': s += 'infinitive' else: s += 'instrumental noun' if root: s += ', root: <' + root + '>' if citation: s += ', citation: ' + citation else: s += 'noun' if citation: s += ', stem: ' + citation elif root: s += ', stem: ' + root s += '\n' if fs: poss = fs.get('poss') if poss and poss.get('expl'): s += ' possessor:' s += arg2string(poss, True) gram = '' # For agent, infinitive, instrumental, give aspect and voice unless both are simple asp = fs.get('as') vc = fs.get('vc') rl = fs.get('rl') any_gram = False if deverbal and asp == 'it': gram += ' iterative' any_gram = True elif deverbal and asp == 'rc': if any_gram: gram += ',' gram += ' reciprocal' any_gram = True if deverbal and vc == 'ps': if any_gram: gram += ',' gram += ' passive' any_gram = True elif vc == 'tr': if any_gram: gram += ',' gram += ' transitive' any_gram = True elif vc == 'cs': if any_gram: gram += ',' gram += ' causative' any_gram = True if fs.get('neg'): # Only possible for infinitive if any_gram: gram += ',' gram += ' negative' any_gram = True if fs.get('plr'): if any_gram: gram += ',' gram += ' plural' any_gram = True if fs.get('def'): if any_gram: gram += ',' any_gram = True gram += ' definite' if fs.get('dis'): if any_gram: gram += ',' any_gram = True gram += ' distrib(Iyye-)' if rl and rl.get('acc'): if any_gram: gram += ',' any_gram = True gram += ' accusative' if rl and rl.get('gen'): if any_gram: gram += ',' any_gram = True gram += ' genitive' # der = fs.get('der') # if der and der.get('ass'): # if any_gram: gram += ',' # any_gram = True # gram += ' assoc(-awi)' if any_gram: s += ' grammar:' + gram + '\n' pp = fs.get('pp') cnj = fs.get('cnj') if pp or cnj: if pp: s += ' preposition: ' + pp if cnj: if pp: s += ',' s += ' conjunctive suffix: ' + cnj s += '\n' return s def vb_anal2string(anal): '''Convert a verb analysis to a string. anal is ("(*)v", root, citation, gramFS) ''' pos = 'verb' root = anal[1] citation = anal[2] fs = anal[3] POS = '?POS: ' if '?' in anal[0] else 'POS: ' s = POS + pos if root: if '{' in root: # Segmented form; not root s += ', segmentation: ' + root else: s += ', root: <' + root + '>' if citation: s += ', citation: ' + citation s += '\n' if fs: sb = fs['sb'] s += ' subject:' s += arg2string(sb) ob = fs.get('ob') if ob and ob.get('expl'): s += ' object:' s += arg2string(ob, True) s += ' grammar:' rl = fs.get('rl') tm = fs.get('tm') if tm == 'prf': s += ' perfective' elif tm == 'imf': s += ' imperfective' elif tm == 'j_i': s += ' jussive/imperative' elif tm == 'ger': s += ' gerundive' else: s += ' present' if fs.get('ax'): s += ', aux:alle' asp = fs['as'] if asp == 'it': s += ', iterative' elif asp == 'rc': s += ', reciprocal' vc = fs['vc'] if vc == 'ps': s += ', passive' elif vc == 'tr': s += ', transitive' elif vc == 'cs': s += ', causative' if fs.get('rel') or fs.get('neg'): if fs.get('rel'): s += ', relative' if rl and rl.get('acc'): s += ', accusative' if fs.get('def'): s += ', definite' if fs.get('neg'): s += ', negative' s += '\n' cj1 = fs.get('cj1') cj2 = fs.get('cj2') prep = fs.get('pp') if cj1 or cj2 or prep: any_affix = False if prep: any_affix = True s += ' preposition: ' + prep if cj1: if any_affix: s += ',' s += ' conjunctive prefix: ' + cj1 if cj2: if any_affix: s += ',' s += ' conjunctive suffix: ' + cj2 s += '\n' return s def arg2string(fs, obj=False): '''Convert an argument Feature Structure to a string.''' s = '' if fs.get('p1'): s += ' 1' elif fs.get('p2'): s += ' 2' else: s += ' 3' if fs.get('plr'): s += ', plur' else: s += ', sing' if not fs.get('plr') and (fs.get('p2') or not fs.get('p1')): if fs.get('fem'): s += ', fem' elif not fs.get('frm'): s += ', masc' if obj: if fs.get('p2'): if fs.get('frm'): s += ', formal' if fs.get('prp'): if fs.get('l'): s += ', prep: -l-' else: s += ', prep: -b-' s += '\n' return s def vb_anal_to_dict(root, fs): '''Convert a verb analysis Feature Structure to a dict.''' args = [] # List of features that are true bools = [] strings = {} gram = {} gram['root'] = root sbj = fs['sb'] obj = fs.get('ob', None) vc = fs['vc'] asp = fs['as'] tm = fs['tm'] cj1 = fs.get('cj1', None) cj2 = fs.get('cj2', None) prp = fs.get('pp', None) rl = fs.get('rl', {}) # Subject and object prep = False formal = False labels = ['person', 'number', 'gender'] if obj.get('expl'): if obj.get('p2'): formal = True labels.append('formality') prep = True labels.append('prepositional') args.append(labels) args1 = [] args1.append(agr_to_list(sbj, 'subject', formal)) if obj.get('expl'): args1.append(agr_to_list(obj, 'object', formal)) args.append(args1) # TAM if tm == 'imf': strings['tense/mood'] = 'imperfective' elif tm == 'prf': strings['tense/mood'] = 'perfective' elif tm == 'ger': strings['tense/mood'] = 'gerundive' else: strings['tense/mood'] = 'jussive/imperative' # DERIVATIONAL STUFF if vc == 'ps': strings['voice'] = 'passive' elif vc == 'tr': strings['voice'] = 'transitive' elif vc == 'cs': strings['voice'] = 'causative' if asp == 'it': strings['aspect'] = 'iterative' elif asp == 'rc': strings['aspect'] = 'reciprocal' # NEGATION if fs.get('neg'): bools.append('negative') # RELATIVIZATION if fs.get('rel'): bools.append('relative') # CASE if rl and rl.get('acc'): bools.append('accusative') # CONJUNCTIONS AND PREPOSITIONS if cj1: strings['prefix conjunction'] = cj1 if cj2: strings['suffix conjunction'] = cj2 if prp: strings['preposition'] = prp gram['args'] = args gram['strings'] = strings gram['bools'] = bools return gram def vb_dict_to_anal(root, dct, freeze=True): '''Convert a verb analysis dict to a Feature Structure.''' fs = FeatStruct() root = root or dct['root'] # Arguments sbj = list_to_arg(dct, 'sbj') if dct.get('obj'): obj = list_to_arg(dct, 'obj') else: obj = FeatStruct() obj['expl'] = False fs['sb'] = sbj fs['ob'] = obj # TAM: labels are the same as FS values fs['tm'] = dct.get('tam', 'prf') # DERIVATIONAL STUFF fs['as'] = dct.get('asp', 'smp') fs['vc'] = dct.get('voice_am', 'smp') # OTHER GRAMMAR fs['neg'] = dct.get('neg', False) fs['rel'] = dct.get('rel', False) fs['acc'] = dct.get('acc', False) if dct.get('aux'): fs['aux'] = 'al' else: fs['aux'] = None # PREPOSITIONS and CONJUNCTIONS fs['pp'] = dct.get('prep_am') if fs['pp']: fs['sub'] = True fs['cj1'] = dct.get('preconj_am') if fs['cj1']: fs['sub'] = True fs['cj2'] = dct.get('sufconj_am') return [root, FSSet(fs)] def agr_to_list(agr, cat, formal=False): '''Convert an agreement Feature Structure to a list. Category, then person, number, gender, formality (2nd prs), prepositional. ''' gram = [cat] if agr.get('p1'): gram.append('1') elif agr.get('p2'): gram.append('2') else: gram.append('3') if agr.get('plr'): gram.append('plural') else: gram.append('singular') if not agr.get('p1') and not agr.get('plr'): # Gender only for 2nd and 3rd person singular if agr.get('fem'): gram.append('feminine') else: gram.append('masculine') else: gram.append('') if formal: if cat == 'object' and agr.get('p2'): if agr.get('frm'): gram.append('formal') else: gram.append('informal') if agr.get('prp'): if agr.get('b'): gram.append('b-') else: gram.append('l-') elif cat == 'object': gram.append('no') return gram def list_to_arg(dct, prefix): '''Convert a dict to an argument Feature Structure.''' arg = FeatStruct() person = dct.get(prefix + '_pers') number = dct.get(prefix + '_num') gender = dct.get(prefix + '_gen') arg['expl'] = True # Person if person == '1': arg['p1'] = True arg['p2'] = False elif person == '2': arg['p2'] = True arg['p1'] = False else: # 3rd person the default arg['p1'] = False arg['p2'] = False # Number if number == 'plur': arg['plr'] = True else: # Singular the default arg['plr'] = False # Gender if person != '1': if gender == 'fem': arg['fem'] = True else: arg['fem'] = False # 2nd person: formality if person == '2': formality = dct.get(prefix + '_form') if formality == 'form': arg['frm'] = True else: # Informal the default arg['frm'] = False # Prepositional (object only) if prefix == 'obj': prep = dct.get(prefix + '_prep_am') if prep == 'l': arg['prp'] = 'l' elif prep == 'b': arg['prp'] = 'b' else: arg['prp'] = None return arg def root_postproc(root, geez=False): '''Postprocess a root, with or without converting to Geez.''' if geez: return root2geez(GEEZ_SERA['am'][1], root, lang='am') else: # # Irregular # if root == "al_e": # return '<al_e>' return '<' + root + '>' def n_postproc(analysis): '''Postprocess a noun, replacing the root, if deverbal with postprocessed form.''' gram1 = list(analysis[1])[0] if analysis[0]: if not gram1.get('v'): # This is not deverbal; convert the "root" (really the stem) to Geez analysis[0] = sera2geez(GEEZ_SERA['am'][1], analysis[0], lang='am') ## Create Language object for Amharic, including preprocessing, postprocessing, ## and segmentation units (phones). AM = language.Language("Amharic", 'am', postproc=lambda form: sera2geez(GEEZ_SERA['am'][1], form, lang='am'), preproc=lambda form: geez2sera(GEEZ_SERA['am'][0], form, lang='am', simp=True), postpostproc=lambda form: ta_convert(form), stat_root_feats=['vc', 'as'], stat_feats=[['poss', 'expl'], ['cnj'], ['cj1'], ['cj2'], ['pp'], ['rel']], seg_units=[["a", "e", "E", "i", "I", "o", "u", "H", "w", "y", "'", "`", "_", "|", "*"], {"b": ["b", "bW"], "c": ["c", "cW"], "C": ["C", "CW"], "d": ["d", "dW"], "f": ["f", "fW"], "g": ["g", "gW"], "h": ["h", "hW"], "j": ["j", "jW"], "k": ["k", "kW"], "l": ["l", "lW"], "m": ["m", "mW"], "n": ["n", "nW"], "p": ["p", "pW"], "P": ["P", "PW"], "N": ["N", "NW"], "q": ["q", "qW"], "r": ["r", "rW"], "s": ["s", "sW"], "S": ["S", "SW"], "t": ["t", "tW"], "T": ["T", "TW"], "v": ["v", "vW"], "x": ["x", "xW"], "z": ["z", "zW"], "Z": ["Z", "ZW"], "^": ["^s", "^S", "^h", "^hW", "^sW", "^SW"]}]) ## Create Morphology object and noun, verb, and copula POSMorphology objects for Amharic, ## including punctuation and ASCII characters that are part of the romanization. AM.set_morphology(language.Morphology((), pos_morphs=[('cop',), ('n',), ('v',)], # Exclude ^ and - (because it can be used in compounds) punctuation=r'[“‘”’–—:;/,<>?.!%$()[\]{}|#@&*\_+=\"፡።፣፤፥፦፧፨]', # Include digits? characters=r'[a-zA-Zሀ-ፚ\'`^]')) ### Assign various attributes to Morphology and POSMorphology objects # Functions that simplifies Amharic orthography AM.morphology.simplify = lambda word: simplify(word) AM.morphology.orthographize = lambda word: orthographize(word) # Function that performs trivial analysis on forms that don't require romanization AM.morphology.triv_anal = lambda form: no_convert(form) ## Functions converting between feature structures and simple dicts AM.morphology['v'].anal_to_dict = lambda root, anal: vb_anal_to_dict(root, anal) AM.morphology['v'].dict_to_anal = lambda root, anal: vb_dict_to_anal(root, anal) ## Default feature structures for POSMorphology objects ## Used in generation and production of citation form AM.morphology['v'].defaultFS = \ language.FeatStruct("[pos=v,tm=prf,as=smp,vc=smp,sb=[-p1,-p2,-plr,-fem],ob=[-expl,-p1,-p2,-plr,-fem,-b,-l,-prp,-frm],cj1=None,cj2=None,pp=None,ax=None,-neg,-rel,-sub,-def,-acc,-ye,rl=[-p,-acc]]") AM.morphology['v'].FS_implic = {'rel': ['def', 'sub'], 'cj1': ['sub'], 'pp': ['rel', 'sub'], ('pp', ('be', 'le', 'ke', 'wede', 'Inde', 'sIle', 'Iske', 'Iyye')): [['rl', ['p']]], 'def': ['rel', 'sub'], 'l': ['prp'], 'b': ['prp'], 'ob': [['expl']]} # defaultFS with voice and aspect unspecified AM.morphology['v'].citationFS = language.FeatStruct("[pos=v,tm=prf,sb=[-p1,-p2,-plr,-fem],ob=[-expl],cj1=None,cj2=None,pp=None,ax=None,-neg,-rel,-sub,-def,-ye,-acc,rl=[-p,-acc]]") AM.morphology['n'].defaultFS = \ language.FeatStruct("[pos=n,-acc,-def,-neg,-fem,-itu,as=smp,cnj=None,-dis,-gen,-plr,poss=[-expl,-p1,-p2,-plr,-fem,-frm],pp=None,v=None,vc=smp,rl=[-p,-gen,-acc]]") AM.morphology['n'].FS_implic = {'poss': [['expl'], 'def'], ('pp', ('be', 'le', 'ke', 'wede', 'Inde', 'sIle', 'Iske')): [['rl', ['p']]], ('gen', True): [['rl', ['gen']]], ('acc', True): [['rl', ['acc']]]} # defaultFS with voice and aspect unspecified AM.morphology['n'].citationFS = language.FeatStruct("[-acc,-def,-neg,cnj=None,-dis,-gen,-plr,poss=[-expl],pp=None,v=inf]") AM.morphology['cop'].defaultFS = language.FeatStruct("[cj2=None,-neg,ob=[-expl],-rel,sb=[-fem,-p1,-p2,-plr,-frm],-sub,tm=prs]") ## Functions that return the citation forms for words AM.morphology['v'].citation = lambda root, fss, simplified, guess, vc_as: vb_get_citation(root, fss, simplified, guess, vc_as) AM.morphology['n'].citation = lambda root, fss, simplified, guess, vc_as: n_get_citation(root, fss, simplified, guess, vc_as) ## Functions that convert analyses to strings AM.morphology['v'].anal2string = lambda fss: vb_anal2string(fss) AM.morphology['n'].anal2string = lambda fss: n_anal2string(fss) AM.morphology['cop'].anal2string = lambda fss: cop_anal2string(fss) ## Postprocessing function for nouns (treats roots differently) # AM.morphology['v'].postproc = lambda analysis: vb_postproc(analysis) AM.morphology['n'].postproc = lambda analysis: n_postproc(analysis) # AM.morphology['cop'].postproc = lambda analysis: cop_postproc(analysis) def load_anal(pos='v', lex=True, guess=False): if lex: AM.morphology[pos].load_fst(True, verbose=True) if guess: AM.morphology[pos].load_fst(True, guess=True, verbose=True) def load_gen(pos='v', lex=True, guess=False): if lex: AM.morphology[pos].load_fst(True, generate=True, invert=True, verbose=True) if guess: AM.morphology[pos].load_fst(True, generate=True, invert=True, guess=True, verbose=True)
from pandac.PandaModules import * CollectionTime = 30 BarrelRoomIntroTimeout = 15.0 RewardUiTime = 5.0 EndWithAllBarrelsCollected = False ShowRewardUI = False AllBarrelsCollectedTime = 5.0 ToonUp = (2, 4) BarrelProps = [{'pos': (-10, -66, 0), 'heading': 9}, {'pos': (-7.8, -54.5, 0), 'heading': 12}, {'pos': (-10.5, -44, 0), 'heading': 166}, {'pos': (-8.9, -33.5, 0), 'heading': 142}, {'pos': (-9.6, -19.8, 0), 'heading': 94}, {'pos': (7.8, -63.9, 0), 'heading': 169}, {'pos': (10, -44.5, 0), 'heading': 120}, {'pos': (7.4, -36.6, 0), 'heading': 127}, {'pos': (10.6, -27.5, 0), 'heading': 141}, {'pos': (10, -14.4, 0), 'heading': 2}] StomperProps = [{'path': '**/stomper_GRP_01/stomper_cylinder_01', 'motion': 'up'}, {'path': '**/stomper_GRP_02/stomper_cylinder_034', 'motion': 'down'}, {'path': '**/stomper_GRP_03/stomper_cylinder_034', 'motion': 'up'}, {'path': '**/stomper_GRP_04/stomper_cylinder_034', 'motion': 'up'}, {'path': '**/stomper_GRP_05/stomper_cylinder_034', 'motion': 'down'}, {'path': '**/stomper_GRP_06/stomper_cylinder_034', 'motion': 'up'}, {'path': '**/stomper_GRP_07/stomper_cylinder_034', 'motion': 'down'}, {'path': '**/stomper_GRP_08/stomper_cylinder_034', 'motion': 'up'}, {'path': '**/stomper_GRP_09/stomper_cylinder_034', 'motion': 'up'}, {'path': '**/stomper_GRP_10/stomper_cylinder_034', 'motion': 'down'}, {'path': '**/stomper_GRP_11/stomper_cylinder_034', 'motion': 'up'}, {'path': '**/stomper_GRP_12/stomper_cylinder_034', 'motion': 'up'}] StomperHaltTime = 7.3 StomperSound = 'phase_9/audio/sfx/CHQ_FACT_stomper_raise.mp3' MaxToons = 4 BarrelRoomModel = 'phase_5/models/cogdominium/tt_m_ara_cbr_barrelRoom' BarrelRoomModelPos = (0, 0, 0) BarrelRoomElevatorOutPath = '**/elevatorOut_locator' BarrelRoomPlayerSpawnPoints = [(-4, 0, 0, 0, 0, 0), (-2, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0), (2, 0, 0, 0, 0, 0)] BarrelRoomCameraFar = 525.0 BarrelRoomFogColor = Vec4(0.65, 0.21, 0, 1.0) BarrelRoomFogLinearRange = (0.0, 800.0) BarrelModel = 'phase_5/models/cogdominium/tt_m_ara_cbr_laughBarrel' BarrelModelScale = 1.0 BarrelCollParams = (0, 0, 2, 2.0) BarrelBumpSound = 'phase_4/audio/sfx/Golf_Hit_Barrier_2.mp3' BarrelGrabSound = 'phase_4/audio/sfx/SZ_DD_treasure.mp3' StateHidden, StateAvailable, StateUsed, StateCrushed = range(4) def numBarrels(): return len(BarrelProps)
# -*- coding: utf-8 -*- import requests from enviopack import Enviopack from enviopack.constants import BASE_API_URL from typing import List from enviopack import Auth class Quote(Enviopack): """ """ _name = "Quote orders" state:str "ID Provincia: Deberá informarse el valor ID devuelto por el webservice de provincias. Los IDs de provincias están bajo el estándar ISO_3166-2:AR sin el prefijo AR-." city:int "ID Localidad: Deberá informarse el valor ID devuelto por el webservice de localidades." zip_code:int "Codigo postal: Entero de 4 dígitos" weight:float "Peso: Hasta 2 dígitos decimales" packages:str """Este parámetro espera un formato especial el cual debe indicar las dimensiones de los N paquetes que pueda tener el envio a cotizar. Ej: 20x2x10,20x2x10 indica que se envian 2 paquetes y cada uno tiene 20 cm de alto x 2 cm de ancho x 10 cm de largo. En caso de no recibir valor alguno, nuestro sistema asume por default el envio de un unico paquete de 1 x 1 x 1.""" carrier:int "correo: Deberá informarse el valor ID devuelto por el webservice de correos. Por ejemplo para FastMail su ID es fastmail." dispatch:str """despacho: Indica si el operador logistico debe retirar el paquete por el deposito del vendedor o si el vendedor lo va a acercar a una sucursal. Los valores posibles son: - D: retiro por domicilio - S: despacho desde sucursal""" mode:str """modalidad Los valores posibles son: - D: para envíos a domicilio - S: para envíos a sucursal """ service:str """servicio Los valores posibles son: - N: para el servicio estándar - P: para el servicio prioritario - X: para el servicio express - R: para el servicio de devoluciones""" dispatch_address:int """direccion_envio ID que identifica la dirección, por donde el correo pasara a retirar la mercadería a enviar. Podes obtenerlo ingresando en Configuración / Mis Direcciones Si bien este parámetro no es obligatorio es conveniente enviarlo, pues de esta manera la cotización sera más precisa. En caso de no recibir valor alguno, nuestro sistema asume que el envío se realizará desde la dirección de envio default. Si no existiera una dirección de envio default no sera posible devolver cotizaciones y el WS no informara resultados.""" column_order:str """orden_columna: Los valores posibles son: - valor: para ordenar por precio (Default) - horas_entrega: para ordenar por velocidad de envío - cumplimiento: para ordenar por porcentaje de cumplimiento en envios de similares caracteristicas - anomalos: para ordenar por porcentaje de anómalos en envios de similares caracteristicas""" order_way:str """orden_sentido Los valores posibles son: - asc: para orden ascendente (Default) - desc: para orden descendente""" def __init__(self, state:str, zip_code:int, weight:float, auth:Auth, base_url=BASE_API_URL, base_path='/cotizar', **kwargs): """ city:int=False packages:str=False carrier:int=False dispatch:str=False mode:str=False service:str=False dispatch_address:int=False column_order:str=False order_way:str=False """ super(Quote,self).__init__(auth) self.state = state self.zip_code = zip_code self.weight = weight for arg in kwargs: value = kwargs.get(arg, False) if value: setattr(self, arg, value) self.base_request_url = base_url self.base_request_path = base_path def __repr__(self): return '(Quote: weight {weight}, state {state}, zip_code {zip_code})'.format(weight=self.weight,state=self.state, zip_code=self.zip_code) def cost(self) -> dict: """ GET /cotizar/costo Obtener el costo que abona el vendedor por el envío Permite obtener un listado de cotizaciones brindando en cada una de ellas el valor que vendedor va a pagar por el envío: """ url = "{base_url}{base_path}{endpoint}".format(base_url=self.base_request_url, base_path=self.base_request_path, endpoint="/costo") access_token = self.auth.access_token if not access_token: raise Exception('No access token defined') mandatory_params = { 'access_token':access_token, 'provincia':self.state, 'codigo_postal': self.zip_code, 'peso':self.weight } params = self._optional_params(mandatory_params, optional_fields={ "packages":"packages", "carrier":"correo", "dispatch":"despacho", "mode":"modalidad", "service":"servicio", "dispatch_address":"direccion_envio", "column_order":"orden_columna", "order_way":"orden_sentido", }) response = requests.get(url, params) if response.status_code == 200: return response.json() else: raise Exception('El pedido de costo fallo, revisar los parametros utilizados') def price_to_address(self): """ GET /cotizar/precio/a-domicilio Permite obtener un listado de cotizaciones brindando en cada una de ellas el valor que comprador va a pagar por el envío a domicilio. Los valores devueltos por este webservice pueden ser modificados desde la sección correos y tarifas para cada servicio en particular. """ raise NotImplementedError def price_to_post_office(self): """ GET /cotizar/precio/a-sucursal Permite obtener un listado de cotizaciones brindando en cada una de ellas el valor que el comprador va a pagar por un envío a sucursal, retornando ademas toda la información de cada sucursal elegible. Este webservice esta diseñado para que tu comprador en el checkout de tu aplicación pueda cotizar y elegir en tiempo real en que sucursal quiere recibir su pedido. Los valores devueltos por este webservice pueden ser modificados desde la sección correos y tarifas para cada correo en particular. """ raise NotImplementedError
import asyncio import datetime import io import os import pickle import pprint import subprocess import sys import textwrap import time from contextlib import redirect_stdout import nextcord as discord import psutil import traceback2 from nextcord.ext import commands from .milkcoffee import MilkCoffee from .utils.messenger import error_embed, success_embed, warning_embed, normal_embed # class class Developer(commands.Cog, command_attrs=dict(hidden=True)): """BOTのシステムを管理します""" def __init__(self, bot): self.bot = bot # type: MilkCoffee self._last_result = None try: import psutil except: self.psutil = False else: self.psutil = True def cleanup_code(self, content): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n') async def cog_before_invoke(self, ctx): if ctx.author.id not in [513136168112750593, 519760564755365888, 561359054165901347, 585351496523186187, 822814328238506014]: await ctx.send(ctx.author.mention) await error_embed(ctx, "あなたにはこのコマンドを利用する権限がありません(笑)") raise Exception("Developer-Admin-Error") async def cog_command_error(self, ctx, error): if isinstance(error, commands.errors.MissingRequiredArgument): await ctx.send(f"引数が足りません。\nエラー詳細:\n{error}") else: await ctx.send(f"エラーが発生しました:\n{error}") @commands.command(aliases=["ac"]) async def accept(self, ctx, guild_id): try: guild_id = int(guild_id) except: return await error_embed(ctx, "無効なIDです") if guild_id not in self.bot.cache_guilds: guild = self.bot.get_guild(guild_id) if guild is None: await error_embed(ctx, "そのサーバーに参加していません") else: self.bot.cache_guilds.add(guild_id) await success_embed(ctx, f"{guild.name}での利用を承認しました") with open('guilds.pickle', 'wb') as f: pickle.dump(self.bot.cache_guilds, f) else: await warning_embed(ctx, "そのサーバーはすでに承認されています") @commands.command(aliases=["rf"]) async def refuse(self, ctx, guild_id): try: guild_id = int(guild_id) except: return await error_embed(ctx, "無効なIDです") if guild_id in self.bot.cache_guilds: guild = self.bot.get_guild(guild_id) if guild is None: self.bot.cache_guilds.discard(guild_id) await error_embed(ctx, "そのサーバーでの使用を拒否しました") else: self.bot.cache_guilds.discard(guild_id) await success_embed(ctx, f"{guild.name}での利用を拒否しました") with open('guilds.pickle', 'wb') as f: pickle.dump(self.bot.cache_guilds, f) else: await warning_embed(ctx, "そのサーバーはまだ承認されていません") @commands.command(aliases=["rl"]) async def reload(self, ctx, text): if text == "music": players = self.bot.get_cog("Music").players self.bot.reload_extension("Cogs.music") self.bot.get_cog("Music").players = players return await ctx.send("musicを再読み込みしました") try: self.bot.reload_extension(text) except: await ctx.send(f"{text}の再読み込みに失敗しました\n{traceback2.format_exc()}.") else: await ctx.send(f"{text}の再読み込みに成功しました.") @commands.command() async def restart(self, ctx): await ctx.send(":closed_lock_with_key:BOTを再起動します.") python = sys.executable os.execl(python, python, *sys.argv) @commands.command() async def quit(self, ctx): await ctx.send(":closed_lock_with_key:BOTを停止します.") sys.exit() @commands.command() async def exe(self, ctx, *, body: str): env = { 'bot': self.bot, 'ctx': ctx, 'channel': ctx.channel, 'author': ctx.author, 'guild': ctx.guild, 'message': ctx.message, '_': self._last_result } env.update(globals()) body = self.cleanup_code(body) stdout = io.StringIO() to_compile = f'async def func():\n{textwrap.indent(body, " ")}' try: exec(to_compile, env) except Exception as e: return await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```') func = env['func'] try: with redirect_stdout(stdout): ret = await func() except Exception as e: value = stdout.getvalue() await ctx.send(f'```py\n{value}{traceback2.format_exc()}\n```') else: value = stdout.getvalue() try: await ctx.message.add_reaction('\u2705') except: pass if ret is None: if value: await ctx.send(f'```py\n{value}\n```') else: self._last_result = ret await ctx.send(f'```py\n{value}{ret}\n```') @commands.command(aliases=["pr"]) async def process(self, ctx): td = datetime.timedelta(seconds=int(time.time() - self.bot.uptime)) m, s = divmod(td.seconds, 60) h, m = divmod(m, 60) d = td.days uptime = f"{d}d {h}h {m}m {s}s" cpu_per = psutil.cpu_percent() mem_total = psutil.virtual_memory().total / 10 ** 9 mem_used = psutil.virtual_memory().used / 10 ** 9 mem_per = psutil.virtual_memory().percent swap_total = psutil.swap_memory().total / 10 ** 9 swap_used = psutil.swap_memory().used / 10 ** 9 swap_per = psutil.swap_memory().percent guilds = len(self.bot.guilds) users = len(self.bot.users) vcs = len(self.bot.voice_clients) text_channels = 0 voice_channels = 0 for channel in self.bot.get_all_channels(): if isinstance(channel, discord.TextChannel): text_channels += 1 elif isinstance(channel, discord.VoiceChannel): voice_channels += 1 latency = self.bot.latency try: temp = [str(obj.current) + "℃" for key in psutil.sensors_temperatures() for obj in psutil.sensors_temperatures()[key]] except: temp = ["N/A"] process = psutil.Process(os.getpid()) using_mem = f"{(process.memory_info().rss // 1000000):.1f} MB" embed = discord.Embed(title="Process") embed.add_field(name="Server", value=f"```yaml\nCPU: [{cpu_per}%]\nMemory: [{mem_per}%] {mem_used:.2f}GiB / {mem_total:.2f}GiB\nSwap: [{swap_per}%] {swap_used:.2f}GiB / {swap_total:.2f}GiB\nTemperature: {','.join(temp)}\nUsingMem: {using_mem}```", inline=False) embed.add_field(name="Discord", value=f"```yaml\nServers: {guilds}\nTextChannels: {text_channels}\nVoiceChannels: {voice_channels}\nUsers: {users}\nConnectedVC: {vcs}```", inline=False) embed.add_field(name="Run", value=f"```yaml\nCommandRuns: {self.bot.commands_run}\nUptime: {uptime}\nLatency: {latency:.2f}[s]\n```") await ctx.send(embed=embed) @commands.command() async def db(self, ctx, *, text): res = await self.bot.db.con.fetch(text) res = [dict(i) for i in res] await ctx.send("```json\n" + pprint.pformat(res)[:1980] + "```") @commands.command(aliases=["pg"]) async def ping(self, ctx): before = time.monotonic() message = await ctx.send("Pong") ping = (time.monotonic() - before) * 1000 await message.delete() await ctx.send(f"反応速度: `{int(ping)}`[ms]") @commands.command() async def cmd(self, ctx, *, text): msg = "" try: output = await self.run_subprocess(text, loop=self.bot.loop) await ctx.send("\n".join(output)) except: await ctx.send(file=discord.File(fp=io.StringIO(msg), filename="output.txt")) async def run_subprocess(self, cmd, loop=None): loop = loop or asyncio.get_event_loop() try: process = await asyncio.create_subprocess_shell(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except NotImplementedError: with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) as process: try: result = await loop.run_in_executor(None, process.communicate) except Exception: # muh pycodestyle def kill(): process.kill() process.wait() await loop.run_in_executor(None, kill) raise else: result = await process.communicate() return [res.decode('utf-8') for res in result] def setup(bot): bot.add_cog(Developer(bot))
<reponame>lasse-herzog/pi-game-console import os import pygame from pygame.locals import * from pong.utils import load_asset import pong.level_easy as level_easy import pong.level_hard as level_hard import pong.level_med as level_med import pong.level_unf as level_unf pygame.init() # Game Initialization # Center the Game Application os.environ['SDL_VIDEO_CENTERED'] = '1' # Game Resolution screen_width = 1024 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) # Text Renderer def text_format(message, textFont, textSize, textColor): newFont = pygame.font.Font(textFont, textSize) newText = newFont.render(message, 0, textColor) return newText # Colors white = (255, 255, 255) black = (0, 0, 0) gray = (50, 50, 50) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) yellow = (255, 255, 0) # Game Fonts font = load_asset("Pixeled.ttf") # Sounds select_sound = pygame.mixer.Sound(load_asset("choose.wav")) confirm_sound = pygame.mixer.Sound(load_asset("chooseThis.wav")) # Game Framerate clock = pygame.time.Clock() FPS = 30 # Joystick initialization if pygame.joystick.get_count() > 0: joystick = pygame.joystick.Joystick(0) joystick.init() loop = True # Main Menu def main_menu(): menu = True selected = "start" last_select = 0 while menu: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: pygame.mixer.Sound.play(select_sound) selected = "start" print(selected) elif event.key == pygame.K_DOWN: pygame.mixer.Sound.play(select_sound) selected = "quit" print(selected) elif event.key == pygame.K_RETURN: pygame.mixer.Sound.play(confirm_sound) if selected == "start": level_select() elif selected == "quit": menu = False elif event.type == JOYBUTTONDOWN: pygame.mixer.Sound.play(select_sound) if selected == "start": level_select() elif selected == "quit": menu = False elif event.type == JOYAXISMOTION: # Joystick Controls axis = [0, 0] for j in range(2): axis[j] = joystick.get_axis(j) if round(axis[0]) == 1 and round( axis[1]) == 0 and last_select + 1000 < pygame.time.get_ticks(): # Joystick Up last_select = pygame.time.get_ticks() selected = "start" if round(axis[0]) == -1 and round( axis[1]) == 0 and last_select + 1000 < pygame.time.get_ticks(): # Joystick Down last_select = pygame.time.get_ticks() selected = "quit" # Main Menu UI screen.fill(black) title = text_format("PYCO PONG", font, 45, white) if selected == "start": text_start = text_format("START", font, 35, white) else: text_start = text_format("START", font, 35, gray) if selected == "quit": text_quit = text_format("QUIT", font, 35, white) else: text_quit = text_format("QUIT", font, 35, gray) title_rect = title.get_rect() start_rect = text_start.get_rect() quit_rect = text_quit.get_rect() # Main Menu Text screen.blit(title, (screen_width / 2 - (title_rect[2] / 2), 80)) screen.blit(text_start, (screen_width / 2 - (start_rect[2] / 2), 300)) screen.blit(text_quit, (screen_width / 2 - (quit_rect[2] / 2), 360)) pygame.display.update() clock.tick(FPS) pygame.display.set_caption("PiG-C Pong Main Menu") def level_select(): run = True selection = ["easy", "medium", "hard", "unfair"] s: int = 0 selected = selection[s] last_select = 0 while run: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: pygame.mixer.Sound.play(select_sound) s -= 1 if (s < 0): s = 3 selected = selection[s] print(selected) elif event.key == pygame.K_DOWN: pygame.mixer.Sound.play(select_sound) s += 1 if (s > 3): s = 0 selected = selection[s] print(selected) if event.key == pygame.K_RETURN: pygame.mixer.Sound.play(confirm_sound) if selected == "easy": print("Start") run = False level_easy.easyLoop() if selected == "medium": print("Coming soon") run = False level_med.medLoop() if selected == "hard": level_hard.hardLoop() run = False if selected == "unfair": run = False level_unf.unfLoop() elif event.type == JOYBUTTONDOWN: pygame.mixer.Sound.play(confirm_sound) if selected == "easy": print("Start") run = False level_easy.easyLoop() if selected == "medium": run = False level_med.medLoop() if selected == "hard": level_hard.hardLoop() run = False if selected == "unfair": run = False level_unf.unfLoop() elif event.type == JOYAXISMOTION: # Joystick Controls axis = [0, 0] for j in range(2): axis[j] = joystick.get_axis(j) if round(axis[0]) == 1 and round( axis[1]) == 0 and last_select + 1000 < pygame.time.get_ticks(): # Joystick Up last_select = pygame.time.get_ticks() s -= 1 if (s < 0): s = 4 selected = selection[s] if round(axis[0]) == -1 and round( axis[1]) == 0 and last_select + 1000 < pygame.time.get_ticks(): # Joystick Down last_select = pygame.time.get_ticks() s += 1 if (s > 4): s = 0 selected = selection[s] # Main Menu UI screen.fill(black) title = text_format("LEVEL SELECT", font, 45, white) if selected == "easy": text_easy = text_format("easy", font, 35, white) else: text_easy = text_format("easy", font, 35, gray) if selected == "medium": text_med = text_format("medium", font, 35, white) else: text_med = text_format("medium", font, 35, gray) if selected == "hard": text_hard = text_format("hard", font, 35, white) else: text_hard = text_format("hard", font, 35, gray) if selected == "unfair": text_unf = text_format("unfair", font, 35, white) else: text_unf = text_format("unfair", font, 35, gray) title_rect = title.get_rect() easy_rect = text_easy.get_rect() med_rect = text_med.get_rect() hard_rect = text_hard.get_rect() unf_rect = text_unf.get_rect() # Main Menu Text screen.blit(title, (screen_width / 2 - (title_rect[2] / 2), 50)) screen.blit(text_easy, (screen_width / 2 - (easy_rect[2] / 2), 200)) screen.blit(text_med, (screen_width / 2 - (med_rect[2] / 2), 260)) screen.blit(text_hard, (screen_width / 2 - (hard_rect[2] / 2), 320)) screen.blit(text_unf, (screen_width / 2 - (unf_rect[2] / 2), 380)) pygame.display.update() clock.tick(FPS) pygame.display.set_caption("PiG-C Pong Main Menu") if __name__ == '__main__': main_menu()
# Copyright (C) 2013-present The DataCentric Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import numpy as np from enum import IntEnum from typing import Iterable, Dict, Any, List, TypeVar, Set, TYPE_CHECKING from bson import ObjectId from pymongo.collection import Collection from pymongo.command_cursor import CommandCursor from datacentric.primitive.string_util import StringUtil from datacentric.date_time.local_time import LocalTime from datacentric.date_time.local_minute import LocalMinute from datacentric.date_time.local_date import LocalDate from datacentric.date_time.local_date_time import LocalDateTime from datacentric.storage.record import Record from datacentric.serialization.serializer import deserialize if TYPE_CHECKING: from datacentric.storage.mongo.temporal_mongo_data_source import TemporalMongoDataSource TRecord = TypeVar('TRecord', bound=Record) class TemporalMongoQuery: """Implements query methods for temporal MongoDB data source. This implementation adds additional constraints and ordering to retrieve the correct version of the record across multiple datasets. """ def __init__(self, record_type: type, data_source: TemporalMongoDataSource, collection: Collection, load_from: ObjectId): self._data_source: TemporalMongoDataSource = data_source self._type = record_type self._collection = collection self._load_from = load_from self._pipeline: List[Dict[str, Any]] = [{'$match': {'_t': self._type.__name__}}] def __has_sort(self) -> bool: stage_names = [stage_name for stage in self._pipeline for stage_name in stage.keys()] return '$sort' in stage_names def where(self, predicate: Dict[str, Any]) -> TemporalMongoQuery: """Filters a sequence of values based on passed dictionary parameter. Corresponds to appending $match stage to the pipeline. """ if not self.__has_sort(): renamed_keys = dict() for k, v in predicate.items(): new_key = StringUtil.to_pascal_case(k) renamed_keys[new_key] = v TemporalMongoQuery.__fix_predicate_query(renamed_keys) query = TemporalMongoQuery(self._type, self._data_source, self._collection, self._load_from) query._pipeline = self._pipeline.copy() query._pipeline.append({'$match': renamed_keys}) return query else: raise Exception(f'All where(...) clauses of the query must precede' f'sort_by(...) or sort_by_descending(...) clauses of the same query.') @staticmethod def __fix_predicate_query(dict_: Dict[str, Any]): """Updated and convert user defined query to bson friendly format.""" for k, value in dict_.items(): updated_value: Any if type(value) is dict: updated_value = TemporalMongoQuery.__process_dict(value) elif type(value) is list: updated_value = TemporalMongoQuery.__process_list(value) else: updated_value = TemporalMongoQuery.__process_element(value) dict_[k] = updated_value @staticmethod def __process_dict(dict_: Dict[str, Any]) -> Dict[str, Any]: """Process dictionary values.""" for k, value in dict_.items(): updated_value: Any if type(value) is dict: updated_value = TemporalMongoQuery.__process_dict(value) elif type(value) is list: updated_value = TemporalMongoQuery.__process_list(value) else: updated_value = TemporalMongoQuery.__process_element(value) dict_[k] = updated_value return dict_ @staticmethod def __process_list(list_: List[Any]) -> List[Any]: """Process list elements.""" updated_list = [] for value in list_: updated_value: Any if type(value) is dict: updated_value = TemporalMongoQuery.__process_dict(value) elif type(value) is list: updated_value = TemporalMongoQuery.__process_list(value) else: updated_value = TemporalMongoQuery.__process_element(value) updated_list.append(updated_value) return updated_list @staticmethod def __process_element(value) -> Any: """Serializes elements to bson valid objects.""" value_type = type(value) if value_type in [LocalMinute, LocalDate, LocalDateTime, LocalTime]: return value elif value_type == np.ndarray: return value.tolist() elif issubclass(value_type, IntEnum): return value.name else: return value def sort_by(self, attr: str) -> TemporalMongoQuery: """Sorts the elements of a sequence in ascending order according to provided attribute name.""" # Adding sort argument since sort stage is already present. if self.__has_sort(): query = TemporalMongoQuery(self._type, self._data_source, self._collection, self._load_from) query._pipeline = self._pipeline.copy() sorts = next(stage['$sort'] for stage in query._pipeline if '$sort' in stage) sorts[StringUtil.to_pascal_case(attr)] = 1 return query # append sort stage else: query = TemporalMongoQuery(self._type, self._data_source, self._collection, self._load_from) query._pipeline = self._pipeline.copy() query._pipeline.append({'$sort': {StringUtil.to_pascal_case(attr): 1}}) return query def sort_by_descending(self, attr) -> TemporalMongoQuery: """Sorts the elements of a sequence in descending order according to provided attribute name.""" # Adding sort argument since sort stage is already present. if self.__has_sort(): query = TemporalMongoQuery(self._type, self._data_source, self._collection, self._load_from) query._pipeline = self._pipeline.copy() sorts = next(stage['$sort'] for stage in query._pipeline if '$sort' in stage) sorts[StringUtil.to_pascal_case(attr)] = -1 return query # append sort stage else: query = TemporalMongoQuery(self._type, self._data_source, self._collection, self._load_from) query._pipeline = self._pipeline.copy() query._pipeline.append({'$sort': {StringUtil.to_pascal_case(attr): -1}}) return query def as_iterable(self) -> Iterable[TRecord]: """Applies aggregation on collection and returns its result as Iterable.""" if not self.__has_sort(): batch_queryable = self._data_source.apply_final_constraints(self._pipeline, self._load_from) else: batch_queryable = self._pipeline projected_batch_queryable = batch_queryable projected_batch_queryable.append({'$project': {'Id': '$_id', 'Key': '$_key', '_id': 0}}) with self._collection.aggregate(projected_batch_queryable) as cursor: # type: CommandCursor batch_size = 1000 continue_query = True while continue_query: batch_index = 0 batch_keys_hash_set: Set[str] = set() batch_ids_hash_set: Set[ObjectId] = set() batch_ids_list: List[ObjectId] = [] while True: continue_query = cursor.alive if continue_query: record_info = cursor.next() batch_key = record_info['Key'] batch_id = record_info['Id'] if batch_key not in batch_keys_hash_set: batch_keys_hash_set.add(batch_key) batch_index += 1 batch_ids_hash_set.add(batch_id) batch_ids_list.append(batch_id) if batch_index == batch_size: break else: break if not continue_query and batch_index == 0: break id_queryable: List[Dict[str, Any]] = [{'$match': {'_key': {'$in': list(batch_keys_hash_set)}}}] id_queryable = self._data_source.apply_final_constraints(id_queryable, self._load_from) id_queryable.append({'$sort': {'_key': 1, '_dataset': -1, '_id': -1}}) projected_id_queryable = id_queryable projected_id_queryable.append( {'$project': {'Id': '$_id', 'DataSet': '$_dataset', 'Key': '$_key', '_id': 0}}) imports_cutoff = self._data_source.get_imports_cutoff_time(self._load_from) record_ids = [] current_key = None for obj in self._collection.aggregate(projected_id_queryable): obj_key = obj['Key'] if current_key == obj_key: pass else: record_id = obj['Id'] record_data_set = obj['DataSet'] if imports_cutoff is None or record_data_set == self._load_from or record_id < imports_cutoff: current_key = obj_key if record_id in batch_ids_hash_set: record_ids.append(record_id) if len(record_ids) == 0: break record_queryable = [{'$match': {'_id': {'$in': record_ids}}}] record_dict = dict() for record in self._collection.aggregate(record_queryable): rec: TRecord = deserialize(record) record_dict[rec.id_] = rec for batch_id in batch_ids_list: if batch_id in record_dict: yield record_dict[batch_id]
# -*- coding: utf-8 -*- # # Copyright (C) 2004-2013 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. from trac.versioncontrol import diff import unittest def get_opcodes(*args, **kwargs): for hunk in diff.get_filtered_hunks(*args, **kwargs): for opcode in hunk: yield opcode class DiffTestCase(unittest.TestCase): def testget_change_extent(self): self.assertEqual((3, 0), diff.get_change_extent('xxx', 'xxx')) self.assertEqual((0, 0), diff.get_change_extent('', 'xxx')) self.assertEqual((0, 0), diff.get_change_extent('xxx', '')) self.assertEqual((0, 0), diff.get_change_extent('xxx', 'yyy')) self.assertEqual((1, -1), diff.get_change_extent('xxx', 'xyx')) self.assertEqual((1, -1), diff.get_change_extent('xxx', 'xyyyx')) self.assertEqual((1, 0), diff.get_change_extent('xy', 'xzz')) self.assertEqual((1, -1), diff.get_change_extent('xyx', 'xzzx')) self.assertEqual((1, -1), diff.get_change_extent('xzzx', 'xyx')) def test_insert_blank_line(self): opcodes = get_opcodes(['A', 'B'], ['A', 'B', ''], ignore_blank_lines=0) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertEqual(('insert', 2, 2, 2, 3), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A', 'B'], ['A', 'B', ''], ignore_blank_lines=1) self.assertEqual(('equal', 0, 2, 0, 3), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A'], ['A', 'B', ''], ignore_blank_lines=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('insert', 1, 1, 1, 3), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A'], ['A', 'B', ''], ignore_blank_lines=1) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('insert', 1, 1, 1, 3), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) def test_delete_blank_line(self): opcodes = get_opcodes(['A', 'B', ''], ['A', 'B'], ignore_blank_lines=0) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertEqual(('delete', 2, 3, 2, 2), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A', 'B', ''], ['A', 'B'], ignore_blank_lines=1) self.assertEqual(('equal', 0, 3, 0, 2), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A', 'B', ''], ['A'], ignore_blank_lines=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('delete', 1, 3, 1, 1), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A', 'B', ''], ['A'], ignore_blank_lines=1) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('delete', 1, 3, 1, 1), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) def test_space_changes(self): opcodes = get_opcodes(['A', 'B b'], ['A', 'B b'], ignore_space_changes=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('replace', 1, 2, 1, 2), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A', 'B b'], ['A', 'B b'], ignore_space_changes=1) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) def test_space_changes_2(self): left = """\ try: try: func() commit() except: rollback() finally: cleanup() """ left = left.splitlines() right = """\ try: func() commit() except: rollback() finally: cleanup() """ right = right.splitlines() opcodes = get_opcodes(left, right, ignore_space_changes=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('replace', 1, 6, 1, 5), opcodes.next()) self.assertEqual(('equal', 6, 8, 5, 7), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(left, right, ignore_space_changes=1) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('delete', 1, 2, 1, 1), opcodes.next()) self.assertEqual(('equal', 2, 4, 1, 3), opcodes.next()) self.assertEqual(('replace', 4, 5, 3, 4), opcodes.next()) self.assertEqual(('equal', 5, 8, 4, 7), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) def test_case_changes(self): opcodes = get_opcodes(['A', 'B b'], ['A', 'B B'], ignore_case=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('replace', 1, 2, 1, 2), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A', 'B b'], ['A', 'B B'], ignore_case=1) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) def test_space_and_case_changes(self): opcodes = get_opcodes(['A', 'B b'], ['A', 'B B'], ignore_case=0, ignore_space_changes=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('replace', 1, 2, 1, 2), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) opcodes = get_opcodes(['A', 'B b'], ['A', 'B B'], ignore_case=1, ignore_space_changes=1) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertRaises(StopIteration, opcodes.next) def test_grouped_opcodes_context1(self): groups = diff.get_filtered_hunks( ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ['A', 'B', 'C', 'd', 'e', 'f', 'G', 'H'], context=1) group = groups.next() self.assertRaises(StopIteration, groups.next) self.assertEqual(('equal', 2, 3, 2, 3), group[0]) self.assertEqual(('replace', 3, 6, 3, 6), group[1]) self.assertEqual(('equal', 6, 7, 6, 7), group[2]) def test_grouped_opcodes_context1_ignorecase(self): old = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] new = ['X', 'B', 'C', 'd', 'e', 'f', 'G', 'Y'] groups = diff.get_filtered_hunks(old, new, context=1, ignore_case=1) group = groups.next() self.assertEqual([('replace', 0, 1, 0, 1), ('equal', 1, 2, 1, 2)], group) group = groups.next() self.assertRaises(StopIteration, groups.next) self.assertEqual([('equal', 6, 7, 6, 7), ('replace', 7, 8, 7, 8)], group) def test_grouped_opcodes_full_context(self): old = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] new = ['X', 'B', 'C', 'd', 'e', 'f', 'G', 'Y'] groups = diff.get_filtered_hunks(old, new, context=None) group = groups.next() self.assertRaises(StopIteration, groups.next) self.assertEqual([ ('replace', 0, 1, 0, 1), ('equal', 1, 3, 1, 3), ('replace', 3, 6, 3, 6), ('equal', 6, 7, 6, 7), ('replace', 7, 8, 7, 8), ], group) groups = diff.get_filtered_hunks(old, new, context=None, ignore_case=1) group = groups.next() self.assertRaises(StopIteration, groups.next) self.assertEqual([ ('replace', 0, 1, 0, 1), ('equal', 1, 7, 1, 7), ('replace', 7, 8, 7, 8), ], group) def test_grouped_opcodes_insert_blank_line_at_top(self): """ Regression test for #2090. Make sure that the equal block following an insert at the top of a file is correct. """ groups = diff.get_filtered_hunks(['B', 'C', 'D', 'E', 'F', 'G'], ['A', 'B', 'C', 'D', 'E', 'F', 'G'], context=3) self.assertEqual([('insert', 0, 0, 0, 1), ('equal', 0, 3, 1, 4)], groups.next()) self.assertRaises(StopIteration, groups.next) def test_unified_diff_no_context(self): diff_lines = list(diff.unified_diff(['a'], ['b'])) self.assertEqual(['@@ -1,1 +1,1 @@', '-a', '+b'], diff_lines) def test_quotes_not_marked_up(self): """Make sure that the escape calls leave quotes along, we don't need to escape them.""" changes = diff.diff_blocks(['ab'], ['a"b']) self.assertEqual(len(changes), 1) blocks = changes[0] self.assertEqual(len(blocks), 1) block = blocks[0] self.assertEqual(block['type'], 'mod') self.assertEqual(str(block['base']['lines'][0]), 'a<del></del>b') self.assertEqual(str(block['changed']['lines'][0]), 'a<ins>"</ins>b') def test_whitespace_marked_up1(self): """Regression test for #5795""" changes = diff.diff_blocks(['*a'], [' *a']) block = changes[0][0] self.assertEqual(block['type'], 'mod') self.assertEqual(str(block['base']['lines'][0]), '<del></del>*a') self.assertEqual(str(block['changed']['lines'][0]), '<ins>&nbsp;</ins>*a') def test_whitespace_marked_up2(self): """Related to #5795""" changes = diff.diff_blocks([' a'], [' b']) block = changes[0][0] self.assertEqual(block['type'], 'mod') self.assertEqual(str(block['base']['lines'][0]), '&nbsp; &nbsp;<del>a</del>') self.assertEqual(str(block['changed']['lines'][0]), '&nbsp; &nbsp;<ins>b</ins>') def test_whitespace_marked_up3(self): """Related to #5795""" changes = diff.diff_blocks(['a '], ['b ']) block = changes[0][0] self.assertEqual(block['type'], 'mod') self.assertEqual(str(block['base']['lines'][0]), '<del>a</del>&nbsp; &nbsp;') self.assertEqual(str(block['changed']['lines'][0]), '<ins>b</ins>&nbsp; &nbsp;') def test_expandtabs_works_right(self): """Regression test for #4557""" changes = diff.diff_blocks(['aa\tb'], ['aaxb']) block = changes[0][0] self.assertEqual(block['type'], 'mod') self.assertEqual(str(block['base']['lines'][0]), 'aa<del>&nbsp; &nbsp; &nbsp; </del>b') self.assertEqual(str(block['changed']['lines'][0]), 'aa<ins>x</ins>b') def test_suite(): return unittest.makeSuite(DiffTestCase) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
#////////////////////////Class constuctor////////////// #.......Boid class class Boid(object): """ Custom Boid Class""" def __init__(self,Pos,Vel,Range,Vision,Alignment,Separation,Cohesion): self.pos = Pos self.vel = Vel self.ran = Range self.vis = Vision self.Al = Alignment self.Se = Separation self.Co = Cohesion initial_boids = Pos #New List to store the trails from the boids self.Boid_trail = [] self.Boid_trail.append(initial_boids) def update(self,others): self.flocking(others) self.move() if Wrap == False: self.Boundary() elif Wrap == True: self.Boundary2() def move(self): t,u1,v1 = Terrain.ClosestPoint(self.pos) t1,pln = Terrain.FrameAt(u1,v1) xaxis = pln.XAxis ang1 = Rhino.Geometry.Vector3d.VectorAngle(self.vel,xaxis,pln) xaxis.Rotate(-ang1,pln.ZAxis) self.vel = xaxis self.pos = self.pos + (self.vel*Velocity) t,u2,v2 = Terrain.ClosestPoint(self.pos) self.pos = Terrain.PointAt(u2,v2) self.Boid_trail.append(self.pos) def Boundary(self): t,u,v = Terrain.ClosestPoint(self.pos) if u >= 1 or u <= 0 : self.vel[0] = -self.vel[0] self.vel[2] = -self.vel[2] if v >= 1 or v <= 0: self.vel[1] = -self.vel[1] self.vel[2] = -self.vel[2] def Boundary2(self): t,u,v = Terrain.ClosestPoint(self.pos) if u >= 1: self.pos = Terrain.PointAt(0,v) if u <= 0: self.pos = Terrain.PointAt(1,v) if v >= 1: self.pos = Terrain.PointAt(u,0) if v <= 0 : self.pos = Terrain.PointAt(u,1) def flocking(self,others): closer = self.Get_neighbors(others,self.ran,self.vis) cl_agents = closer[0] cl_distances = closer[1] if len(cl_agents)>0: b_acc = Rhino.Geometry.Vector3d(0.0,0.0,0.0) cl_center = self.Center(cl_agents) Al_vec = self.Align(cl_agents,cl_distances) Se_vec = self.Separate(cl_agents,cl_distances) Co_vec = self.Cohere(cl_agents) b_acc = b_acc+cl_center b_acc = b_acc+Al_vec b_acc = b_acc+Se_vec b_acc = b_acc+Co_vec self.vel = self.vel+b_acc self.vel = lim_vec(self.vel) def Align(self,others, o_dist): Al_steer = Rhino.Geometry.Vector3d(0.0,0.0,0.0) for i in range(len(others)): b = others[i] d = o_dist[i] if d >0 or d<0: dir = Rhino.Geometry.Vector3d dir = b.vel*(self.ran/d) Al_steer = Al_steer + dir Al_steer = lim_vec(Al_steer) Al_steer = Al_steer*self.Al return Al_steer def Separate(self,others, o_dist): desired_sep = 5.00 Se_steer =Rhino.Geometry.Vector3d(0.0,0.0,0.0) for i in range(len(others)): b = others[i] d = o_dist[i] if d > 0 and d <= desired_sep: dir = Rhino.Geometry.Vector3d dir = self.pos - b.pos if d >0 or d<0: dir = b.vel*(self.ran/d) if dir: Se_steer = Se_steer + dir Se_steer = lim_vec(Se_steer) Se_steer = Se_steer*self.Se return Se_steer def Cohere(self,others): Co_steer = Rhino.Geometry.Vector3d(0.0,0.0,0.0) for i in range(len(others)): b = others[i] Co_steer =Co_steer + b.pos Co_steer = Co_steer*(1/len(others)) d = self.pos.DistanceTo(Co_steer) Co_steer = Co_steer-self.pos if d >0 or d<0: Co_steer = Co_steer*(self.ran/d) Co_steer = lim_vec(Co_steer) Co_steer = Co_steer*self.Co return Co_steer def Center(self,others): sumx,sumy,sumz = 0.0,0.0,0.0 for other in others: n_pos = other.pos sumx += n_pos[0] sumy += n_pos[1] sumz += n_pos[2] for other in others: n_pos = other.pos if n_pos: center = Rhino.Geometry.Point3d(sumx/len(others),sumy/len(others),sumz/len(others)) toward = Rhino.Geometry.Vector3d toward = center - n_pos toward = lim_vec(toward) return toward else: return Rhino.Geometry.Vector3d(0,0,0) def Get_neighbors(self,others,radius,angle): Nboidslist = [] Nboids_dist = [] for other in others : if other is self: continue dist = Rhino.Geometry.Vector3d dist = other.pos - self.pos orient = Rhino.Geometry.Vector3d.VectorAngle(((self.pos+self.vel)-self.pos),dist) distance= dist.Length if distance <radius and orient < angle : Nboidslist.append(other) Nboids_dist.append(distance) return Nboidslist,Nboids_dist
import urllib, json, os from default_files import gitignore, wingproj, license, readme, setupfile, testfile def get_default_files(name,desc): """ General default files """ defaultfiles = [['.gitignore', gitignore()], ['README.md', readme(name, desc)], ['LICENSE.txt', license()]] return defaultfiles def get_default_py_files(name,desc,url): """ Python - specific default files """ defaultfiles = [['setup.py', setupfile(name, url, desc)]] return defaultfiles #make a source directory for setup.py to point to make_src_dir = True def prep_directory(basedir): if not os.path.exists(basedir): os.mkdir(basedir) def writefile(fpath,data): f = open(fpath, 'wb') f.write(data) f.close() def write_default_files(dpath, name, desc, url): if os.path.exists(dpath): onlyfiles = [ f for f in os.listdir(dpath) if os.path.isfile(os.path.join(dpath,f)) ] if len(onlyfiles) > 0: return #only add defaults if repo is empty print "Empty repo - adding default files..." files = get_default_files(name, desc) if "python" in desc.lower(): files = files + get_default_py_files(name,desc,url) if make_src_dir: srcdir = dpath+'/src' os.mkdir(srcdir) writefile(srcdir+'/__init__.py', '') testdir = dpath+'/tests' os.mkdir(testdir) writefile(testdir+'/__init__.py', '') writefile(testdir+'/test_main.py', testfile(name)) for fname, data in files: fn = '/'.join([dpath, fname]) writefile(fn, data) def process(cmd,name,fpath, ask, desc, url, typ = "repo"): if ask: print "Clone %s ?" % name resp = raw_input("(yes or no): ") #faster: [enter] for "yes", [space] + [enter] for "no" if resp == "no" or resp == " ": return os.system(cmd) if typ == "repo": write_default_files(fpath,name, desc, url) def get_gists(uname, ask = False, basedir = ''): print print "Cloning gists from %s..." % uname print gists = urllib.urlopen("https://api.github.com/users/%s/gists" % uname) wingfn = 'gists.wpr' if basedir: prep_directory(basedir) for item in json.loads(gists.readlines()[0]): name= '-'.join(item['files'].keys()[-1].split('.')) if basedir: fpath = '/'.join([basedir, name]) else: fpath = name if os.path.exists(fpath): #already cloned continue desc = item['description'] idn = item['id'] url = item['html_url'] cmd = "git clone git@gist.github.com:%s.git %s" % (idn, fpath) process(cmd, name, fpath, ask, desc, url,typ="gist") print def get_repos(uname, ask = False, basedir = ''): print print "Cloning repos from %s..." % uname print gists = urllib.urlopen("https://api.github.com/users/%s/repos" % uname) if basedir: prep_directory(basedir) for item in json.loads(gists.readlines()[0]): name= item['full_name'] if basedir: fpath = '/'.join([basedir, item['name']]) else: fpath = item['name'] if os.path.exists(fpath): continue cmd = "git clone <EMAIL>:%s.git %s" % (name, fpath) desc = item['description'] url = item['html_url'] process(cmd, item['name'], fpath, ask, desc,url, typ="repo") print
# coding: utf-8 """ Hydrogen Atom API The Hydrogen Atom API # noqa: E501 OpenAPI spec version: 1.7.0 Contact: <EMAIL> Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class ClientAdvisorOverviewVO(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'age': 'int', 'client_account_list': 'list[ClientAccountAdvisorVO]', 'client_assets': 'ClientAssetsAdvisorVO', 'client_id': 'str', 'date_of_birth': 'datetime', 'first_name': 'str', 'gender': 'str', 'income': 'int', 'last_name': 'str' } attribute_map = { 'age': 'age', 'client_account_list': 'client_account_list', 'client_assets': 'client_assets', 'client_id': 'client_id', 'date_of_birth': 'date_of_birth', 'first_name': 'first_name', 'gender': 'gender', 'income': 'income', 'last_name': 'last_name' } def __init__(self, age=None, client_account_list=None, client_assets=None, client_id=None, date_of_birth=None, first_name=None, gender=None, income=None, last_name=None): # noqa: E501 """ClientAdvisorOverviewVO - a model defined in Swagger""" # noqa: E501 self._age = None self._client_account_list = None self._client_assets = None self._client_id = None self._date_of_birth = None self._first_name = None self._gender = None self._income = None self._last_name = None self.discriminator = None if age is not None: self.age = age if client_account_list is not None: self.client_account_list = client_account_list if client_assets is not None: self.client_assets = client_assets if client_id is not None: self.client_id = client_id if date_of_birth is not None: self.date_of_birth = date_of_birth if first_name is not None: self.first_name = first_name if gender is not None: self.gender = gender if income is not None: self.income = income if last_name is not None: self.last_name = last_name @property def age(self): """Gets the age of this ClientAdvisorOverviewVO. # noqa: E501 :return: The age of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: int """ return self._age @age.setter def age(self, age): """Sets the age of this ClientAdvisorOverviewVO. :param age: The age of this ClientAdvisorOverviewVO. # noqa: E501 :type: int """ self._age = age @property def client_account_list(self): """Gets the client_account_list of this ClientAdvisorOverviewVO. # noqa: E501 :return: The client_account_list of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: list[ClientAccountAdvisorVO] """ return self._client_account_list @client_account_list.setter def client_account_list(self, client_account_list): """Sets the client_account_list of this ClientAdvisorOverviewVO. :param client_account_list: The client_account_list of this ClientAdvisorOverviewVO. # noqa: E501 :type: list[ClientAccountAdvisorVO] """ self._client_account_list = client_account_list @property def client_assets(self): """Gets the client_assets of this ClientAdvisorOverviewVO. # noqa: E501 :return: The client_assets of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: ClientAssetsAdvisorVO """ return self._client_assets @client_assets.setter def client_assets(self, client_assets): """Sets the client_assets of this ClientAdvisorOverviewVO. :param client_assets: The client_assets of this ClientAdvisorOverviewVO. # noqa: E501 :type: ClientAssetsAdvisorVO """ self._client_assets = client_assets @property def client_id(self): """Gets the client_id of this ClientAdvisorOverviewVO. # noqa: E501 :return: The client_id of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: str """ return self._client_id @client_id.setter def client_id(self, client_id): """Sets the client_id of this ClientAdvisorOverviewVO. :param client_id: The client_id of this ClientAdvisorOverviewVO. # noqa: E501 :type: str """ self._client_id = client_id @property def date_of_birth(self): """Gets the date_of_birth of this ClientAdvisorOverviewVO. # noqa: E501 :return: The date_of_birth of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: datetime """ return self._date_of_birth @date_of_birth.setter def date_of_birth(self, date_of_birth): """Sets the date_of_birth of this ClientAdvisorOverviewVO. :param date_of_birth: The date_of_birth of this ClientAdvisorOverviewVO. # noqa: E501 :type: datetime """ self._date_of_birth = date_of_birth @property def first_name(self): """Gets the first_name of this ClientAdvisorOverviewVO. # noqa: E501 :return: The first_name of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: str """ return self._first_name @first_name.setter def first_name(self, first_name): """Sets the first_name of this ClientAdvisorOverviewVO. :param first_name: The first_name of this ClientAdvisorOverviewVO. # noqa: E501 :type: str """ self._first_name = first_name @property def gender(self): """Gets the gender of this ClientAdvisorOverviewVO. # noqa: E501 :return: The gender of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: str """ return self._gender @gender.setter def gender(self, gender): """Sets the gender of this ClientAdvisorOverviewVO. :param gender: The gender of this ClientAdvisorOverviewVO. # noqa: E501 :type: str """ self._gender = gender @property def income(self): """Gets the income of this ClientAdvisorOverviewVO. # noqa: E501 :return: The income of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: int """ return self._income @income.setter def income(self, income): """Sets the income of this ClientAdvisorOverviewVO. :param income: The income of this ClientAdvisorOverviewVO. # noqa: E501 :type: int """ self._income = income @property def last_name(self): """Gets the last_name of this ClientAdvisorOverviewVO. # noqa: E501 :return: The last_name of this ClientAdvisorOverviewVO. # noqa: E501 :rtype: str """ return self._last_name @last_name.setter def last_name(self, last_name): """Sets the last_name of this ClientAdvisorOverviewVO. :param last_name: The last_name of this ClientAdvisorOverviewVO. # noqa: E501 :type: str """ self._last_name = last_name def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ClientAdvisorOverviewVO, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ClientAdvisorOverviewVO): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
import os import sys import traceback import json from osgeo import gdal, osr OUTPUT_FOLDER = "data" def write_metadata_json(path, metadata): with open(os.path.join(OUTPUT_FOLDER, path, 'metadata.json'), 'w') as outfile: json.dump(metadata, outfile, indent=4, sort_keys=True) def get_extent(dataset): cols = dataset.RasterXSize rows = dataset.RasterYSize transform = dataset.GetGeoTransform() minx = transform[0] maxx = transform[0] + cols * transform[1] + rows * transform[2] miny = transform[3] + cols * transform[4] + rows * transform[5] maxy = transform[3] return { "minX": str(minx), "maxX": str(maxx), "minY": str(miny), "maxY": str(maxy), "cols": str(cols), "rows": str(rows) } def create_tiles(minx, miny, maxx, maxy, n): width = maxx - minx height = maxy - miny matrix = [] for j in range(n, 0, -1): for i in range(0, n): ulx = minx + (width/n) * i # 10/5 * 1 uly = miny + (height/n) * j # 10/5 * 1 lrx = minx + (width/n) * (i + 1) lry = miny + (height/n) * (j - 1) matrix.append([[ulx, uly], [lrx, lry]]) return matrix def split(file_name, n): print "Splitting ", file_name, "into ", n, " pieces" raw_file_name = os.path.splitext(os.path.basename(file_name))[0].replace("_downsample", "") driver = gdal.GetDriverByName('GTiff') dataset = gdal.Open(file_name) band = dataset.GetRasterBand(1) transform = dataset.GetGeoTransform() extent = get_extent(dataset) cols = int(extent["cols"]) rows = int(extent["rows"]) print "Columns: ", cols print "Rows: ", rows minx = float(extent["minX"]) maxx = float(extent["maxX"]) miny = float(extent["minY"]) maxy = float(extent["maxY"]) # width = maxx - minx # height = maxy - miny output_path = os.path.join(OUTPUT_FOLDER, raw_file_name) if not os.path.exists(output_path): os.makedirs(output_path) # print "GCD", gcd(round(width, 0), round(height, 0)) # print "Width", width # print "height", height tiles = create_tiles(minx, miny, maxx, maxy, n) transform = dataset.GetGeoTransform() x_origin = transform[0] y_origin = transform[3] pixel_width = transform[1] pixel_height = -transform[5] print x_origin, y_origin tile_num = 0 metadata = {} for tile in tiles: minx = tile[0][0] maxx = tile[1][0] miny = tile[1][1] maxy = tile[0][1] p1 = (minx, maxy) p2 = (maxx, miny) i1 = int((p1[0] - x_origin) / pixel_width) j1 = int((y_origin - p1[1]) / pixel_height) i2 = int((p2[0] - x_origin) / pixel_width) j2 = int((y_origin - p2[1]) / pixel_height) print i1, j1 print i2, j2 new_cols = i2-i1 new_rows = j2-j1 data = band.ReadAsArray(i1, j1, new_cols, new_rows) #print data new_x = x_origin + i1*pixel_width new_y = y_origin - j1*pixel_height print new_x, new_y new_transform = (new_x, transform[1], transform[2], new_y, transform[4], transform[5]) output_file_base = raw_file_name + "_" + str(tile_num) + ".tif" output_file = os.path.join(OUTPUT_FOLDER, raw_file_name, output_file_base) tile_dataset = driver.Create( output_file, new_cols, new_rows, 1, gdal.GDT_Float32 ) # Writing output raster tile_dataset.GetRasterBand(1).WriteArray(data) # Setting extension of output raster # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution tile_dataset.SetGeoTransform(new_transform) wkt = dataset.GetProjection() # Setting spatial reference of output raster srs = osr.SpatialReference() srs.ImportFromWkt(wkt) export_prj = srs.ExportToWkt() tile_dataset.SetProjection(export_prj) # Set file-level metadata tile_extent = get_extent(tile_dataset) tile_dataset.SetMetadata(tile_extent) print "Metadata set: ", tile_dataset.GetMetadata() # Close output raster dataset tile_dataset = None # Set our metadata info for this tile metadata[tile_num] = tile_extent metadata[tile_num]["fileSize"] = os.path.getsize(output_file) metadata[tile_num]["path"] = output_file tile_num += 1 write_metadata_json(raw_file_name, metadata) dataset = None if __name__ == '__main__': try: if len(sys.argv) == 1: print "Input file not specified" else: filename = str(sys.argv[1]) if len(sys.argv) == 3: n = int(sys.argv[2]) else: n = 3 split(filename, n) print "...Done!" except: error = sys.exc_info()[0] print "There was an error: ", error, "\n" print traceback.format_exc()
import itertools, copy, random import numpy as np from time import time from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.circuit.library.standard_gates import HGate, SGate, SdgGate, XGate from qiskit_helper_functions.non_ibmq_functions import read_dict, find_process_jobs, evaluate_circ, get_alloted_backend def run_subcircuit_instances(subcircuits,subcircuit_instances,eval_mode,num_shots_fn,tket=False): ''' subcircuit_instance_probs[subcircuit_idx][subcircuit_instance_idx] = measured probability ''' subcircuit_instance_probs = {} for subcircuit_idx in subcircuit_instances: subcircuit_instance_probs[subcircuit_idx] = {} num_shots = num_shots_fn(subcircuits[subcircuit_idx]) for init_meas in subcircuit_instances[subcircuit_idx]: subcircuit_instance_idx = subcircuit_instances[subcircuit_idx][init_meas] if subcircuit_instance_idx not in subcircuit_instance_probs[subcircuit_idx]: # print('Subcircuit %d instance %d'%(subcircuit_idx,subcircuit_instance_idx)) subcircuit_instance = modify_subcircuit_instance( subcircuit=subcircuits[subcircuit_idx], init=init_meas[0],meas=init_meas[1]) # subcircuit_inst_prob = simulate_subcircuit(subcircuit=subcircuit_instance,eval_mode=eval_mode,num_shots=num_shots) if type(eval_mode) is dict: subcircuit_inst_prob = simulate_subcircuit(subcircuit=subcircuit_instance,eval_mode=get_alloted_backend(eval_mode, subcircuits[subcircuit_idx]),num_shots=num_shots, tket=tket) else: subcircuit_inst_prob = simulate_subcircuit(subcircuit=subcircuit_instance,eval_mode=eval_mode,num_shots=num_shots, tket=tket) mutated_meas = mutate_measurement_basis(meas=init_meas[1]) for meas in mutated_meas: measured_prob = measure_prob(unmeasured_prob=subcircuit_inst_prob,meas=meas) mutated_subcircuit_instance_idx = subcircuit_instances[subcircuit_idx][(init_meas[0],meas)] subcircuit_instance_probs[subcircuit_idx][mutated_subcircuit_instance_idx] = measured_prob # print('Measured instance %d'%mutated_subcircuit_instance_idx) return subcircuit_instance_probs def mutate_measurement_basis(meas): ''' I and Z measurement basis correspond to the same logical circuit ''' if all(x!='I' for x in meas): return [meas] else: mutated_meas = [] for x in meas: if x != 'I': mutated_meas.append([x]) else: mutated_meas.append(['I','Z']) mutated_meas = list(itertools.product(*mutated_meas)) return mutated_meas def modify_subcircuit_instance(subcircuit, init, meas): ''' Modify the different init, meas for a given subcircuit Returns: Modified subcircuit_instance List of mutated measurements ''' subcircuit_dag = circuit_to_dag(subcircuit) subcircuit_instance_dag = copy.deepcopy(subcircuit_dag) for i,x in enumerate(init): q = subcircuit.qubits[i] if x == 'zero': continue elif x == 'one': subcircuit_instance_dag.apply_operation_front(op=XGate(),qargs=[q],cargs=[]) elif x == 'plus': subcircuit_instance_dag.apply_operation_front(op=HGate(),qargs=[q],cargs=[]) elif x == 'minus': subcircuit_instance_dag.apply_operation_front(op=HGate(),qargs=[q],cargs=[]) subcircuit_instance_dag.apply_operation_front(op=XGate(),qargs=[q],cargs=[]) elif x == 'plusI': subcircuit_instance_dag.apply_operation_front(op=SGate(),qargs=[q],cargs=[]) subcircuit_instance_dag.apply_operation_front(op=HGate(),qargs=[q],cargs=[]) elif x == 'minusI': subcircuit_instance_dag.apply_operation_front(op=SGate(),qargs=[q],cargs=[]) subcircuit_instance_dag.apply_operation_front(op=HGate(),qargs=[q],cargs=[]) subcircuit_instance_dag.apply_operation_front(op=XGate(),qargs=[q],cargs=[]) else: raise Exception('Illegal initialization :',x) for i,x in enumerate(meas): q = subcircuit.qubits[i] if x == 'I' or x == 'comp': continue elif x == 'X': subcircuit_instance_dag.apply_operation_back(op=HGate(),qargs=[q],cargs=[]) elif x == 'Y': subcircuit_instance_dag.apply_operation_back(op=SdgGate(),qargs=[q],cargs=[]) subcircuit_instance_dag.apply_operation_back(op=HGate(),qargs=[q],cargs=[]) else: raise Exception('Illegal measurement basis:',x) subcircuit_instance_circuit = dag_to_circuit(subcircuit_instance_dag) return subcircuit_instance_circuit def simulate_subcircuit(subcircuit,eval_mode,num_shots, tket=False): ''' Simulate a subcircuit ''' if eval_mode=='sv': subcircuit_inst_prob = evaluate_circ(circuit=subcircuit,backend='statevector_simulator') elif eval_mode=='qasm': subcircuit_inst_prob = evaluate_circ(circuit=subcircuit,backend='noiseless_qasm_simulator',options={'num_shots':num_shots}) else: subcircuit_inst_prob = evaluate_circ(circuit=subcircuit,backend=eval_mode,options={'num_shots':num_shots}, TKET=tket) # else: # raise NotImplementedError return subcircuit_inst_prob def measure_prob(unmeasured_prob,meas): if meas.count('comp')==len(meas): return unmeasured_prob else: measured_prob = np.zeros(int(2**meas.count('comp'))) # print('Measuring in',meas) for full_state, p in enumerate(unmeasured_prob): sigma, effective_state = measure_state(full_state=full_state,meas=meas) # TODO: Add states merging here. Change effective_state to merged_bin measured_prob[effective_state] += sigma*p return measured_prob def measure_state(full_state,meas): ''' Compute the corresponding effective_state for the given full_state Measured in basis `meas` Returns sigma (int), effective_state (int) where sigma = +-1 ''' bin_full_state = bin(full_state)[2:].zfill(len(meas)) sigma = 1 bin_effective_state = '' for meas_bit, meas_basis in zip(bin_full_state,meas[::-1]): if meas_bit=='1' and meas_basis!='I' and meas_basis!='comp': sigma*=-1 if meas_basis=='comp': bin_effective_state += meas_bit effective_state = int(bin_effective_state,2) if bin_effective_state!='' else 0 # print('bin_full_state = %s --> %d * %s (%d)'%(bin_full_state,sigma,bin_effective_state,effective_state)) return sigma, effective_state
<filename>2DX4_FinalProject_molinark.py ''' <NAME> 400136596 2DX4 Final Project Using Python 3.6.5 Need to pyserial, open3d, numpy, math, and sys libraries ''' import serial import math import numpy import open3d import sys angleOffset = 0 #starting angle in degrees relative to motor position (just corrects for staring orientation of motor) distanceOffset = 10 #offset of the VL53L1X sensor from the axis of rotation (in millimeters) s = serial.Serial("COM6", 115200) print("Opening: " + s.name) lines = [] def initialize(): s.write(b'1') #write 1 to serial port to indicate that its ready to read data start = 0 #initialize start flag to 0 #ignore all serial data (eg startup print statements) until the step angle is given followed by a comma while(start == 0): firstLine = s.readline().decode().replace(',','') #read serial data but take out any commas try: #if the serial data is a number then that means it is the step angle stepAngle = int(firstLine) start = 1 #set start flag to 1 except: #if the serial data is not a number print(firstLine) getData(stepAngle) def getData(angle): f = open("tof_radar.xyz", "w") #create a xyz file to write to z = 0 #initial z position i = 0 revs = 0 global lines while(i<int(360/angle)): x = s.readline() # read one line c = x.decode() # convert to str if(c != c.replace(',','')): ##if there is a comma in the string that means that it is giving the step angle angle = int(c.replace(',','')) #make sure step angle is updated x = s.readline() #read the next string c = x.decode() if c=="restart\n": #if emergency stop button is pressed print("Goodbye\n") f.close() #close xyz file sys.exit() #stop the program else: distance = int(c)+distanceOffset #get serial data and set it as distance. add the distanceOffset to adjust for hardware limitations #use unit vector direction & distance to get x and y position x=-distance*math.sin(i*math.radians(angle)+math.radians(angleOffset)) y=distance*math.cos(i*math.radians(angle)+math.radians(angleOffset)) data = str(x)+" "+str(y)+" "+str(z)+"\n" f.write(data) #write coordinates to xyz file print(data) ####lines.append([i, (i+1)%(360/angle)]) if(i == int(360/angle)-1): #once full revolution is completed revs = revs + 1 keepCollecting = input("Press enter to end program and see 3D plot. If you would like to keep collecting data, enter the change in Z coordinate from the last measurement in mm.\n") try: #if a number is entered z = z + int(keepCollecting) #update the z coordinate for the next rotation i = -1 #i will be updated to 0 after this if statement and the while loop will run again except: #if enter is pressed (or a number is not entered) print("Closing: " + s.name) f.close() visualize(angle, revs) i = i + 1 def visualize(angle, revs): global lines pts = int(360/angle) #connect lines between pts in each plane for i in range(revs): #for each displacement (offset in z direction) for j in range(pts): #go through all points in the plane if(j+1 == pts): #if its the last point connect it to the first point lines.append([j+i*pts, 0+i*pts]) else: #connect adjacent points in the plane lines.append([j+i*pts, j+1+i*pts]) #connect vertices between planes for i in range(revs-1): #go through all planes execpt the last one for j in range(pts): #go through all points in that plane lines.append([j+i*pts, j+(i+1)*pts]) #connect the point to the corresponding point in the next plane pcd = open3d.io.read_point_cloud("tof_radar.xyz", format='xyz') line_set = open3d.geometry.LineSet() line_set.points = open3d.utility.Vector3dVector(numpy.asarray(pcd.points)) line_set.lines = open3d.utility.Vector2iVector(lines) print(pcd) print(numpy.asarray(pcd.points)) open3d.visualization.draw_geometries([line_set]) #mesh visualization #open3d.visualization.draw_geometries([pcd]) #point cloud visualization initialize()
import datetime import typing import numpy as np import pandas as pd from dateutil.relativedelta import relativedelta from influxdb import DataFrameClient import atpy.data.iqfeed.bar_util as bars from atpy.data.ts_util import slice_periods class InfluxDBOHLCRequest(object): def __init__(self, client: DataFrameClient, interval_len: int, interval_type: str = 's', listeners=None): """ :param client: influxdb client :param interval_len: interval length :param interval_type: interval type """ self.interval_len = interval_len self.interval_type = interval_type self.client = client self.listeners = listeners if self.listeners is not None: self.listeners += self.on_event def on_event(self, event): if event['type'] == 'request_ohlc' and self.listeners is not None: data = self.request(**event['data']) self.listeners({'type': 'cache_result', 'data': data}) def _request_raw_data(self, symbol: typing.Union[list, str] = None, bgn_prd: datetime.datetime = None, end_prd: datetime.datetime = None, ascending: bool = True): """ :param symbol: symbol or symbol list :param bgn_prd: start datetime (excluding) :param end_prd: end datetime (excluding) :param ascending: asc/desc :return: data from the database """ query = "SELECT * FROM bars" + \ _query_where(interval_len=self.interval_len, interval_type=self.interval_type, symbol=symbol, bgn_prd=bgn_prd, end_prd=end_prd) + \ " ORDER BY time " + "ASC" if ascending else "DESC" result = self.client.query(query, chunked=True) if len(result) == 0: result = None else: result = result['bars'] result.drop('interval', axis=1, inplace=True) result.index.name = 'timestamp' for c in [c for c in result.columns if result[c].dtype == np.int64]: result[c] = result[c].astype(np.uint64, copy=False) result['timestamp'] = result.index if len(result['symbol'].unique()) > 1: result.set_index('symbol', drop=False, append=True, inplace=True) result.sort_index(inplace=True, ascending=ascending) result = result[[c for c in ['open', 'high', 'low', 'close', 'volume', 'timestamp', 'symbol'] if c in result.columns]] return result def _postprocess_data(self, data): return data def request(self, symbol: typing.Union[list, str] = None, bgn_prd: datetime.datetime = None, end_prd: datetime.datetime = None, ascending: bool = True, synchronize_timestamps: bool = False): data = self._request_raw_data(symbol=symbol, bgn_prd=bgn_prd, end_prd=end_prd, ascending=ascending) if synchronize_timestamps: data = bars.synchronize_timestamps(data) return data, self._postprocess_data(data) class InfluxDBValueRequest(object): """abstract class for single value selection""" def __init__(self, value: str, client: DataFrameClient, interval_len: int, interval_type: str = 's', listeners=None): """ :param value: value to select. value is a part of query :param client: influxdb client :param interval_len: interval length :param interval_type: interval type :param listeners: listeners """ self.value = value self.interval_len = interval_len self.interval_type = interval_type self.client = client self.listeners = listeners if self.listeners is not None: self.listeners += self.on_event self.means = None self.stddev = None def on_event(self, event): if event['type'] == 'request_value': data = self.request(**event['data']) self.listeners({'type': 'cache_result', 'data': data}) def _request_raw_data(self, symbol: typing.Union[list, str] = None, bgn_prd: datetime.datetime = None, end_prd: datetime.datetime = None, ascending: bool = True): """ :param symbol: symbol or symbol list :param bgn_prd: start datetime (excluding) :param end_prd: end datetime (excluding) :param ascending: asc/desc :return: data from the database """ query = "SELECT symbol, " + self.value + " FROM bars" + \ _query_where(interval_len=self.interval_len, interval_type=self.interval_type, symbol=symbol, bgn_prd=bgn_prd, end_prd=end_prd) + \ " ORDER BY time " + "ASC" if ascending else "DESC" result = self.client.query(query, chunked=True) if len(result) == 0: result = None else: result = result['bars'] result.index.name = 'timestamp' for c in [c for c in result.columns if result[c].dtype == np.int64]: result[c] = result[c].astype(np.uint64, copy=False) result['timestamp'] = result.index if len(result['symbol'].unique()) > 1: result.set_index('symbol', drop=False, append=True, inplace=True) result = result.swaplevel(0, 1, axis=0) result.sort_index(inplace=True, ascending=ascending) return result def _postprocess_data(self, data): if self.means is not None or self.stddev is not None: data = data.copy(deep=True) if len(data['symbol'].unique()) > 1: if self.means is not None: data['delta'] = data['delta'].groupby(level='timestamp').apply(lambda x: x - self.means[x.name]) if self.stddev is not None: data['delta'] = data['delta'].groupby(level='timestamp').apply(lambda x: x / self.stddev[x.name]) else: if self.means is not None: data['delta'] = data['delta'] - self.means[data['symbol'][0]] if self.stddev is not None: data['delta'] = data['delta'] / self.stddev[data['symbol'][0]] return data def request(self, symbol: typing.Union[list, str] = None, bgn_prd: datetime.datetime = None, end_prd: datetime.datetime = None, ascending: bool = True, synchronize_timestamps: bool = False): data = self._request_raw_data(symbol=symbol, bgn_prd=bgn_prd, end_prd=end_prd, ascending=ascending) if synchronize_timestamps: data = bars.synchronize_timestamps(data) return data, self._postprocess_data(data) def enable_mean(self, symbol: typing.Union[list, str] = None, bgn_prd: datetime.datetime = None, end_prd: datetime.datetime = None): """ :param symbol: symbol or symbol list :param bgn_prd: start datetime (excluding) :param end_prd: end datetime (excluding) :return: data from the database """ query = "SELECT MEAN(delta) FROM (SELECT symbol, (close - open) / open as delta FROM bars" + \ _query_where(interval_len=self.interval_len, interval_type=self.interval_type, symbol=symbol, bgn_prd=bgn_prd, end_prd=end_prd) + \ ") GROUP BY symbol" rs = super(DataFrameClient, self.client).query(query, chunked=True) self.means = {k[1]['symbol']: next(data)['mean'] for k, data in rs.items()} def enable_stddev(self, symbol: typing.Union[list, str] = None, bgn_prd: datetime.datetime = None, end_prd: datetime.datetime = None): """ :param symbol: symbol or symbol list :param bgn_prd: start datetime (excluding) :param end_prd: end datetime (excluding) :return: data from the database """ query = "SELECT STDDEV(delta) FROM (SELECT symbol, (close - open) / open as delta FROM bars" + \ _query_where(interval_len=self.interval_len, interval_type=self.interval_type, symbol=symbol, bgn_prd=bgn_prd, end_prd=end_prd) + \ ") GROUP BY symbol" rs = super(DataFrameClient, self.client).query(query, chunked=True) self.stddev = {k[1]['symbol']: next(data)['stddev'] for k, data in rs.items()} def get_adjustments(client: DataFrameClient, symbol: typing.Union[list, str] = None, typ: str = None, provider: str = None): query = "SELECT * FROM splits_dividends" where = list() if symbol is not None: if isinstance(symbol, list) and len(symbol) > 0: where.append("symbol =~ /{}/".format("|".join(['^' + s + '$' for s in symbol]))) elif isinstance(symbol, str) and len(symbol) > 0: where.append("symbol = '{}'".format(symbol)) if typ is not None: where.append("type='{}'".format(typ)) if provider is not None: where.append("provider='{}'".format(provider)) if len(where) > 0: query += " WHERE " + " AND ".join(where) result = DataFrameClient.query(client, query) if result: result = result['splits_dividends'] result.set_index(['symbol', 'type', 'provider'], inplace=True, drop=True, append=True) result.sort_index(inplace=True) return result return pd.DataFrame() def _query_where(interval_len: int, interval_type: str, symbol: typing.Union[list, str] = None, bgn_prd: datetime.datetime = None, end_prd: datetime.datetime = None): """ generate query where string :param interval_len: interval length :param interval_type: interval type :param symbol: symbol or symbol list :param bgn_prd: start datetime (including) :param end_prd: end datetime (excluding) :return: data from the database """ result = " WHERE" \ " interval = '{}'" + \ ('' if symbol is None else " AND symbol =" + ("~ /{}/ " if isinstance(symbol, list) else " '{}'")) + \ ('' if bgn_prd is None else " AND time >= '{}'") + \ ('' if end_prd is None else " AND time < '{}'") bgn_prd = bgn_prd.replace(tzinfo=None) if bgn_prd is not None else None end_prd = end_prd.replace(tzinfo=None) if end_prd is not None else None args = tuple(filter(lambda x: x is not None, [str(interval_len) + '_' + interval_type, None if symbol is None else "|".join(['^' + s + '$' for s in symbol]) if isinstance(symbol, list) else symbol, bgn_prd, end_prd])) return result.format(*args) class BarsInPeriodProvider(object): """ OHLCV Bars in period provider """ def __init__(self, influxdb_cache: InfluxDBOHLCRequest, bgn_prd: datetime.datetime, delta: relativedelta, symbol: typing.Union[list, str] = None, ascend: bool = True, overlap: relativedelta = None): self._periods = slice_periods(bgn_prd=bgn_prd, delta=delta, ascend=ascend, overlap=overlap) self.influxdb_cache = influxdb_cache self.symbol = symbol self.ascending = ascend def __iter__(self): self._deltas = -1 return self def __next__(self): self._deltas += 1 if self._deltas < len(self._periods): return self.influxdb_cache.request(symbol=self.symbol, bgn_prd=self._periods[self._deltas][0], end_prd=self._periods[self._deltas][1], ascending=self.ascending) else: raise StopIteration
#!/usr/bin/env python # # Copyright 2009 <NAME> All Rights Reserved. # Portions Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for gmock.scripts.generator.cpp.gmock_class.""" __author__ = '<EMAIL> (<NAME>)' import os import sys import unittest # Allow the cpp imports below to work when run as a standalone script. sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from cpp import ast from cpp import gmock_class class TestCase(unittest.TestCase): """Helper class that adds assert methods.""" def StripLeadingWhitespace(self, lines): """Strip leading whitespace in each line in 'lines'.""" return '\n'.join([s.lstrip() for s in lines.split('\n')]) def assertEqualIgnoreLeadingWhitespace(self, expected_lines, lines): """Specialized assert that ignores the indent level.""" self.assertEqual(expected_lines, self.StripLeadingWhitespace(lines)) class GenerateMethodsTest(TestCase): def GenerateMethodSource(self, cpp_source): """Convert C++ source to Google Mock output source lines.""" method_source_lines = [] # <test> is a pseudo-filename, it is not read or written. builder = ast.BuilderFromSource(cpp_source, '<test>') ast_list = list(builder.Generate()) gmock_class._GenerateMethods(method_source_lines, cpp_source, ast_list[0]) return '\n'.join(method_source_lines) def testSimpleMethod(self): source = """ class Foo { public: virtual int Bar(); }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD0(Bar,\nint());', self.GenerateMethodSource(source)) def testSimpleConstMethod(self): source = """ class Foo { public: virtual void Bar(bool flag) const; }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_CONST_METHOD1(Bar,\nvoid(bool flag));', self.GenerateMethodSource(source)) def testExplicitVoid(self): source = """ class Foo { public: virtual int Bar(void); }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD0(Bar,\nint(void));', self.GenerateMethodSource(source)) def testStrangeNewlineInParameter(self): source = """ class Foo { public: virtual void Bar(int a) = 0; }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD1(Bar,\nvoid(int a));', self.GenerateMethodSource(source)) def testDefaultParameters(self): source = """ class Foo { public: virtual void Bar(int a, char c = 'x') = 0; }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD2(Bar,\nvoid(int, char));', self.GenerateMethodSource(source)) def testMultipleDefaultParameters(self): source = """ class Foo { public: virtual void Bar(int a = 42, char c = 'x') = 0; }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD2(Bar,\nvoid(int, char));', self.GenerateMethodSource(source)) def testRemovesCommentsWhenDefaultsArePresent(self): source = """ class Foo { public: virtual void Bar(int a = 42 /* a comment */, char /* other comment */ c= 'x') = 0; }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD2(Bar,\nvoid(int, char));', self.GenerateMethodSource(source)) def testDoubleSlashCommentsInParameterListAreRemoved(self): source = """ class Foo { public: virtual void Bar(int a, // inline comments should be elided. int b // inline comments should be elided. ) const = 0; }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_CONST_METHOD2(Bar,\nvoid(int a, int b));', self.GenerateMethodSource(source)) def testCStyleCommentsInParameterListAreNotRemoved(self): # NOTE(nnorwitz): I'm not sure if it's the best behavior to keep these # comments. Also note that C style comments after the last parameter # are still elided. source = """ class Foo { public: virtual const string& Bar(int /* keeper */, int b); }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD2(Bar,\nconst string&(int /* keeper */, int b));', self.GenerateMethodSource(source)) def testArgsOfTemplateTypes(self): source = """ class Foo { public: virtual int Bar(const vector<int>& v, map<int, string>* output); };""" self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD2(Bar,\n' 'int(const vector<int>& v, map<int, string>* output));', self.GenerateMethodSource(source)) def testReturnTypeWithOneTemplateArg(self): source = """ class Foo { public: virtual vector<int>* Bar(int n); };""" self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD1(Bar,\nvector<int>*(int n));', self.GenerateMethodSource(source)) def testReturnTypeWithManyTemplateArgs(self): source = """ class Foo { public: virtual map<int, string> Bar(); };""" # Comparing the comment text is brittle - we'll think of something # better in case this gets annoying, but for now let's keep it simple. self.assertEqualIgnoreLeadingWhitespace( '// The following line won\'t really compile, as the return\n' '// type has multiple template arguments. To fix it, use a\n' '// typedef for the return type.\n' 'MOCK_METHOD0(Bar,\nmap<int, string>());', self.GenerateMethodSource(source)) def testSimpleMethodInTemplatedClass(self): source = """ template<class T> class Foo { public: virtual int Bar(); }; """ self.assertEqualIgnoreLeadingWhitespace( 'MOCK_METHOD0_T(Bar,\nint());', self.GenerateMethodSource(source)) class GenerateMocksTest(TestCase): def GenerateMocks(self, cpp_source): """Convert C++ source to complete Google Mock output source.""" # <test> is a pseudo-filename, it is not read or written. filename = '<test>' builder = ast.BuilderFromSource(cpp_source, filename) ast_list = list(builder.Generate()) lines = gmock_class._GenerateMocks(filename, cpp_source, ast_list, None) return '\n'.join(lines) def testNamespaces(self): source = """ namespace Foo { namespace Bar { class Forward; } namespace Baz { class Test { public: virtual void Foo(); }; } // namespace Baz } // namespace Foo """ expected = """\ namespace Foo { namespace Baz { class MockTest : public Test { public: MOCK_METHOD0(Foo, void()); }; } // namespace Baz } // namespace Foo """ self.assertEqualIgnoreLeadingWhitespace( expected, self.GenerateMocks(source)) def testClassWithStorageSpecifierMacro(self): source = """ class STORAGE_SPECIFIER Test { public: virtual void Foo(); }; """ expected = """\ class MockTest : public Test { public: MOCK_METHOD0(Foo, void()); }; """ self.assertEqualIgnoreLeadingWhitespace( expected, self.GenerateMocks(source)) def testTemplatedForwardDeclaration(self): source = """ template <class T> class Forward; // Forward declaration should be ignored. class Test { public: virtual void Foo(); }; """ expected = """\ class MockTest : public Test { public: MOCK_METHOD0(Foo, void()); }; """ self.assertEqualIgnoreLeadingWhitespace( expected, self.GenerateMocks(source)) def testTemplatedClass(self): source = """ template <typename S, typename T> class Test { public: virtual void Foo(); }; """ expected = """\ template <typename T0, typename T1> class MockTest : public Test<T0, T1> { public: MOCK_METHOD0_T(Foo, void()); }; """ self.assertEqualIgnoreLeadingWhitespace( expected, self.GenerateMocks(source)) if __name__ == '__main__': unittest.main()
<reponame>icanbwell/mockserver_client import json from typing import Dict, Any, Optional, List, Union, cast from urllib.parse import parse_qs class MockRequest: def __init__(self, request: Dict[str, Any]) -> None: """ Class for mock requests :param request: """ self.request: Dict[str, Any] = request self.method: Optional[str] = self.request.get("method") self.path: Optional[str] = self.request.get("path") self.querystring_params: Optional[Dict[str, Any]] = self.request.get( "queryStringParameters" ) self.headers: Optional[Dict[str, Any]] = self.request.get("headers") raw_body: Union[str, bytes, Dict[str, Any], List[Dict[str, Any]]] = cast( Union[str, bytes, Dict[str, Any], List[Dict[str, Any]]], self.request.get("body"), ) self.body_list: Optional[List[Dict[str, Any]]] = MockRequest.parse_body( body=raw_body, headers=self.headers ) assert self.body_list is None or isinstance( self.body_list, list ), f"{type(self.body_list)}: {json.dumps(self.body_list)}" raw_json_content: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = ( self.body_list[0].get("json") if self.body_list is not None and len(self.body_list) > 0 else None ) self.json_list: Optional[List[Dict[str, Any]]] = ( MockRequest.parse_body(body=raw_json_content, headers=self.headers) if raw_json_content else None ) assert self.json_list is None or isinstance( self.json_list, list ), f"{type(self.json_list)}: {json.dumps(self.json_list)}" @staticmethod def parse_body( *, body: Union[str, bytes, Dict[str, Any], List[Dict[str, Any]]], headers: Optional[Dict[str, Any]], ) -> Optional[List[Dict[str, Any]]]: # body can be either: # 0. None # 1. bytes (UTF-8 encoded) # 2. str (form encoded) # 3. str (json) # 3. dict # 4. list of string # 5. list of dict if body is None: return None if isinstance(body, bytes): return MockRequest.parse_body(body=body.decode("utf-8"), headers=headers) if isinstance(body, str): return MockRequest.parse_body(body=json.loads(body), headers=headers) if isinstance(body, dict): if ( body and "string" in body and headers and headers.get("Content-Type") == ["application/x-www-form-urlencoded"] ): return [MockRequest.convert_query_parameters_to_dict(body["string"])] else: return [body] if isinstance(body, list): my_list: List[Optional[List[Dict[str, Any]]]] = [ MockRequest.parse_body(body=c, headers=headers) for c in body if c is not None ] return [ item for sublist in my_list if sublist is not None for item in sublist if item is not None ] assert False, f"body is in unexpected type: {type(body)}" def __str__(self) -> str: return ( f"url: {self.path} \nquery params: {self.querystring_params} \n" f"json: {self.json_list}" ) @staticmethod def convert_query_parameters_to_dict(query: str) -> Dict[str, str]: params: Dict[str, List[str]] = parse_qs(query) return {k: v[0] for k, v in params.items()}
<reponame>ecoen66/imcsdk<gh_stars>10-100 """This module contains the general information for BiosVfPartialMirrorPercent ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class BiosVfPartialMirrorPercentConsts: VP_PARTIAL_MIRROR_PERCENT_PLATFORM_DEFAULT = "platform-default" class BiosVfPartialMirrorPercent(ManagedObject): """This is BiosVfPartialMirrorPercent class.""" consts = BiosVfPartialMirrorPercentConsts() naming_props = set([]) mo_meta = { "classic": MoMeta("BiosVfPartialMirrorPercent", "biosVfPartialMirrorPercent", "Partial-Mirror-Percent", VersionMeta.Version411c, "InputOutput", 0x1f, [], ["admin"], ['biosPlatformDefaults', 'biosSettings'], [], [None]), "modular": MoMeta("BiosVfPartialMirrorPercent", "biosVfPartialMirrorPercent", "Partial-Mirror-Percent", VersionMeta.Version411c, "InputOutput", 0x1f, [], ["admin"], ['biosPlatformDefaults', 'biosSettings'], [], [None]) } prop_meta = { "classic": { "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version411c, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version411c, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version411c, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []), "vp_partial_mirror_percent": MoPropertyMeta("vp_partial_mirror_percent", "vpPartialMirrorPercent", "string", VersionMeta.Version411c, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""(\d+(\.\d{1,2})?)""", ["platform-default"], ["0.00-50.00"]), "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version411c, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), }, "modular": { "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version411c, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version411c, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version411c, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []), "vp_partial_mirror_percent": MoPropertyMeta("vp_partial_mirror_percent", "vpPartialMirrorPercent", "string", VersionMeta.Version411c, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""(\d+(\.\d{1,2})?)""", ["platform-default"], ["0.00-50.00"]), "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version411c, MoPropertyMeta.INTERNAL, None, None, None, None, [], []), }, } prop_map = { "classic": { "dn": "dn", "rn": "rn", "status": "status", "vpPartialMirrorPercent": "vp_partial_mirror_percent", "childAction": "child_action", }, "modular": { "dn": "dn", "rn": "rn", "status": "status", "vpPartialMirrorPercent": "vp_partial_mirror_percent", "childAction": "child_action", }, } def __init__(self, parent_mo_or_dn, **kwargs): self._dirty_mask = 0 self.status = None self.vp_partial_mirror_percent = None self.child_action = None ManagedObject.__init__(self, "BiosVfPartialMirrorPercent", parent_mo_or_dn, **kwargs)
from typing import Union from app import db class Team(db.Model): __tablename__ = 'team' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) nickname = db.Column(db.String(100), nullable=True) ap_poll = db.relationship('APPoll', backref='team', lazy=True) ap_poll_ranking = db.relationship( 'APPollRanking', backref='team', lazy=True) first_downs = db.relationship('FirstDowns', backref='team', lazy=True) passing = db.relationship('Passing', backref='team', lazy=True) passing_plays = db.relationship('PassingPlays', backref='team', lazy=True) record = db.relationship('Record', backref='team', lazy=True) rpi = db.relationship('RPI', backref='team', lazy=True) rushing = db.relationship('Rushing', backref='team', lazy=True) rushing_plays = db.relationship('RushingPlays', backref='team', lazy=True) scoring = db.relationship('Scoring', backref='team', lazy=True) scrimmage_plays = db.relationship( 'ScrimmagePlays', backref='team', lazy=True) srs = db.relationship('SRS', backref='team', lazy=True) total = db.relationship('Total', backref='team', lazy=True) @classmethod def get_teams(cls, year: int, conference: str = None) -> list['Team']: """ Get FBS teams for the given year. If conference is provided, only get teams belonging to that conference. Args: year (int): Year to get teams conference (str): Conference name to filter teams Returns: list[Team]: All teams or teams filtered by conference """ teams = cls.query.all() if conference is not None: return [ team for team in teams if any( year in membership.years and conference == membership.conference.name for membership in team.conferences ) ] return [ team for team in teams if any(year in membership.years for membership in team.conferences) ] @classmethod def get_qualifying_teams(cls, start_year: int, end_year: int) -> list[str]: """ Get teams that qualify for records and stats for the given years. The criteria is that the teams must be in FBS for the end year and at least 50% of the years. Args: start_year (int): Start year end_year (int): End year Returns: list[str]: Qualifying teams """ min_years = (end_year - start_year + 1) / 2 teams = cls.get_teams(year=end_year) qualifying_teams = [] for team in teams: years = [ year for membership in team.conferences for year in membership.years ] active_years = [ year for year in years if year in range(start_year, end_year + 1) ] if len(active_years) >= min_years: qualifying_teams.append(team.name) return qualifying_teams def get_conference(self, year: int) -> Union[str, None]: """ Get the conference a team belongs to for the given year, if the team was in FBS for the given year. Args: year (int): Year to get the team's conference Returns: str: Conference name """ try: return next(( membership for membership in self.conferences if year in membership.years )).conference.name except StopIteration: return None def serialize(self, year: int) -> dict: return { 'id': self.id, 'name': self.name, 'conference': self.get_conference(year=year) }
<reponame>Huanzhuo/njica #! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 """ About: Core functions of a MEICA end host. Currently, source data (X matrix) is fragmented into UDP datagrams with a preamble (or header) for distributed MEICA. The choice of UDP instead of TCP is due to following reasons: - The TCP is designed based on end-to-end principle. For example, the sender would stop sending new segments and re-transmit the already sent segments when it does not receive the ACKs from the server. In our COIN scenario, the network nodes need to buffer source data for computing. If the source data can not be packed into the TCP segments of a window size. The network can not get the data to compute. - Flow granularity: TCP provides a steam of bytes. Data is dynamically distributed across different segments (controlled by the TCP stack). The data needed for COIN computing can be split up and difficult to reassemble. Therefore, UDP is used just for fast **PROTOTYPING**. Datagram-based transport protocols like SCTP could be a reasonable candidate for advanced transport features including re-transmission and congestion control. These sources are just used for **PoC**, the long term roadmap is to implement the ideas into SCTP protocol. """ import logging import math import pickle import struct import sys import typing from dataclasses import dataclass import utils import numpy as np sys.path.insert(0, "../") from pyfastbss_testbed import pyfbss_tb # This is used as the default payload size for each chunk. MEICA_IP_TOTAL_LEN: typing.Final[int] = 1400 # bytes # The number of chunks has a big impact on the queuing and transmission latency # for COIN applications. So the maximal chunk number should be limited. For # larger data, multiple messages should be used. MAX_CHUNK_NUM: typing.Final[int] = 4096 LEVELS = { "debug": logging.DEBUG, "info": logging.INFO, } def get_logger(level): log_level = LEVELS.get(level, None) if not log_level: raise RuntimeError("Unknown logging level!") logger = logging.getLogger("meica_host") handler = logging.StreamHandler() formatter = logging.Formatter("%(asctime)s %(levelname)-6s %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(log_level) return logger """ This customized header (in the UDP payload) is used since I have not found a de-facto standard way for COIN applications. Discussion of issues of transport layer protocol can be found [here](https://datatracker.ietf.org/rg/coinrg/about/). This is ONLY a draft version for a single stream, sufficiency and consistency are not considered yet. Service Header ONLY for the **DATAPLANE or data messages**. The control messages are NOT yet implemented. Service Header Fields: 0 1 2 3 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 +---------------+---------------+-------------+---------------+ | Message Type | Message Flags | Total Message Number (D) | +---------------+---------------+-------------+---------------+ | Message Number | Total Chunk Number | +---------------+---------------+-------------+---------------+ | Chunk Number | Chunk Length | +---------------+---------------+-------------+---------------+ ! Above fields could be merged into header(s) of message-oriented transport protocol such as [SCTP](https://en.wikipedia.org/wiki/Stream_Control_Transmission_Protocol). +-------------------------------------------------------------+ ! Following fields are related to the idea of distributed MEICA. +---------------+---------------+-------------+---------------+ | Data Chunk Number (D) | Iteration Number | +---------------+---------------+-------------+---------------+ # TODO: Replace (D)EPRECIATED fields with something useful. - Message Type: - 0: Unprocessed raw data (e.g. mixture matrix X). - 1: Intermediate result of the iteration (e.g. uW). TBD: - 2: Preprocessed data (e.g. uX generated from X). - Message Flags: Reserved. The description depends on the message type. - Message type 0: Unused. - Message type 1: - 0: The iteration was not completed. - 1: The iteration is completed. - Total Message Number (DEPRECIATED): Total number of messages to send. - Message Number: Sequence number of current message. - Total Chunk Number: Total number of chunks in the current message. - Chunk Number: Sequence number of the current chunk. - Chunk Length: A 16-bit unsigned value specifying the total length of the chunk in bytes (excludes any padding), that includes all fields of service header. - Data Chunk Number (DEPRECIATED): Number of data chunks. Now it equals total chunk num. - Iteration number: Current iteration number of the processing function (The 'mu' in MEICA code). Several fields are currently missing for addressing, security or advanced transport layer features including congestion control, retransmission. They will be explored in the future work. """ @dataclass class ServiceHeader(object): _PACK_STR = "!BBHHHHHHH" msg_type: int = 0 msg_flags: int = 0 total_msg_num: int = 0 msg_num: int = 0 total_chunk_num: int = 0 chunk_num: int = 0 chunk_len: int = 0 data_chunk_num: int = 0 iter_num: int = 0 length: int = struct.calcsize(_PACK_STR) def serialize(self) -> bytes: data = struct.pack( self._PACK_STR, self.msg_type, self.msg_flags, self.total_msg_num, self.msg_num, self.total_chunk_num, self.chunk_num, self.chunk_len, self.data_chunk_num, self.iter_num, ) return data @classmethod def parse(cls, data: bytes): ret = struct.unpack(cls._PACK_STR, data) return cls(*ret) class MEICAHost(object): """Base class for a MEICA-enabled end host.""" @staticmethod def serialize(x_array): return pickle.dumps(x_array) def fragment( self, x_array: np.ndarray, msg_type: int, total_msg_num: int, msg_num: int ) -> tuple: """Fragment X matrix into chunks. :param x_array: X matrix in np.ndarray format. :param msg_type: Type of the message. :param total_msg_num: Total message number. :param msg_num: Current message number. :return: A tuple of all chunks (header+payload) and the length of the serialized X matrix in bytes. """ x_bytes = self.serialize(x_array) full_chunks_num = math.floor(len(x_bytes) / MEICA_IP_TOTAL_LEN) total_chunk_num = full_chunks_num + 1 chunks = list() for c in range(full_chunks_num): hdr = ServiceHeader( msg_type=msg_type, msg_flags=0, total_msg_num=total_msg_num, msg_num=msg_num, total_chunk_num=total_chunk_num, chunk_num=c, chunk_len=MEICA_IP_TOTAL_LEN + ServiceHeader.length, data_chunk_num=total_chunk_num, iter_num=0, ) chunks.append( ( hdr.serialize(), x_bytes[c * MEICA_IP_TOTAL_LEN : (c + 1) * MEICA_IP_TOTAL_LEN], ) ) # The last chunk. hdr = ServiceHeader( msg_type=msg_type, msg_flags=0, total_msg_num=total_msg_num, msg_num=msg_num, total_chunk_num=total_chunk_num, chunk_num=full_chunks_num, chunk_len=len(x_bytes) - (MEICA_IP_TOTAL_LEN * full_chunks_num) + ServiceHeader.length, data_chunk_num=total_chunk_num, iter_num=0, ) chunks.append( (hdr.serialize(), x_bytes[full_chunks_num * MEICA_IP_TOTAL_LEN :]) ) return (chunks, len(x_bytes)) def check_chunks(self, chunks: list) -> bool: """Run sanity checks on chunks. :param chunks: A list of all chunks of a single message. """ prev_chunk_num = -1 for hdr_bytes, _ in chunks: hdr = ServiceHeader.parse(hdr_bytes) chunk_num = hdr.chunk_num if chunk_num != prev_chunk_num + 1: return False prev_chunk_num = chunk_num return True def defragment(self, chunks: list) -> np.ndarray: """Defragment chunks into array in np.ndarray format :param chunks: A list of chunks. :return: A tuple of data array and result array. """ array_bytes = b"".join(c[1] for c in chunks) array = pickle.loads(array_bytes) return array @utils.timer def run_tests(): print("* Run basic tests...") header = ServiceHeader( msg_type=0, msg_flags=0, total_msg_num=1, msg_num=0, total_chunk_num=100, chunk_num=0, chunk_len=1416, data_chunk_num=90, iter_num=0, ) assert header.length == 16 data = header.serialize() new_header = ServiceHeader.parse(data) new_data = new_header.serialize() assert data == new_data assert new_header.msg_type == 0 assert new_header.msg_flags == 0 assert new_header.total_msg_num == 1 assert new_header.msg_num == 0 assert new_header.total_chunk_num == 100 assert new_header.chunk_num == 0 assert new_header.chunk_len == 1416 assert new_header.data_chunk_num == 90 assert new_header.iter_num == 0 folder_address = "/in-network_bss/google_dataset/32000_wav_factory" _, _, X = pyfbss_tb.generate_matrix_S_A_X( folder_address, 3, 2, mixing_type="normal", max_min=(1, 0.01), mu_sigma=(0, 1), ) data_size = len(X.tobytes()) print(f"- Data size: {data_size}") host = MEICAHost() chunks, msg_len = host.fragment(X, msg_type=0, total_msg_num=1, msg_num=0) print(f"- Message size: {msg_len}") new_X = host.defragment(chunks) assert (X == new_X).all() print("* All tests passed!") if __name__ == "__main__": run_tests()
# - *- coding: utf- 8 - *- import xlwings from xlwings import Range from cargarExcel import cargarExcelDataframe import math import logginProcess import urllib.request from urllib.error import HTTPError, URLError import json import pandas as pd URL_SERVICIO_WEB = 'http://viscoandres.pythonanywhere.com/' #?tipo=' # URL_SERVICIO = 'http://127.0.0.1:5000/?tipo=' # URL_SERVICIO = 'http://0.0.0.0:5003/?tipo=' # URL_SERVICIO = 'http://localhost:5003/?tipo=' def calcularPorcentajeLote(dfCuantoPLanificar, dfTamanoLote): valorPorcentaje = dfCuantoPLanificar / dfTamanoLote return valorPorcentaje def flagRevisar(x): flag = 0 frac, entero = math.modf(x) if (entero >= 1.01) and ((frac >= 0.4) and (frac <= 0.89)): flag = 1 else: flag = 0 return flag def ValidarRevision(dfRevision): dfRevision.loc[:,'PorcentajeLoteAnterior'] = dfRevision.apply( lambda x: calcularPorcentajeLote( x['CuantoPlanificarNuevo'], x['TamanoLote'] ), axis=1) dfRevision.loc[:, 'FlagRevisar'] = dfRevision.apply( lambda x: flagRevisar( x['PorcentajeLoteAnterior'] ), axis=1) dfReturnFlag = dfRevision[dfRevision['FlagRevisar'] != 0] return dfReturnFlag def EjecutarMotorDeSugerenciasRevision(gElaboracion): gElaboracion = str(gElaboracion).strip('][').split(', ') if len(gElaboracion) > 0: gElaboracion = gElaboracion else: gElaboracion = gElaboracion[0] costoTotal = 0 # gElaboracionList = gElaboracion if isinstance(gElaboracion,int) else str(gElaboracion) # gElaboracionList = gElaboracion.split(",") logginProcess.logger.info("GElaboracion: {} Typo {} ".format( gElaboracion, type(gElaboracion)) ) dfCarga, fechaInicioPlan = cargarExcelDataframe(gElaboracion) columnas = dfCarga.columns.tolist() dfCargaJson = dfCarga.values.tolist() datosTotal = [] datosTotal.append(columnas) datosTotal.append(dfCargaJson) tipo = 'REVISION' jsondata = json.dumps(datosTotal) # req = urllib.request.Request('http://1192.168.3.11:5000') URL_SERVICIO = URL_SERVICIO_WEB + '?fechaInicio={}tipo={}'.format(fechaInicioPlan, tipo) req = urllib.request.Request(str(URL_SERVICIO)) req.add_header('Content-Type', 'application/json; charset=utf-8') jsondataBytes = jsondata.encode('utf-8') req.add_header('Content-Length', len(jsondataBytes)) response = urllib.request.urlopen(req, jsondataBytes) dfProcesoTemp = response.read() from io import StringIO s = str(dfProcesoTemp, 'utf-8') # data = StringIO(s) # # print(data.read()) # # return(str(data)) # dfProceso = pd.read_json(data) # logginProcess.logger.info("dfReturn: {} Typo {} ".format( # dfProceso, # type(dfProceso)) # ) # dfResult = EjecutarRevision(dfCarga) # dfResultMaximos = mainProcesoRevision(dfCarga) Range('A3').value = "Columna" Range('B3').value = "Suma Nulos" Range('A5').value = s Range('D3').value = "Grupo de Elaboracion" Range('D5').value = str(gElaboracion) Range('E1').value = s def EjecutarMotorDeSugerencias(gElaboracion): # exit() gElaboracion = str(gElaboracion).strip('][').split(', ') if len(gElaboracion) > 0: gElaboracion = gElaboracion else: gElaboracion = gElaboracion[0] logginProcess.logger.info("GElaboracion: {} Typo {} ".format( gElaboracion, type(gElaboracion)) ) dfCarga, fechaInicioPlan = cargarExcelDataframe(gElaboracion) tipo = 'SUGERENCIAS' URL_SERVICIO = URL_SERVICIO_WEB + '?fechaInicio={}&tipo={}'.format(fechaInicioPlan, tipo) logginProcess.logger.info("dfCarga: {} Typo {} ".format( dfCarga, type(dfCarga)) ) logginProcess.logger.info( "URLServicio: {} ".format(URL_SERVICIO) ) logginProcess.logger.info( "FechaInicioPlan: {} ".format(fechaInicioPlan) ) # import sys # sys.exit() ######## VERISION COMENTADA SERVICIOS columnas = dfCarga.columns.tolist() dfCargaJson = dfCarga.values.tolist() datosTotal = [] datosTotal.append(columnas) datosTotal.append(dfCargaJson) jsondata = json.dumps(datosTotal) # req = urllib.request.Request('http://127.0.0.1:5000') req = urllib.request.Request(str(URL_SERVICIO)) req.add_header('Content-Type', 'application/json; charset=utf-8') jsondataBytes = jsondata.encode('utf-8') req.add_header('Content-Length', len(jsondataBytes)) logginProcess.logger.info( "datos: {}".format( str(str(jsondataBytes) + " - " + str(req.data)) ) ) response = urllib.request.urlopen(req, jsondataBytes) dfProcesoTemp = response.read() logginProcess.logger.info( "resp: {}".format( str(dfProcesoTemp) ) ) from io import StringIO s = str(dfProcesoTemp, 'utf-8') data = StringIO(s) # print(data.read()) # return(str(data)) dfProceso = pd.read_json(data) logginProcess.logger.info("dfReturn: {} Typo {} ".format( dfProceso, type(dfProceso)) ) # dfProceso.reset_index(inplace=True) # dfProceso.index.rename('CodigoProductoExp', inplace=True) dfProceso.set_index('CodigoProductoExp', inplace=True) columnasDf = dfProceso.columns.tolist() columnasDf[6] = 'TamanoLoteTotal' dfProceso.columns = columnasDf dfProceso['PorcentajeLote'] = dfProceso.Dist / dfProceso.TamanoLoteTotal dfGroupFinal = dfProceso.groupby(dfProceso['GrupoElaboracion']) listaDFReturn = [] listaCompiladaDfReturn = [] ####### FIN VERSION SERVICIOS # logginProcess.logger.info("DFCarga : {}".format(str(dfCarga))) # dfProceso = mainProceso(dfCarga, 0) columnasDf = dfProceso.columns.to_list() columnasDf[6] = 'TamanoLoteTotal' dfProceso.columns = columnasDf dfProceso['PorcentajeLote'] = dfProceso.Dist / dfProceso.TamanoLoteTotal wbSug = xlwings.Book.caller() sheetSug = wbSug.sheets('Sugerencias') if isinstance(dfProceso, str): dfProceso = "" dfProceso = "Recomendamos verificar los tamaños de lote y las cantidades en el forecast, ya que la suma de todos los maximos tratados no llegan a un entero del minimo lote" Range('A4').value =dfProceso else: Range('A5').value = dfProceso if __name__ == '__main__': # # gElaboracion="[ANASTR]" gElaboracion="[PARACE2]" # # archivo = 'BP_190306_FAPASA_V01.xlsb' archivo = 'motor_ultimo (1).xlsb' # archivo = 'BP_190306_FAPASA_V01 - copia (2).xlsb' # # Expects the Excel file next to this source file, adjust accordingly. xlwings.Book(archivo).set_mock_caller() EjecutarMotorDeSugerencias(gElaboracion) # EjecutarMotorDeSugerenciasRevision(gElaboracion)
# -*- coding: utf-8 -*- """ @author: <NAME> @description: Module containing functions to calculate derivatives, averages, decompositions, vorticity. @contact: <EMAIL> """ # Imports import numpy as np import warnings # Functions def avg_z(u): """ Return the span-wise spatial average of a three-dimensional field. If the passed u is spanwise periodic use trapz()/(n-1). Otherwise mean(). :param u: The field to be spanwise-averaged. :return: Return the span-wise spatial average of a three-dimensional field. """ from scipy.integrate import trapz, simps if not len(u.shape)==3: warnings.warn("Field not 3D. Returning same array.") return u else: if np.array_equal(u[..., 0], u[..., -1]): # Periodic on last axis return trapz(u, axis=2)/(u.shape[2]-1) # return simps(u, axis=2)/(u.shape[2]-1) else: print('hi') return u.mean(axis=2) def avg_z2(u): """ Return the span-wise spatial average of a three-dimensional field using Simpson rule. If the passed u is spanwise periodic use trapz()/(n-1). Otherwise mean(). :param u: The field to be spanwise-averaged. :return: Return the span-wise spatial average of a three-dimensional field. """ from scipy.integrate import trapz, simps if not len(u.shape)==3: warnings.warn("Field not 3D. Returning same array.") return u else: sum = np.zeros(u.shape[:2]) for i in np.arange(u.shape[0]): print(i) for j in np.arange(u.shape[1]): for k in np.arange(4, u.shape[2]-4): sum[i,j] = sum[i,j] + u[i,j,k] sum[i,j] = sum[i,j] + 1/48*(17*u[i,j,0]+59*u[i,j,1]+43*u[i,j,2]+49*u[i,j,3]+ 49*u[i,j,-4]+43*u[i,j,-3]+59*u[i,j,-2]+17*u[i,j,-1]) sum[i,j] = sum[i,j]/(u.shape[2]-1) return sum def avg_z_1D(u): """ Return the span-wise spatial average of a three-dimensional field. If the passed u is spanwise periodic use trapz()/(n-1). Otherwise mean(). :param u: The field to be spanwise-averaged. :return: Return the span-wise spatial average of a three-dimensional field. """ from scipy.integrate import trapz, simps, quadrature from scipy.interpolate import Rbf,InterpolatedUnivariateSpline N = len(u) print(N) # Mean a1 = np.mean(u) # Rectangular rule a2 = 0 for i in range(0,len(u)-1): a2 = a2 + (u[i]+u[i+1])/2 a2 = a2/(N-1) # Trapz a3 = trapz(u)/(u.size-1) # Simps a4 = simps(u)/(u.size-1) # Simps2 a5 = 0 for i in range(4,len(u)-4): a5 = a5 + u[i] a5 = a5 + 1/48*(17*u[0]+59*u[1]+43*u[2]+49*u[3]+49*u[-4]+43*u[-3]+59*u[-2]+17*u[-1]) a5 = a5/(N-1) # Gaussian quad with rbf f = InterpolatedUnivariateSpline(np.arange(N),u) a6, err = quadrature(f, 0, N-1) a6 = a6/(N-1) return a1, a2, a3, a4, a5, a6 def make_periodicZ(u, **kwargs): # Methods t = True (add layer), t = False (substitue last layer with 1st layer) add = kwargs.get('add', True) if add: u_temp = np.zeros((u.shape[0], u.shape[1], u.shape[2] + 1)) u_temp[..., :-1], u_temp[..., -1] = u, u[..., 0] u = u_temp else: u[..., -1] = u[..., 0] return u def make_periodic(a, axis): b = np.expand_dims(np.take(a, indices=0, axis=axis), axis=axis) return np.concatenate((a, b), axis=axis) def decomp_z(u): """ :param u: field to be decomposed in z direction. :return: the average and the fluctuating parts of a three-dimensional field spatially averaged in the span-wise direction. """ if not len(u.shape)==3: raise ValueError("Fields must be three-dimensional") else: u_avg = avg_z(u) u_f = u-u_avg[:, :, None] return u_avg, u_f def ddx(u, x=None, acc=1): """ :param u: n-dimensional field. :return: the first- or second-acc derivative in the i direction of (n>=1 dimensional) field. """ if x is not None: if acc == 2: return np.gradient(u, x, axis=0, edge_order=2) else: raise ValueError('Only 2nd accuracy acc considered when x is included') else: if acc == 2: return np.gradient(u, axis=0, edge_order=2) elif acc == 1: a = np.diff(u, n=1, axis=0) if u.ndim == 1: return np.append(0, a) elif u.ndim == 2: return np.concatenate((np.zeros(u.shape[1])[None, :,], a), axis=0) elif u.ndim == 3: return np.concatenate((np.zeros(u.shape[1:])[None, :, :], a), axis=0) else: raise ValueError('Only arrays with dimensions <=3 considered.') else: raise ValueError('Only 1st or 2nd accuracy acc considered.') def ddy(u, y=None, acc=1): """ :param u: n-dimensional field. :return: the first-acc derivative in the j direction of (n>=2 dimensional) field. """ if y is not None: if acc == 2: return np.gradient(u, y, axis=1, edge_order=2) else: raise ValueError('Only 2nd accuracy acc considered when y is included') else: if acc == 2: return np.gradient(u, axis=1, edge_order=2) elif acc == 1: a = np.diff(u, n=1, axis=1) if u.ndim == 2: return np.concatenate((np.zeros(u.shape[0])[:, None], a), axis=1) elif u.ndim == 3: return np.concatenate((np.zeros((u.shape[0], u.shape[2]))[:, None, :], a), axis=1) else: raise ValueError('Only arrays with dimensions >=2 considered.') else: raise ValueError('Only 1st or 2nd accuracy acc considered.') def ddz(u, z=None, acc=1): """ :param u: n-dimensional field. :return: the first-acc derivative in the j direction of (n>=2 dimensional) field. """ if not np.array_equal(u[..., 0], u[..., -1]): # Field is not periodic if z is not None: if acc == 2: return np.gradient(u, z, axis=2, edge_order=2) else: raise ValueError('Only 2nd accuracy acc considered when z is included') else: if acc == 2: return np.gradient(u, axis=2, edge_order=2) elif acc == 1: a = np.diff(u, n=1, axis=2) if u.ndim == 3: return np.concatenate((np.zeros((u.shape[0], u.shape[1]))[:, :, None], a), axis=2) # Return same shape with zeros in k=0 else: raise ValueError('Only arrays with dimensions =3 considered.') else: raise ValueError('Only 1st or 2nd accuracy order considered.') else: # Field is periodic if z is not None: if acc == 2: return np.gradient(u, z, axis=2, edge_order=2) else: raise ValueError('Only 2nd accuracy acc considered when z is included') else: u_temp = np.zeros((u.shape[0], u.shape[1], u.shape[2] + 2)) u_temp[:, :, 1:-1], u_temp[:, :, 0], u_temp[:, :, -1] = u, u[:, :, -2], u[:, :, 1] del u if z is not None: if acc == 2: dudz = np.gradient(u_temp, z, axis=2, edge_order=2) return dudz[:, :, 1:-1] else: raise ValueError('Only 2nd accuracy acc considered when z is included') else: if acc == 1: dudz = np.diff(u_temp, n=1, axis=2) return dudz[..., :-1] elif acc == 2: dudz = np.gradient(u_temp, axis=2, edge_order=2) else: raise ValueError('Only 1st or 2nd accuracy order considered.') return dudz[:, :, 1:-1] # def ddz(u, z=None): # """ # :param u: n-dimensional field. # :return: the first-order derivative in the k direction of (n>=3 dimensional) field. # """ # if np.array_equal(u[..., 0], u[..., -1]): # Periodic on last axis # u_temp = np.zeros((u.shape[0], u.shape[1], u.shape[2]+2)) # u_temp[:, :, 1:-1], u_temp[:, :, 0], u_temp[:, :, -1] = u, u[:, :, -1], u[:, :, 0] # del u # if z is not None: # dudz = np.gradient(u_temp, z, axis=2, edge_order=2) # else: # dudz = np.gradient(u_temp, axis=2, edge_order=2) # del u_temp # return dudz[:, :, 1:-1] # else: # if z is not None: # return np.gradient(u, z, axis=2, edge_order=2) # else: # return np.gradient(u, axis=2, edge_order=2) def vortZ(u, v, **kwargs): """ :param u: x component of the velocity vector field. :param v: y component of the velocity vector field. :return: The z-vorticity of a two-dimensional velocity vector field """ # if not (len(u.shape)==2 and len(v.shape)==2): # raise ValueError("Fields must be two-dimensional") # else: x = kwargs.get('x', None) y = kwargs.get('y', None) return ddx(v, x)-ddy(u, y) def vort(u, v, w, **kwargs): """ :param u: x component of the velocity vector field. :param v: y component of the velocity vector field. :param w: z component of the velocity vector field. :return: the three components of the vorticity of a three-dimensional velocity vector field. """ if not (len(u.shape)==3 and len(v.shape)==3 and len(w.shape)==3): raise ValueError("Fields must be three-dimensional") else: x = kwargs.get('x', None) y = kwargs.get('y', None) z = kwargs.get('z', None) return ddy(w, y) - ddz(v, z), ddz(u, z) - ddx(w, x), ddx(v, x) - ddy(u, y) def grad(u): """ Return the gradient of a n-dimensinal array (scalar field) :param u: input scalar array :return: vector field array, gradient of u """ return np.array(np.gradient(u, edge_order=2)) def div(*args): dd = [ddx, ddy, ddz] res = np.zeros(args[0].shape) for i, a in enumerate(args): res += dd[i](a) return res def _transpose(Aij): return np.einsum('ij...->ji...', Aij) def _J3(u, v, w): """ Calculate the velocity gradient tensor :param u: Horizontal velocity component :param v: Vertical velocity component :param w: Spanwise velocity component :return: np.array (tensor) of the velocity gradient """ a11, a12, a13 = ddx(u), ddy(u), ddz(u) a21, a22, a23 = ddx(v), ddy(v), ddz(v) a31, a32, a33 = ddx(w), ddy(w), ddz(w) return np.array([[a11, a12, a13], [a21, a22, a23], [a31, a32, a33]]) def _J2(u, v): """ Calculate the velocity gradient tensor :param u: Horizontal velocity component :param v: Vertical velocity component :param w: Spanwise velocity component :return: np.array (tensor) of the velocity gradient """ a11, a12 = ddx(u), ddy(u) a21, a22 = ddx(v), ddy(v) return np.array([[a11, a12], [a21, a22]]) def _J(u_i): from itertools import product """ Calculate the velocity gradient tensor of a velocity vector field u_i :return: np.array (tensor) of the velocity gradient """ ndims = len(u_i) sh = u_i[0].shape indxs = [i for i in range(ndims)] dd = [ddx, ddy, ddz] Jij = np.empty((ndims, ndims) + sh) for i,j in product(indxs, indxs): Jij[i,j] = dd[j](u_i[i]) return Jij def _S(u_i): J = _J(u_i) return 0.5*(J + _transpose(J)) def Aij_mag(Aij): """ :param T: n-order tensor :return: Magnitude of T tensor """ # return np.linalg.norm(T, ord='fro', axis=(0,1))*np.sqrt(2) return np.sqrt(2*np.einsum('ijkl,ijkl->kl',Aij,Aij)) def S3(u, v, w): J = _J3(u, v, w) return 0.5*(J + np.transpose(J, (1,0,2,3,4))) def R3(u, v, w): J = _J3(u, v, w) return 0.5*(J - np.transpose(J, (1,0,2,3,4))) def Q3(u, v, w): J = _J3(u, v, w) S = 0.5*(J + np.transpose(J, (1,0,2,3,4))) R = 0.5*(J - np.transpose(J, (1,0,2,3,4))) S_mag = np.linalg.norm(S, ord='fro', axis=(0,1)) # Falta sqrt(2) S_mag2 = np.sqrt(np.trace(np.dot(S, S.T))) # Falta sqrt(2) S_mag3 = np.sqrt(np.tensordot(S,S,axes=2)) # Falta sqrt(2) print(np.sum(S_mag)) print(np.sum(S_mag2)) R_mag = np.linalg.norm(R, ord='fro', axis=(0,1)) print(R_mag.shape) Q = 0.5*(R_mag**2-S_mag**2) # Q = np.clip(Q, 0, None) return Q def crop(u, window, **kwargs): scaling = kwargs.get('scaling', 1) shift = kwargs.get('shift', (0, 0)) N, M = u.shape[0], u.shape[1] # Create uniform grid if 'grid' in kwargs: grid = kwargs['grid'] x, y = grid[0] / scaling + shift[0], grid[1] / scaling + shift[1] elif 'x' in kwargs and 'y' in kwargs: x = kwargs.get('x') / scaling + shift[0] y = kwargs.get('y') / scaling + shift[1] x, y = np.meshgrid(x, y) elif 'x_lims' in kwargs and 'y_lims' in kwargs: xlims = kwargs.get('x_lims') ylims = kwargs.get('y_lims') x, y = np.linspace(xlims[0] / scaling, xlims[1] / scaling, N), np.linspace(ylims[0] / scaling, ylims[1] / scaling, M) x, y = x + shift[0], y + shift[1] x, y = np.meshgrid(x, y) else: xmin, xmax = 0, N - 1 ymin, ymax = -M / 2, M / 2 - 1 x, y = np.linspace(xmin / scaling, xmax / scaling, N), np.linspace(ymin / scaling, ymax / scaling, M) x, y = x + shift[0], y + shift[1] x, y = np.meshgrid(x, y) x_args = np.where(np.logical_and(np.any(x > window[0][0], axis=0), np.any(x < window[0][1], axis=0)))[0] y_args = np.where(np.logical_and(np.any(y > window[1][0], axis=1), np.any(y < window[1][1], axis=1)))[0] return u[x_args][:, y_args] def map_cyl(grid2D, r, eps): x, y = grid2D[0], grid2D[1] r_grid = np.sqrt(x**2+y**2) indices = np.where((r_grid>=r*(1+0.5*eps)) & (r_grid<=r*(1+1.5*eps))) r_grid = np.zeros(x.shape) r_grid[indices] = 1 return r_grid, indices def map_normal(grid2D, r, r_max, angle): x, y = grid2D[0], grid2D[1] r_grid = np.sqrt(x**2+y**2) atan_grid = np.arctan2(y, x)*180/np.pi angle_eps = 0.5 # indices = np.where((r_grid<=r_max) & (np.abs(atan_grid-angle)<angle_eps)) indices = np.where((r_grid<=r_max) & close(atan_grid, angle, angle_eps)) result = np.zeros(x.shape) result[indices] = 1 return result, indices def separation_points(q, alphas, eps=0.0005): """ :param q: 2D scalar field (quantity) we analyse :param l: list of tuples. Each tuples is: ((i,j), alpha)) :return: upper and lower separation points """ alpha_u, alpha_l = None, None # find upper separation point for (idx, alpha) in sorted(alphas, key=lambda tup: tup[1])[80:]: if -eps<=q[idx] and q[idx]<=eps: alpha_u = alpha break # find lower separation point for (idx, alpha) in sorted(alphas, key=lambda tup: tup[1], reverse=True)[80:]: if -eps<=q[idx] and q[idx]<=eps: alpha_l = alpha break return alpha_u, alpha_l-360 def separation_points2(q, alphas, eps=0.1): """ :param q: 2D scalar field (quantity) we analyse :param l: list of tuples. Each tuples is: ((i,j), alpha)) :return: upper and lower separation points """ alpha_u, alpha_l = None, None l_upper = sorted(alphas, key=lambda tup: tup[1])[100:] l_lower = sorted(alphas, key=lambda tup: tup[1], reverse=True)[100:] # find upper separation point for i, (idx, alpha) in enumerate(l_upper): if q[idx]<eps: alpha_u = alpha break # find lower separation point for i, (idx, alpha) in enumerate(l_lower): if q[idx]<eps: alpha_l = alpha break return alpha_u, alpha_l-360 def wake_width_eps(a, eps=0.0025, cyl_pos=1.5, L=90): ww = np.zeros(a.shape) ww[np.abs(a) > eps] = 1 ww[:int(cyl_pos * L)] = 0 return ww def wake_width_length(a, eps=0.0025, cyl_pos=1.5, L=90): ww = np.zeros(a.shape) for i in range(a.shape[0]): col = np.where(np.abs(a[i,:])>eps) if col[0].size >= 2: min,max = np.min(col[0]),np.max(col[0]) ww[i, min:max+1] = 1 elif col[0].size == 1: min=col[0][0] ww[i, min:min+1] = 1 else: continue ww[:int(cyl_pos * L)] = 0 return ww def corr(a,b): am = np.mean(a) bm = np.mean(b) ac = a - am # a centered bc = b - bm # b centered cov_ab = np.mean(ac * bc) cov_aa = np.mean(ac ** 2) cov_bb = np.mean(bc ** 2) return cov_ab / np.sqrt(cov_aa * cov_bb) def close(a, b, eps): return np.abs(a - b) < eps
#importing necessary packages import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import PolynomialFeatures from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression from sklearn.svm import SVR from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor #importing datasets # slr --> simple linear regression # mlr --> Multiple linear regression # pr --> polynomial regression data_slr = pd.read_csv("C://Users//manis//Desktop//Projects//Machine Learning A-Z (Codes and Datasets)//Regression//Salary_Data_slr.csv") data_mlr = pd.read_csv("C://Users//manis//Desktop//Projects//Machine Learning A-Z (Codes and Datasets)//Regression//50_Startups_mlr.csv") data_pr = pd.read_csv("C://Users//manis//Desktop//Projects//Machine Learning A-Z (Codes and Datasets)//Regression//Position_Salaries_pr.csv") data_sv = pd.read_csv("C://Users//manis//Desktop//Projects//Machine Learning A-Z (Codes and Datasets)//Regression//Position_Salaries_pr.csv") data_dt = pd.read_csv("C://Users//manis//Desktop//Projects//Machine Learning A-Z (Codes and Datasets)//Regression//Position_Salaries_pr.csv") data_rf = pd.read_csv("C://Users//manis//Desktop//Projects//Machine Learning A-Z (Codes and Datasets)//Regression//Position_Salaries_pr.csv") #----------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------- """ SIMPLE-LINEAR-REGRESSION """ print("--Starting Simple linear regression--") data_slr.head(2) #checking first 2 instances data_slr.count() #counting number of instances for each feature data_slr.plot.line(x = "YearsExperience" , y = "Salary") #visualizing features using a line plot data_slr.plot.scatter(x = "YearsExperience" , y = "Salary" , c= "red") #visualizing features using a scatter plot """ splitting dataset into dependent and independent variables """ X = data_slr.iloc[:, :-1].values #indpendent variable y = data_slr.iloc[:, -1].values #dependent variable """ Making a test-train splits """ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) """ Imporitng a linear regressor from Scikit learn and fitting it to our training data """ regressor = LinearRegression() regressor.fit(X_train, y_train) """ Predicting on our test dataset """ y_pred = regressor.predict(X_test) """ Visualizing our train and test sets """ plt.scatter(X_train, y_train, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Training set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() plt.scatter(X_test, y_test, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Test set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show() #----------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------- """ Multiple linear regression : we are supposed to implement a multiple linear regressor on a dataset related to 50 """ print("--Starting Multiple linear regression--") data_mlr.head(2) #checking first 2 instances print(data_mlr.corr()) #cheking if there exists any correlation between features data_mlr["State"].unique() #checking how many unique values we have for his categorical variable X = data_mlr.iloc[:, :-1].values y = data_mlr.iloc[:, -1].values print(X) ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [3])], remainder='passthrough') X = np.array(ct.fit_transform(X)) print(X) #multiple linear regression class automatically avoids the dummy variable trap, hence not removing # columns in order to dodge this. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) regressor = LinearRegression() regressor.fit(X_train, y_train) y_pred = regressor.predict(X_test) np.set_printoptions(precision=2) print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)) #----------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------- """ Polynomial Regression. consists info of a position and its respective salary """ print("--Starting polynomial linear regression--") data_pr.head(2) X = data_pr.iloc[:, 1:-1].values y = data_pr.iloc[:, -1].values lin_reg = LinearRegression() lin_reg.fit(X, y) poly_reg = PolynomialFeatures(degree = 4) X_poly = poly_reg.fit_transform(X) lin_reg_2 = LinearRegression() lin_reg_2.fit(X_poly, y) plt.scatter(X, y, color = 'red') plt.plot(X, lin_reg.predict(X), color = 'blue') plt.title('Truth or Bluff (Linear Regression)') plt.xlabel('Position Level') plt.ylabel('Salary') plt.show() plt.scatter(X, y, color = 'red') plt.plot(X, lin_reg_2.predict(poly_reg.fit_transform(X)), color = 'blue') plt.title('Truth or Bluff (Polynomial Regression)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() X_grid = np.arange(min(X), max(X), 0.1) X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, y, color = 'red') plt.plot(X_grid, lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue') plt.title('Truth or Bluff (Polynomial Regression)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() lin_reg.predict([[6.5]]) lin_reg_2.predict(poly_reg.fit_transform([[6.5]])) #----------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------- """ Support-Vector-Regression """ print("--Starting suuport vector regression --") X = data_sv.iloc[:, 1:-1].values y = data_sv.iloc[:, -1].values sc_X = StandardScaler() sc_y = StandardScaler() X = sc_X.fit_transform(X) y = sc_y.fit_transform(y) regressor = SVR(kernel = 'rbf') regressor.fit(X, y) sc_y.inverse_transform(regressor.predict(sc_X.transform([[6.5]]))) plt.scatter(sc_X.inverse_transform(X), sc_y.inverse_transform(y), color = 'red') plt.plot(sc_X.inverse_transform(X), sc_y.inverse_transform(regressor.predict(X)), color = 'blue') plt.title('Truth or Bluff (SVR)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() X_grid = np.arange(min(sc_X.inverse_transform(X)), max(sc_X.inverse_transform(X)), 0.1) X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(sc_X.inverse_transform(X), sc_y.inverse_transform(y), color = 'red') plt.plot(X_grid, sc_y.inverse_transform(regressor.predict(sc_X.transform(X_grid))), color = 'blue') plt.title('Truth or Bluff (SVR)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() #----------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------- """ Decision-Tree-Regression """ print("--Starting decision tree regression--") X = data_dt.iloc[:, 1:-1].values y = data_dt.iloc[:, -1].values regressor = DecisionTreeRegressor(random_state = 0) regressor.fit(X, y) regressor.predict([[6.5]]) X_grid = np.arange(min(X), max(X), 0.01) X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, y, color = 'red') plt.plot(X_grid, regressor.predict(X_grid), color = 'blue') plt.title('Truth or Bluff (Decision Tree Regression)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() #----------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------- """ Random-forest-Regression """ print("--Starting random forest regression--") X = data_rf.iloc[:, 1:-1].values y = data_rf.iloc[:, -1].values regressor = RandomForestRegressor(n_estimators = 10, random_state = 0) regressor.fit(X, y) regressor.predict([[6.5]]) X_grid = np.arange(min(X), max(X), 0.01) X_grid = X_grid.reshape((len(X_grid), 1)) plt.scatter(X, y, color = 'red') plt.plot(X_grid, regressor.predict(X_grid), color = 'blue') plt.title('Truth or Bluff (Random Forest Regression)') plt.xlabel('Position level') plt.ylabel('Salary') plt.show()
<reponame>HawkEleven/Python-RESTful-API #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-07-06 14:30:10 # @Author : Eleven (<EMAIL>) # @Link : https://github.com/HawkEleven # @Version : 1.0 import pymysql from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql import func import json from newBaseModel import NewBaseModel import functools class MySQLCommand(object): # 类的初始化 def __init__(self): self.host = 'localhost' self.port = 3306 # 端口号 self.user = 'root' # 用户名 self.password = "<PASSWORD>" # 密码 self.db = "home" # 库 self.table = "home_list" # 表 self.insert_id = 0; # 链接数据库 def connectMysql(self): try: self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.password, db=self.db, charset='utf8', cursorclass = pymysql.cursors.DictCursor) self.cursor = self.conn.cursor() except: print('connect mysql error.') def insertData(self, my_dict): table = self.table sqlExit = "SELECT url FROM home_list WHERE url = '%s'" % (my_dict['url']) try: res = self.cursor.execute(sqlExit) if res: print('数据已存在', res) return 0 cols = ', '.join(my_dict.keys()) values = '","'.join(map(str, my_dict.values())) sql = "INSERT INTO home_list (%s) VALUES (%s)" % (cols, '"' + values + '"') try: result = self.cursor.execute(sql) self.conn.commit() if result: self.insert_id += 1 print('插入成功 id = ', self.insert_id) except pymysql.Error as e: # 发生错误时回滚 self.conn.rollback() # 主键唯一,无法插入 if "KEY 'PRIMARY'" in e.args[1]: print("数据已存在,未插入数据") else: print("插入数据失败,原因 %d: %s" % (e.args[0], e.args[1])) self.insert_id = self.getLastId() except pymysql.Error as e: print("数据库错误,原因%d: %s" % (e.args[0], e.args[1])) self.insert_id = self.getLastId() finally: return self.insert_id def selectAllData(self): sql = "SELECT * FROM home_list ORDER BY id ASC" res = self.cursor.execute(sql) if res: return self.cursor.fetchall() def selectDataById(self, id): sql = "SELECT * FROM home_list WHERE id = '%s'" % (id) res = self.cursor.execute(sql) if res: print('数据存在') return self.cursor.fetchall() def getLastId(self): sql = "SELECT max(id) FROM " + self.table try: self.cursor.execute(sql) row = self.cursor.fetchone() # 获取查询到的第一条数据 if list(row.values())[0]: return list(row.values())[0] # 返回最后一条数据的id else: return 0 # 如果表格为空就返回0 except Exception as e: print(sql + ' execute failed.') return 0 def closeMysql(self): self.cursor.close() self.conn.close() # 创建数据库操作类的实例 # ORM Base = declarative_base() class NewModel(Base): __tablename__ = 'home_list' id = Column(String(20), primary_key=True) title = Column(String(20)) img_path = Column(String(20)) url = Column(String(20)) class SqlalchemyCommand(object): # 初始化数据库连接: def connectMysql(self): engine = create_engine('mysql+mysqlconnector://root:123@localhost:3306/home') # 创建DBSession类型: DBSession = sessionmaker(bind=engine) # 创建session对象: self.session = DBSession() self.insert_id = 0 def insertData(self, my_dict): try: newBaseModel = self.session.query(NewModel).filter(NewModel.url==my_dict['url']).one() print('数据已存在', newBaseModel) self.insert_id = self.getLastId() except: self.session.rollback() newBaseModel = self._dictToObj(my_dict) newModel = NewModel(id=newBaseModel.id, title=newBaseModel.title, img_path=newBaseModel.img_path, url=newBaseModel.url) try: self.session.add(newModel) self.session.commit() self.insert_id += 1 print('插入成功 id = ', self.insert_id) except Exception as e: print("插入数据失败,原因: %s" % e) self.insert_id = getLastId() finally: return self.insert_id def selectAllData(self): results = self.session.query(NewModel).all() res = [] for newBaseModel in results: print(newBaseModel.id) res.append(self._objToDict(newBaseModel)[0]) return res def selectDataById(self, id): # order_by(NewModel.id.asc())排序函数 try: newBaseModel = self.session.query(NewModel).filter(NewModel.id==id).one() return self._objToDict(newBaseModel) except: return None def getLastId(self): maxId = self.session.query(func.max(NewModel.id)).scalar(); if maxId: return maxId else: return 0 def closeMysql(self): self.session.close() def _objToDict(self, newModel): model = NewBaseModel(newModel.id, newModel.title, newModel.img_path, newModel.url) json_str = json.dumps(model, default=lambda obj: obj.__dict__) # print(json_str) # print(json.loads(json_str)) return [json.loads(json_str)] def _dictToObj(self, my_dict): json_str = json.dumps(my_dict) model = json.loads(json_str, object_hook=lambda x: NewBaseModel(x['id'], x['title'], x['img_path'], x['url'])) return model def createdatabase(): db = pymysql.connect(host='localhost', port=3306, user='root', password='<PASSWORD>') cursor = db.cursor() cursor.execute('SELECT VERSION()') data = cursor.fetchone() print('Database version:', data) cursor.execute("CREATE DATABASE IF NOT EXISTS home DEFAULT CHARACTER SET utf8") db.close() def createtable(): db = pymysql.connect(host='localhost', user='root', password='<PASSWORD>', port=3306, db='home') cursor = db.cursor() sql = 'CREATE TABLE IF NOT EXISTS home_list (id int NOT NULL, title VARCHAR(255) NOT NULL, img_path VARCHAR(255) NOT NULL, url VARCHAR(255) NOT NULL, PRIMARY KEY (id))' cursor.execute(sql) db.close() createdatabase() createtable()
<reponame>pramulkant/https-github.com-android-art-intel-marshmallow #!/usr/bin/python import os, sys, csv def AppendData(filename, data): data[filename] = {} with open(filename, 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='"') for i,row in enumerate(spamreader): data[filename][i] = {} for j,cell in enumerate(row): data[filename][i][j] = cell def is_number(s): try: float(s) return True except ValueError: return False def ComputeData(data, max_data, sum_data): for filename in data: for i in data[filename]: if len(max_data) < len(data[filename]): max_data.append([]) if len(sum_data) < len(data[filename]): sum_data.append([]) for j in data[filename][i]: # append new 0s if any if len(max_data[i]) < len(data[filename][i]): max_data[i].append(0) if len(sum_data[i]) < len(data[filename][i]): sum_data[i].append(0) # if cell is a number, then we can update our numbers. if is_number(data[filename][i][j]): if len(max_data[i]) < len(data[filename][i]): max_data[i].append(0) if len(sum_data[i]) < len(data[filename][i]): sum_data[i].append(0) if i != 0: f_data = float(data[filename][i][j]) if is_number(max_data[i][j]): f_max = float(max_data[i][j]) # compute max data if f_max < f_data: max_data[i][j] = f_data # compute sum data if is_number(sum_data[i][j]): sum_data[i][j] += f_data else: if i == 0 and j == 0: max_data[i][j] = "" sum_data[i][j] = "" else: max_data[i][j] = data[filename][i][j] sum_data[i][j] = data[filename][i][j] def DumpData(output_name, data, max_data, sum_data): if len(data) == 0: return with open(output_name, 'wb') as myfile: wr = csv.writer(myfile, delimiter=',', quoting=csv.QUOTE_ALL) wr.writerow(['Max']) for row in max_data: wr.writerow(row) wr.writerow(['Sum']) for row in sum_data: wr.writerow(row) if len(sys.argv) != 2: print "Usage: ./gathering.py [folder-name]" sys.exit(0) data = {} folder_name = sys.argv[1] nb_files = 0 print "Collecting data from folder " + folder_name + "..." for filename in os.listdir(folder_name): if filename.endswith(".hash.csv"): filename = folder_name + "/" + filename AppendData(filename, data) nb_files = nb_files + 1 if nb_files == 0: print "There is no CSV file in folder " + folder_name else: max_data = [] sum_data = [] print "Computing data..." ComputeData(data, max_data, sum_data) print "Dumping computed data..." output_filename = "summary.csv" DumpData(output_filename, data, max_data, sum_data) print "Summarized " + str(nb_files) + " files in file " + output_filename
<reponame>maccesch/django-moderation from __future__ import unicode_literals from django.test.testcases import TestCase from django import VERSION from django.db import models from django.contrib.auth.models import User, Group if VERSION >= (1, 4): from django.test.utils import override_settings from tests.models import UserProfile,\ SuperUserProfile, ModelWithSlugField2, ProxyProfile from moderation.models import ModeratedObject, MODERATION_STATUS_APPROVED,\ MODERATION_STATUS_PENDING, MODERATION_STATUS_REJECTED,\ MODERATION_READY_STATE, MODERATION_DRAFT_STATE from moderation.fields import SerializedObjectField from moderation.register import ModerationManager, RegistrationError from moderation.managers import ModerationObjectsManager from moderation.moderator import GenericModerator from moderation.helpers import automoderate from tests.utils import setup_moderation, teardown_moderation from tests.utils import unittest class SerializationTestCase(TestCase): fixtures = ['test_users.json', 'test_moderation.json'] def setUp(self): self.user = User.objects.get(username='moderator') self.profile = UserProfile.objects.get(user__username='moderator') def test_serialize_of_object(self): """Test if object is properly serialized to json""" json_field = SerializedObjectField() serialized_str = json_field._serialize(self.profile) self.assertIn('"pk": 1', serialized_str) self.assertIn('"model": "tests.userprofile"', serialized_str) self.assertIn('"fields": {', serialized_str) self.assertIn('"url": "http://www.google.com"', serialized_str) self.assertIn('"user": 1', serialized_str) self.assertIn('"description": "Old description"', serialized_str) def test_serialize_with_inheritance(self): """Test if object is properly serialized to json""" profile = SuperUserProfile(description='Profile for new super user', url='http://www.test.com', user=User.objects.get(username='user1'), super_power='invisibility') profile.save() json_field = SerializedObjectField() serialized_str = json_field._serialize(profile) self.assertIn('"pk": 2', serialized_str) self.assertIn('"model": "tests.superuserprofile"', serialized_str) self.assertIn('"fields": {"super_power": "invisibility"}', serialized_str) self.assertIn('"pk": 2', serialized_str) self.assertIn('"model": "tests.userprofile"', serialized_str) self.assertIn('"url": "http://www.test.com"', serialized_str) self.assertIn('"user": 2', serialized_str) self.assertIn('"description": "Profile for new super user"', serialized_str) self.assertIn('"fields": {', serialized_str) def test_deserialize(self): value = '[{"pk": 1, "model": "tests.userprofile", "fields": '\ '{"url": "http://www.google.com", "user": 1, '\ '"description": "Profile description"}}]' json_field = SerializedObjectField() object = json_field._deserialize(value) self.assertEqual(repr(object), '<UserProfile: moderator - http://www.google.com>') self.assertTrue(isinstance(object, UserProfile)) def test_deserialize_with_inheritance(self): value = '[{"pk": 2, "model": "tests.superuserprofile",'\ ' "fields": {"super_power": "invisibility"}}, '\ '{"pk": 2, "model": "tests.userprofile", "fields":'\ ' {"url": "http://www.test.com", "user": 2,'\ ' "description": "Profile for new super user"}}]' json_field = SerializedObjectField() object = json_field._deserialize(value) self.assertTrue(isinstance(object, SuperUserProfile)) self.assertEqual( repr(object), '<SuperUserProfile: user1 - http://www.test.com - invisibility>') def test_deserialzed_object(self): moderated_object = ModeratedObject(content_object=self.profile) self.profile.description = 'New description' moderated_object.changed_object = self.profile moderated_object.save() pk = moderated_object.pk moderated_object = ModeratedObject.objects.get(pk=pk) self.assertEqual(moderated_object.changed_object.description, 'New description') self.assertEqual(moderated_object.content_object.description, 'Old description') def test_change_of_deserialzed_object(self): self.profile.description = 'New description' moderated_object = ModeratedObject(content_object=self.profile) moderated_object.save() pk = moderated_object.pk self.profile.description = 'New changed description' moderated_object.changed_object = self.profile.description moderated_object.save() moderated_object = ModeratedObject.objects.get(pk=pk) self.assertEqual(moderated_object.changed_object.description, 'New changed description') @unittest.skipIf(VERSION[:2] < (1, 4), "Proxy models require 1.4") def test_serialize_proxy_model(self): "Handle proxy models in the serialization." profile = ProxyProfile(description="I'm a proxy.", url="http://example.com", user=User.objects.get(username='user1')) profile.save() json_field = SerializedObjectField() serialized_str = json_field._serialize(profile) self.assertIn('"pk": 2', serialized_str) self.assertIn('"model": "tests.proxyprofile"', serialized_str) self.assertIn('"url": "http://example.com"', serialized_str) self.assertIn('"user": 2', serialized_str) self.assertIn('"description": "I\'m a proxy."', serialized_str) self.assertIn('"fields": {', serialized_str) @unittest.skipIf(VERSION[:2] < (1, 4), "Proxy models require 1.4") def test_deserialize_proxy_model(self): "Correctly restore a proxy model." value = '[{"pk": 2, "model": "tests.proxyprofile", "fields": '\ '{"url": "http://example.com", "user": 2, '\ '"description": "I\'m a proxy."}}]' json_field = SerializedObjectField() profile = json_field._deserialize(value) self.assertTrue(isinstance(profile, ProxyProfile)) self.assertEqual(profile.url, "http://example.com") self.assertEqual(profile.description, "I\'m a proxy.") self.assertEqual(profile.user_id, 2) class ModerateTestCase(TestCase): fixtures = ['test_users.json', 'test_moderation.json'] def setUp(self): self.user = User.objects.get(username='moderator') self.profile = UserProfile.objects.get(user__username='moderator') self.moderation = setup_moderation([UserProfile]) def tearDown(self): teardown_moderation() def test_objects_with_no_moderated_object_are_visible(self): """ Simulate conditions where moderation is added to a model which already has existing objects, which should remain visible. """ ModeratedObject.objects.all().delete() self.assertEqual( [self.profile], list(self.profile.__class__.objects.all()), "Objects with no attached ModeratedObject should be visible " "by default.") def test_approval_status_pending(self): """test if before object approval status is pending""" self.profile.description = 'New description' self.profile.save() self.assertEqual(self.profile.moderated_object.moderation_status, MODERATION_STATUS_PENDING) def test_moderate(self): self.profile.description = 'New description' self.profile.save() self.profile.moderated_object._moderate(MODERATION_STATUS_APPROVED, self.user, "Reason") self.assertEqual(self.profile.moderated_object.moderation_status, MODERATION_STATUS_APPROVED) self.assertEqual(self.profile.moderated_object.moderated_by, self.user) self.assertEqual(self.profile.moderated_object.moderation_reason, "Reason") def test_multiple_moderations_throws_exception_by_default(self): self.profile.description = 'New description' self.profile.save() moderated_object = ModeratedObject.objects.create( content_object=self.profile) moderated_object.approve(moderated_by=self.user) with self.assertRaises(ModerationObjectsManager.MultipleModerations): self.profile.__class__.objects.get(id=self.profile.id) def test_approve_new_moderated_object(self): """ When a newly created object is approved, it should become visible in standard querysets. """ profile = self.profile.__class__(description='Profile for new user', url='http://www.test.com', user=self.user) profile.save() self.assertEqual( MODERATION_DRAFT_STATE, profile.moderated_object.moderation_state, "Before first approval, the profile should be in draft state, " "to hide it from querysets.") profile.moderated_object.approve(self.user) self.assertEqual( MODERATION_READY_STATE, profile.moderated_object.moderation_state, "After first approval, the profile should be in ready state, " "to show it in querysets.") user_profile = self.profile.__class__.objects.get( url='http://www.test.com') self.assertEqual(user_profile.description, 'Profile for new user') self.assertEqual( [profile], list(self.profile.__class__.objects.filter(pk=profile.pk)), "New profile objects should be visible after being accepted") def test_reject_new_moderated_object(self): """ When a newly created object is rejected, it should remain invisible in standard querysets. """ profile = self.profile.__class__(description='Profile for new user', url='http://www.test.com', user=self.user) profile.save() self.assertEqual( MODERATION_DRAFT_STATE, profile.moderated_object.moderation_state, "Before first approval, the profile should be in draft state, " "to hide it from querysets.") profile.moderated_object.reject(self.user) self.assertEqual( MODERATION_DRAFT_STATE, profile.moderated_object.moderation_state, "After rejection, the profile should still be in draft state, " "to hide it from querysets.") user_profile = self.profile.__class__.unmoderated_objects.get( url='http://www.test.com') self.assertEqual(user_profile.description, 'Profile for new user') self.assertEqual( [], list(self.profile.__class__.objects.filter(pk=profile.pk)), "New profile objects should be hidden after being rejected") def test_approve_modified_moderated_object(self): """ When a previously approved object is updated and approved, it should remain visible in standard querysets, with the new data saved in the object. """ self.profile.description = 'New description' self.profile.save() self.profile.moderated_object.approve(self.user) self.assertEqual( MODERATION_READY_STATE, self.profile.moderated_object.moderation_state, "After first approval, the profile should be in ready state, " "to show it in querysets.") user_profile = self.profile.__class__.objects.get( id=self.profile.id) self.assertEqual(user_profile.description, 'New description') self.assertEqual( [self.profile], list(self.profile.__class__.objects.filter(pk=self.profile.pk)), "Modified profile objects should be visible after being accepted") def test_reject_modified_moderated_object(self): """ When a previously approved object is updated and rejected, it should remain visible in standard querysets, but with the old (previously approved) data saved in the object. """ ModeratedObject.objects.create(content_object=self.profile) self.profile.moderated_object.approve(self.user) self.profile.description = 'New description' self.profile.save() self.profile.moderated_object.reject(self.user) self.assertEqual( MODERATION_READY_STATE, self.profile.moderated_object.moderation_state, "After rejection, the profile should still be in ready state, " "to show it in querysets, but with the old data.") user_profile = self.profile.__class__.objects.get(id=self.profile.id) self.assertEqual(user_profile.description, "Old description") self.assertEqual(self.profile.moderated_object.moderation_status, MODERATION_STATUS_REJECTED) self.assertEqual( [self.profile], list(self.profile.__class__.objects.filter(pk=self.profile.pk)), "Modified profile objects should still be visible after being " "rejected, but with the old data") # Test making another change that's rejected, and that the data # saved in the object is still the previously approved data. self.profile.description = 'Another bad description' self.profile.save() self.profile.moderated_object.reject(self.user) user_profile = self.profile.__class__.objects.get(id=self.profile.id) self.assertEqual(user_profile.description, "Old description") self.assertEqual(self.profile.moderated_object.moderation_status, MODERATION_STATUS_REJECTED) self.assertEqual( [self.profile], list(self.profile.__class__.objects.filter(pk=self.profile.pk)), "Modified profile objects should still be visible after being " "rejected, but with the old data") def test_has_object_been_changed_should_be_true(self): self.profile.description = 'Old description' moderated_object = ModeratedObject(content_object=self.profile) moderated_object.save() moderated_object.approve(moderated_by=self.user) user_profile = self.profile.__class__.objects.get(id=self.profile.id) self.profile.description = 'New description' moderated_object = ModeratedObject(content_object=self.profile) moderated_object.save() value = moderated_object.has_object_been_changed(user_profile) self.assertEqual(value, True) def test_has_object_been_changed_should_be_false(self): moderated_object = ModeratedObject(content_object=self.profile) moderated_object.save() value = moderated_object.has_object_been_changed(self.profile) self.assertEqual(value, False) class AutoModerateTestCase(TestCase): fixtures = ['test_users.json', 'test_moderation.json'] def setUp(self): self.moderation = ModerationManager() class UserProfileModerator(GenericModerator): auto_approve_for_superusers = True auto_approve_for_staff = True auto_reject_for_groups = ['banned'] self.moderation.register(UserProfile, UserProfileModerator) self.user = User.objects.get(username='moderator') self.profile = UserProfile.objects.get(user__username='moderator') def tearDown(self): teardown_moderation() def test_auto_approve_helper_status_approved(self): self.profile.description = 'New description' self.profile.save() status = automoderate(self.profile, self.user) self.assertEqual(status, MODERATION_STATUS_APPROVED) profile = UserProfile.objects.get(user__username='moderator') self.assertEqual(profile.description, 'New description') def test_auto_approve_helper_status_rejected(self): group = Group(name='banned') group.save() self.user.groups.add(group) self.user.save() self.profile.description = 'New description' self.profile.save() status = automoderate(self.profile, self.user) profile = UserProfile.unmoderated_objects.get( user__username='moderator') self.assertEqual(status, MODERATION_STATUS_REJECTED) self.assertEqual(profile.description, 'Old description') def test_model_not_registered_with_moderation(self): obj = ModelWithSlugField2(slug='test') obj.save() self.assertRaises(RegistrationError, automoderate, obj, self.user) @unittest.skipIf(VERSION[:2] < (1, 5), "Custom auth users require 1.5") # Using the decorator is causing problems with Django 1.3, so use # the non-decorated version below. # @override_settings(AUTH_USER_MODEL='tests.CustomUser') class ModerateCustomUserTestCase(ModerateTestCase): def setUp(self): from tests.models import CustomUser,\ UserProfileWithCustomUser from django.conf import settings self.user = CustomUser.objects.create( username='custom_user', password='<PASSWORD>') self.copy_m = ModeratedObject.moderated_by ModeratedObject.moderated_by = models.ForeignKey( getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True, editable=False, related_name='moderated_by_set') self.profile = UserProfileWithCustomUser.objects.create( user=self.user, description='Old description', url='http://google.com') self.moderation = setup_moderation([UserProfileWithCustomUser]) def tearDown(self): teardown_moderation() ModeratedObject.moderated_by = self.copy_m # The actual tests are inherited from ModerateTestCase if VERSION >= (1, 5): ModerateCustomUserTestCase = override_settings( AUTH_USER_MODEL='tests.CustomUser' )(ModerateCustomUserTestCase)
# Standard PyTorch imports import time import math import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import matplotlib.pyplot as plt class EncoderDecoderP(nn.Module): """ A standard Encoder-Decoder architecture. Base for this and many other models. """ def __init__(self, encoder, decoder, src_embed, tgt_embed, generator): super(EncoderDecoderP, self).__init__() self.encoder = encoder self.decoder = decoder self.src_embed = src_embed self.tgt_embed = tgt_embed self.generator = generator def forward(self, src, tgt, src_mask, tgt_mask): """Take in and process masked src and target sequences.""" memory = self.encoder(self.src_embed(src), src_mask) output = self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask) return output def encode(self, src, src_mask): return self.encoder(self.src_embed(src), src_mask) def decode(self, memory, src_mask, tgt, tgt_mask): return self.decoder(self.tgt_embed(tgt), memory, src_mask, tgt_mask) class GeneratorP(nn.Module): """ Define standard linear + softmax generation step. ??? """ def __init__(self, d_model, vocab): super(GeneratorP, self).__init__() self.proj = nn.Linear(d_model, vocab) def forward(self, x): return F.log_softmax(self.proj(x), dim=-1) def clones_p(module, N): """Produce N identical layers.""" return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) class EncoderP(nn.Module): """Core encoder is a stack of N layers""" def __init__(self, layer, N): super(EncoderP, self).__init__() self.layers = clones_p(layer, N) self.norm = LayerNormP(layer.size) def forward(self, x, mask): """Pass the input (and mask) through each layer in turn.""" for layer in self.layers: x = layer(x, mask) return self.norm(x) class LayerNormP(nn.Module): """ Construct a layernorm module (See citation for details). ln = LayerNorm(10) x = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]).type(torch.float) ln.forward(x) """ def __init__(self, features, eps=1e-6): super(LayerNormP, self).__init__() self.a_2 = nn.Parameter(torch.ones(features)) self.b_2 = nn.Parameter(torch.zeros(features)) self.eps = eps def forward(self, x): mean = x.mean(-1, keepdim=True) # std = x.std(-1, keepdim=True) std = x.std(-1, keepdim=True, unbiased=False) # changed @@@ """ default value of unbiased is True. because Keras only provide biased std. for comparison purpose, changed to use biased std. """ return self.a_2 * (x - mean) / (std + self.eps) + self.b_2 class SublayerConnectionP(nn.Module): """ A residual connection followed by a layer norm. Note for code simplicity the norm is first as opposed to last. """ def __init__(self, size, dropout): super(SublayerConnectionP, self).__init__() self.norm = LayerNormP(size) self.dropout = nn.Dropout(dropout) def forward(self, x, sublayer): """ Apply residual connection to any sublayer with the same size. x : input to sublayer sublayer: {multi-head attention or position-wise feed-forward} Following original paper, this should be norm(x + dropout(sublayer(x))) But according to below comment https://github.com/tensorflow/tensor2tensor/blob/v1.6.5/tensor2tensor/layers/common_hparams.py#L110-L112 # TODO(noam): The current settings ("", "dan") are the published version # of the transformer. ("n", "da") seems better for harder-to-learn # models, so it should probably be the default. and comment below https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/layers/common_layers.py The sequence is specified as a string which may contain the following characters: a: add previous_value n: apply normalization d: apply dropout z: zero add original paper use only post process 'dan' which is doing dropout, add, norm for sublayer_output and it is norm(x + dropout(sublayer(x)) enhanced version is doing norm on x and then dropout on sublayer_output and add. this is x + dropout(sublayer(norm(x))) """ return x + self.dropout(sublayer(self.norm(x))) class EncoderLayerP(nn.Module): """ Encoder is made up of self-attn and feed forward (defined below) """ def __init__(self, size, self_attn, feed_forward, dropout): super(EncoderLayerP, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward self.sublayer = clones_p(SublayerConnectionP(size, dropout), 2) self.size = size def forward(self, x, mask): """Follow Figure 1 (left) for connections.""" x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) return self.sublayer[1](x, self.feed_forward) class DecoderP(nn.Module): """Generic N layer decoder with masking.""" def __init__(self, layer, N): super(DecoderP, self).__init__() self.layers = clones_p(layer, N) self.norm = LayerNormP(layer.size) def forward(self, x, memory, src_mask, tgt_mask): for layer in self.layers: x = layer(x, memory, src_mask, tgt_mask) return self.norm(x) class DecoderLayerP(nn.Module): """Decoder is made of self-attn, src-attn, and feed forward (defined below)""" def __init__(self, size, self_attn, src_attn, feed_forward, dropout): super(DecoderLayerP, self).__init__() self.size = size self.self_attn = self_attn self.src_attn = src_attn self.feed_forward = feed_forward self.sublayer = clones_p(SublayerConnectionP(size, dropout), 3) def forward(self, x, memory, src_mask, tgt_mask): """Follow Figure 1 (right) for connections.""" m = memory x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, tgt_mask)) x = self.sublayer[1](x, lambda x: self.src_attn(x, m, m, src_mask)) return self.sublayer[2](x, self.feed_forward) def subsequent_mask_p(size): """ Mask out subsequent positions. >>> subsequent_mask(3) tensor([ [ [1, 0, 0], [1, 1, 0], [1, 1, 1] ]], dtype=torch.uint8) # [1, 3, 3] This function gives mask for a sentence with 'size' words. """ attn_shape = (1, size, size) subsequent_mask = np.triu(np.ones(attn_shape), k=1).astype('uint8') return torch.from_numpy(subsequent_mask) == 0 def attention_p(q_w_q, k_w_k, v_w_v, mask=None, dropout=None): """ Compute 'Scaled Dot Product Attention' With settings d_model = 12 num of word in sentence = 4 num of sentences = nbatches = 5 num of heads = self.h = 2 self.d_k = d_model / self.h = 6 shape of q_w_q, k_w_k, v_w_v: [5, 2, 4, 6] -> last dim is 6 because we divided d_model by num heads. (12/6) -> [num sentences, heads, num words, word info 'for this head'] torch.matmul(q_w_q, k_w_k.transpose(-2, -1)) / math.sqrt(d_k) -> attention(QW^Q, KW^K, VW^V) = softmax( {QW^Q dot (KW^K)^T} / sqrt(d_k)} ) dot VW^V -> eq (1) of original paper shape of scores = torch.matmul(q_w_q, k_w_k.transpose(-2, -1)): [5, 2, 4, 4] -> dot product of [5, 2, 4, 6] and [5, 2, 6, 4] shape of mask: [5, 1, 1, 4] -> this mask shape will be extended as shape of scores, scores's shape is [5, 2, 4, 4] scores.masked_fill(mask == 0, -1e9) -> create new tensor with scores having original value if mask != 0 otherwise having -1e9 if mask == 0. """ d_k = q_w_q.size(-1) scores = torch.matmul(q_w_q, k_w_k.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: scores = scores.masked_fill(mask == 0, -1e9) # Fills scores where mask is zero p_attn = F.softmax(scores, dim=-1) if dropout is not None: p_attn = dropout(p_attn) return torch.matmul(p_attn, v_w_v), p_attn class MultiHeadedAttentionP(nn.Module): """ """ def __init__(self, h, d_model, dropout=0.1, linears=None): """Take in model size and number of heads. h: number of heads linears: added by kdw to test fixed weight linear. """ super(MultiHeadedAttentionP, self).__init__() assert d_model % h == 0 # We assume d_v always equals d_k self.d_k = d_model // h # d_k = d_v = d_model/h self.h = h # number of heads if linears: assert len(linears) == 4 self.linears = linears else: self.linears = clones_p(nn.Linear(d_model, d_model), 4) """ : 4 copies for W^Q, W^K, W^V and W^O (refers to page 5 of paper) : actually W^{Q, K, V} is for h heads, so it's dim is d_model, not d_model/h """ self.attn = None self.dropout = nn.Dropout(p=dropout) def forward(self, query, key, value, mask=None): """ Implements Figure 2 With settings d_model = 12 num of word in sentence = 4 num of sentences = nbatches = 5 num of heads = self.h = 2 self.d_k = d_model / self.h = 6 shape of query: [5, 4, 12] shape of key: [5, 4, 12] shape of value: [5, 4, 12] shape of w_q, w_k, w_v: [12, 12] shape of self.linears[0](query): [5, 4, 12] self.linears[1](key) : [5, 4, 12] self.linears[2](value): [5, 4, 12] ※ view function is similar to reshape of numpy shape of self.linears[0](query).view(5, -1, 2, 6): [5, 4, 2, 6] -> splitting last dim into 2 shape of q_w_q = self.linears[0](query).view(5, -1, 2, 6).transpose(1, 2): [5, 2, 4, 6] k_w_k = self.linears[1](key ).view(5, -1, 2, 6).transpose(1, 2): [5, 2, 4, 6] v_w_v = self.linears[2](value).view(5, -1, 2, 6).transpose(1, 2): [5, 2, 4, 6] -> exchanging 1st and 2nd dim to ... ??? why??? """ if mask is not None: # Same mask applied to all h heads. mask = mask.unsqueeze(1) nbatches = query.size(0) # 1) Do all the linear projections in batch from d_model => h x d_k q_w_q, k_w_k, v_w_v = \ [l(x).view(nbatches, -1, self.h, self.d_k).transpose(1, 2) for l, x in zip(self.linears, (query, key, value))] # 2) Apply attention on all the projected vectors in batch. x, self.attn = attention_p(q_w_q, k_w_k, v_w_v, mask=mask, dropout=self.dropout) # 3) "Concat" using a view and apply a final linear. """ shape of x: [5, 2, 4, 6] -> last two dim represent one sentence. x.transpose(1, 2): [5, 4, 2, 6] -> last two dim represent attentions(multiple heads) of one word. x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k): [5, 4, 12] -> concatenating attentions into one. self.linears[-1](x) -> concat(head1, head2, ...) dot W^O shape of W^O: d_model times d_K """ x = x.transpose(1, 2).contiguous().view(nbatches, -1, self.h * self.d_k) return self.linears[-1](x) class PositionwiseFeedForwardP(nn.Module): """Implements FFN equation.""" def __init__(self, d_model, d_ff, dropout=0.1): super(PositionwiseFeedForwardP, self).__init__() self.w_1 = nn.Linear(d_model, d_ff) self.w_2 = nn.Linear(d_ff, d_model) self.dropout = nn.Dropout(dropout) def forward(self, x): return self.w_2(self.dropout(F.relu(self.w_1(x)))) class EmbeddingsP(nn.Module): """ >>> np.random.seed(0) >>> emb_weight = np.random.rand(7, 12) # total 7 tokens and hidden size is 12 >>> em = EmbeddingsP(d_model=12, vocab=7, weight=emb_weight) >>> test_emb_pytorch = em(torch.tensor([list(range(7))])) >>> test_emb_pytorch = test_emb_pytorch.numpy()[:] >>> print(test_emb_pytorch, test_emb_pytorch.shape) """ def __init__(self, d_model, vocab, weight=None): super(EmbeddingsP, self).__init__() self.d_model = d_model self.lut = nn.Embedding(num_embeddings=vocab, embedding_dim=d_model) if weight is None: pass elif isinstance(weight, np.ndarray): self.lut.weight.data.copy_(torch.from_numpy(weight)) self.lut.weight.requires_grad = False else: raise ValueError('Invalid weight') def forward(self, x): """Why multiply sqrt of d_model? maybe this is scaling factor that is sqrt of d_k in the eq1 of original paper. Btw d_k = d_v = d_model / h = 64, scaling factor is sqrt of length of vector itself. """ return self.lut(x) * math.sqrt(self.d_model) class PositionalEncodingP(nn.Module): """Implement the PE function. >>> # test implementation >>> max_len = 4 >>> d_model = 12 >>> pe = torch.zeros(max_len, d_model); print(pe, pe.shape) >>> # sentence number 0 to max_len-1 >>> position = torch.arange(start=0.0, end=max_len).unsqueeze(1); print(position, position.shape) >>> # div term = exp{ -frac{2i}{d_model} * log(10000) } >>> # PE(pos, 2i) = sin(pos/10000^{frac{2i}{d_model}} >>> # i : index of 0 to d_model-1 >>> div_term = torch.exp(torch.arange(0.0, d_model, 2) * -(math.log(10000.0) / d_model)) >>> pe[:, 0::2] = torch.sin(position * div_term) >>> pe[:, 1::2] = torch.cos(position * div_term) >>> pe.shape # (4, 12) >>> pe = pe.unsqueeze(0) >>> pe.shape # (1, 4, 12) >>> # plotting >>> d_model = 12 >>> num_sentences = 1 >>> num_tokens_in_sentence = 100 >>> plt.figure(figsize=(15, 5)) >>> pe = PositionalEncodingP(d_model=d_model, dropout=0.) >>> y = pe.forward(Variable(torch.zeros(1, num_tokens_in_sentence, d_model))) >>> plt.plot(np.arange(num_tokens_in_sentence), y[0, :, 4:8].data.numpy()) >>> plt.legend(["dim %d" % p for p in [4, 5, 6, 7]]) >>> plt.show() """ def __init__(self, d_model, dropout, max_len=5000): super(PositionalEncodingP, self).__init__() self.dropout = nn.Dropout(p=dropout) # Compute the positional encodings once in log space. pe = torch.zeros(max_len, d_model) position = torch.arange(0.0, max_len).unsqueeze(1) div_term = torch.exp(torch.arange(0.0, d_model, 2) * -(math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0) self.register_buffer('pe', pe) def forward(self, x): x = x + Variable(self.pe[:, :x.size(1)], requires_grad=False) return self.dropout(x) def make_model_p(src_vocab, tgt_vocab, N=6, d_model=512, d_ff=2048, h=8, dropout=0.1): """ Helper: Construct a model from hyperparameters. :param src_vocab: :param tgt_vocab: :param N: # of transformer block :param d_model: size of embedding :param d_ff: hidden layer size of the 'Position wize feed forward' unit. :param h: # of heads :param dropout: :return: """ c = copy.deepcopy attn = MultiHeadedAttentionP(h, d_model) ff = PositionwiseFeedForwardP(d_model, d_ff, dropout) position = PositionalEncodingP(d_model, dropout) model = EncoderDecoderP( encoder=EncoderP( # 'encoder' is stack of N 'encoder layer' layer=EncoderLayerP( # 'encoder layer' has 2 sub-layers, size=d_model, # which are 'multi-attn' and 'position-wise fully connected feed-forward' self_attn=c(attn), feed_forward=c(ff), dropout=dropout ), N=N ), decoder=DecoderP( # stack of N 'decoder layer' layer=DecoderLayerP( size=d_model, self_attn=c(attn), src_attn=c(attn), feed_forward=c(ff), dropout=dropout ), N=N ), src_embed=nn.Sequential( EmbeddingsP( d_model=d_model, vocab=src_vocab ), c(position) # positional encoding ), tgt_embed=nn.Sequential( # Sequential(f1(x), f2) means y = f2(f1(x)) EmbeddingsP( d_model=d_model, vocab=tgt_vocab ), c(position) # positional encoding ), generator=GeneratorP(d_model=d_model, vocab=tgt_vocab) ) # This was important from their code. # Initialize parameters with Glorot / fan_avg. for p in model.parameters(): if p.dim() > 1: # nn.init.xavier_uniform(p) nn.init.xavier_uniform_(p) # fixed by kdw return model class BatchP: """Object for holding a batch of data with mask during training.""" def __init__(self, src, trg=None, pad=0): self.src = src self.src_mask = (src != pad).unsqueeze(-2) """ >>> trg = src = torch.tensor([[1, 2, 3, 2], [1, 2, 1, 4], [1, 2, 4, 5], [1, 1, 2, 1], [1, 2, 5, 5]]) # [5, 4] >>> pad = 0 >>> src.unsqueeze(0).shape # (1, 5, 10) >>> src.unsqueeze(1).shape # (5, 1, 10) >>> src.unsqueeze(-1).shape # (5, 10, 1) >>> src.unsqueeze(-2).shape # (5, 1, 10) """ if trg is not None: self.trg = trg[:, :-1] # without last column, why??? self.trg_y = trg[:, 1:] # without first column, why??? self.trg_mask = self.make_std_mask(self.trg, pad) self.ntokens = (self.trg_y != pad).data.sum() # where this used for??? @staticmethod def make_std_mask(trg, pad): """ Create a mask to hide padding and future words. >>> trg = src = torch.tensor([[1, 2, 3, 2], [1, 2, 1, 4], [1, 2, 4, 5], [1, 1, 2, 1], [1, 2, 5, 5]]) # (5, 4), number of sentence in this batch is 5, size of embedding is 4. >>> tgt = trg[:, :-1] >>> pad = 0 """ tgt_mask = (trg != pad).unsqueeze(-2) # for example, turn [5, 3] to [5, 1, 3] """ >>> (tgt != pad).shape # (5, 3) >>> tgt_mask = (tgt != pad).unsqueeze(-2) # [5, 1, 3] >>> tgt_mask tensor([[[1, 1, 1]], # mask for 1st sentence [[1, 1, 1]], # 2nd [[1, 1, 1]], # 3rd [[1, 1, 1]], # 4th [[1, 1, 1]]], # 5th dtype=torch.uint8) # [5, 1, 3] """ tgt_mask = tgt_mask & Variable( subsequent_mask_p(size=trg.size(-1)).type_as(tgt_mask.data) ) """ >>> tgt.size(-1) # 3 >>> v = Variable(subsequent_mask(size=tgt.size(-1)).type_as(tgt_mask.data)) >>> v tensor([[[1, 0, 0], [1, 1, 0], [1, 1, 1]]], dtype=torch.uint8) # [1, 3, 3] >>> tgt_mask & v tensor([[[1, 0, 0], # mask for 1st sentence [1, 1, 0], [1, 1, 1]], [[1, 0, 0], # mask for 2nd sentence [1, 1, 0], [1, 1, 1]], [[1, 0, 0], # mask for 3rd sentence [1, 1, 0], [1, 1, 1]], [[1, 0, 0], # mask for 4th sentence [1, 1, 0], [1, 1, 1]], [[1, 0, 0], # mask for 5th sentence [1, 1, 0], [1, 1, 1]]], dtype=torch.uint8) # [5, 3, 3] """ return tgt_mask def run_epoch_p(data_iter, model, loss_compute): """Standard Training and Logging Function""" start = time.time() total_tokens = 0 total_loss = 0 tokens = 0 for i, batch in enumerate(data_iter): out = model.forward(batch.src, batch.trg, batch.src_mask, batch.trg_mask) loss = loss_compute(out, batch.trg_y, batch.ntokens) total_loss += loss total_tokens += batch.ntokens tokens += batch.ntokens if i % 50 == 1: elapsed = time.time() - start # print("Epoch Step: %d Loss: %f Tokens per Sec: %f" % (i, loss / batch.ntokens, tokens / elapsed)) print("Epoch Step: %d Loss: %f Tokens per Sec: %f" % (i, loss / batch.ntokens.type(torch.FloatTensor), tokens.type(torch.FloatTensor) / elapsed)) start = time.time() tokens = 0 # return total_loss / total_tokens return total_loss / total_tokens.type(torch.FloatTensor) # fixed by kdw global max_src_in_batch, max_tgt_in_batch def batch_size_fn_p(new, count, sofar): """Keep augmenting batch and calculate total number of tokens + padding.""" global max_src_in_batch, max_tgt_in_batch if count == 1: max_src_in_batch = 0 max_tgt_in_batch = 0 max_src_in_batch = max(max_src_in_batch, len(new.src)) max_tgt_in_batch = max(max_tgt_in_batch, len(new.trg) + 2) src_elements = count * max_src_in_batch tgt_elements = count * max_tgt_in_batch return max(src_elements, tgt_elements) class NoamOptP: """Optim wrapper that implements rate. from paper 5.3 Optimizer. We used the Adam optimizer with β1 = 0:9, β2 = 0:98 and epsilon = 10−9. We varied the learning rate over the course of training, according to the formula: (3) This corresponds to increasing the learning rate linearly for the first warmup_steps training steps, and decreasing it thereafter proportionally to the inverse square root of the step number. We used warmup_steps = 4000 ex) >>> opts = [NoamOptP(512, 1, 4000, None), NoamOpt(512, 1, 8000, None), NoamOpt(256, 1, 4000, None)] >>> plt.plot(np.arange(1, 20000), [[opt.rate(i) for opt in opts] for i in range(1, 20000)]) >>> plt.legend(["512:4000", "512:8000", "256:4000"]) >>> plt.show() """ def __init__(self, model_size, factor, warmup, optimizer): self.optimizer = optimizer self._step = 0 self.warmup = warmup # before this steps, lr increase | after then lr decrease. self.factor = factor # ??? self.model_size = model_size self._rate = 0 def step(self): """Update parameters and rate""" self._step += 1 rate = self.rate() # learning rate actually we use. for p in self.optimizer.param_groups: p['lr'] = rate self._rate = rate # save to be used for calculating lr in the next step. self.optimizer.step() def rate(self, step=None): """Implement `lrate` above""" if step is None: step = self._step # formula (3) of the original paper. return self.factor * (self.model_size ** (-0.5) * min(step ** (-0.5), step * self.warmup ** (-1.5))) def get_std_opt_p(model): return NoamOptP(model.src_embed[0].d_model, 2, 4000, torch.optim.Adam(model.parameters(), lr=0, betas=(0.9, 0.98), eps=1e-9)) class LabelSmoothingP(nn.Module): """Implement label smoothing.""" def __init__(self, size, padding_idx, smoothing=0.0): super(LabelSmoothingP, self).__init__() # self.criterion = nn.KLDivLoss(size_average=False) self.criterion = nn.KLDivLoss(reduction='sum') # fixed by kdw self.padding_idx = padding_idx self.confidence = 1.0 - smoothing self.smoothing = smoothing self.size = size self.true_dist = None def forward(self, x, target): assert x.size(1) == self.size true_dist = x.data.clone() true_dist.fill_(self.smoothing / (self.size - 2)) true_dist.scatter_(1, target.data.unsqueeze(1), self.confidence) true_dist[:, self.padding_idx] = 0 mask = torch.nonzero(target.data == self.padding_idx) if mask.dim() > 1: # fixed 0 to 1 by kew. true_dist.index_fill_(0, mask.squeeze(), 0.0) self.true_dist = true_dist return self.criterion(x, Variable(true_dist, requires_grad=False)) def greedy_decode_p(model, src, src_mask, max_len, start_symbol): memory = model.encode(src, src_mask) ys = torch.ones(1, 1).fill_(start_symbol).type_as(src.data) for i in range(max_len-1): out = model.decode(memory, src_mask, Variable(ys), Variable(subsequent_mask_p(ys.size(1)) .type_as(src.data))) prob = model.generator(out[:, -1]) _, next_word = torch.max(prob, dim = 1) next_word = next_word.data[0] ys = torch.cat([ys, torch.ones(1, 1).type_as(src.data).fill_(next_word)], dim=1) return ys def data_gen_p(V, batch, nbatches, max_words_in_sentence): """ Generate random data for a src-tgt copy task. # 5: # of sentences per batch == batch(2nd arg) # 4: # of words in each sentence # 7: size of word dictionary np.random.randint(low=1, high=7, size=(5, 4)) # 5 by 4 matrix >>> gen = data_gen(7, 5, 2, 4) >>> batch0 = next(gen) >>> batch0.src >>> batch0.trg >>> batch0.src.shape # [5, 4] >>> batch0.ntokens # 15 tensor([[1, 2, 3, 2], [1, 2, 1, 4], [1, 2, 4, 5], [1, 1, 2, 1], [1, 2, 5, 5]]) # [5, 4] >>> batch0.src_mask tensor([[[1, 1, 1, 1]], [[1, 1, 1, 1]], [[1, 1, 1, 1]], [[1, 1, 1, 1]], [[1, 1, 1, 1]]], dtype=torch.uint8) # [5, 1, 4] >>> batch0.trg tensor([[1, 2, 3], [1, 2, 1], [1, 2, 4], [1, 1, 2], [1, 2, 5]]) # [5, 3] >>> batch0.trg_y tensor([[2, 3, 2], [2, 1, 4], [2, 4, 5], [1, 2, 1], [2, 5, 5]]) # [5, 3] >>> batch0.trg_mask tensor([[[1, 0, 0], [1, 1, 0], [1, 1, 1]], [[1, 0, 0], [1, 1, 0], [1, 1, 1]], [[1, 0, 0], [1, 1, 0], [1, 1, 1]], [[1, 0, 0], [1, 1, 0], [1, 1, 1]], [[1, 0, 0], [1, 1, 0], [1, 1, 1]]], dtype=torch.uint8) # [5, 3, 3] >>> batch0.ntokens # 15 >>> batch0.src.shape # (5, 4) """ for _ in range(nbatches): data = torch.from_numpy(np.random.randint(low=1, high=V, size=(batch, max_words_in_sentence))) data[:, 0] = 1 # 1 for first column src = Variable(data, requires_grad=False).type(torch.long) tgt = Variable(data, requires_grad=False).type(torch.long) yield BatchP(src, tgt, 0)
""" Copyright (c) 2018-2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy as np from ..config import BoolField, BaseField, NumberField, ConfigError, StringField from ..preprocessor import Preprocessor class ResampleAudio(Preprocessor): __provider__ = 'resample_audio' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'sample_rate': NumberField(value_type=int, min_value=1, description='Set new audio sample rate.'), }) return parameters def configure(self): self.sample_rate = self.get_value_from_config('sample_rate') def process(self, image, annotation_meta=None): sample_rate = image.metadata.get('sample_rate') if sample_rate is None: raise RuntimeError('Operation "{}" can\'t resample audio: required original samplerate in metadata.'. format(self.__provider__)) if sample_rate == self.sample_rate: return image data = image.data duration = data.shape[1] / sample_rate resampled_data = np.zeros(shape=(data.shape[0], int(duration*self.sample_rate)), dtype=float) x_old = np.linspace(0, duration, data.shape[1]) x_new = np.linspace(0, duration, resampled_data.shape[1]) resampled_data[0] = np.interp(x_new, x_old, data[0]) image.data = resampled_data image.metadata['sample_rate'] = self.sample_rate return image class ClipAudio(Preprocessor): __provider__ = 'clip_audio' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'duration': BaseField( description="Length of audio clip in seconds or samples (with 'samples' suffix)." ), 'max_clips': NumberField( value_type=int, min_value=1, optional=True, description="Maximum number of clips per audiofile." ), 'overlap': BaseField( optional=True, description="Overlapping part for each clip." ), }) return parameters def configure(self): duration = self.get_value_from_config('duration') self._parse_duration(duration) self.max_clips = self.get_value_from_config('max_clips') or np.inf overlap = self.get_value_from_config('overlap') self._parse_overlap(overlap) def process(self, image, annotation_meta=None): data = image.data sample_rate = image.metadata.get('sample_rate') if sample_rate is None: raise RuntimeError('Operation "{}" failed: required "sample rate" in metadata.'. format(self.__provider__)) audio_duration = data.shape[1] clip_duration = self.duration if self.is_duration_in_samples else int(self.duration * sample_rate) clipped_data = [] if self.is_overlap_in_samples: hop = clip_duration - self.overlap_in_samples else: hop = int((1 - self.overlap) * clip_duration) if hop > clip_duration: raise ConfigError("Preprocessor {}: clip overlapping exceeds clip length.".format(self.__provider__)) for clip_no, clip_start in enumerate(range(0, audio_duration, hop)): if clip_start + clip_duration > audio_duration or clip_no >= self.max_clips: break clip = data[:, clip_start: clip_start + clip_duration] clipped_data.append(clip) image.data = clipped_data image.metadata['multi_infer'] = True return image def _parse_overlap(self, overlap): self.is_overlap_in_samples = False self.overlap = 0 if overlap is None: return if isinstance(overlap, str): if overlap.endswith('%'): try: self.overlap = float(overlap[:-1]) / 100 except ValueError: raise ConfigError("Preprocessor {}: invalid value for 'overlap' - {}." .format(self.__provider__, overlap)) elif overlap.endswith('samples'): try: self.overlap_in_samples = int(overlap[:-7]) except ValueError: raise ConfigError("Preprocessor {}: invalid value for 'overlap' - {}." .format(self.__provider__, overlap)) if self.overlap_in_samples < 1: raise ConfigError("Preprocessor {}: invalid value for 'overlap' - {}." .format(self.__provider__, overlap)) self.is_overlap_in_samples = True else: raise ConfigError("Preprocessor {}: invalid value for 'overlap' - {}." .format(self.__provider__, overlap)) else: try: self.overlap = float(overlap) except ValueError: raise ConfigError("Preprocessor {}: invalid value for 'overlap' - {}." .format(self.__provider__, overlap)) if self.overlap <= 0 or self.overlap >= 1: raise ConfigError("Preprocessor {}: invalid value for 'overlap' - {}." .format(self.__provider__, overlap)) def _parse_duration(self, duration): self.is_duration_in_samples = False if isinstance(duration, str): if duration.endswith('samples'): try: self.duration = int(duration[:-7]) except ValueError: raise ConfigError("Preprocessor {}: invalid value for duration - {}." .format(self.__provider__, duration)) if self.duration <= 1: raise ConfigError("Preprocessor {}: duration should be positive value - {}." .format(self.__provider__, self.duration)) self.is_duration_in_samples = True else: raise ConfigError("Preprocessor {}: invalid value for duration - {}.". format(self.__provider__, duration)) else: try: self.duration = float(duration) except ValueError: raise ConfigError("Preprocessor {}: invalid value for duration - {}." .format(self.__provider__, duration)) if self.duration <= 0: raise ConfigError("Preprocessor {}: duration should be positive value - {}." .format(self.__provider__, self.duration)) class SamplesToFloat32(Preprocessor): __provider__ = 'audio_samples_to_float32' def process(self, image, annotation_meta=None): image.data = self._convert_samples_to_float32(image.data) return image @staticmethod def _convert_samples_to_float32(samples): """Convert sample type to float32. Audio sample type is usually integer or float-point. Integers will be scaled to [-1, 1] in float32. """ float32_samples = samples.astype('float32') if samples.dtype in np.sctypes['int']: bits = np.iinfo(samples.dtype).bits float32_samples *= 1.0 / 2 ** (bits - 1) elif samples.dtype in np.sctypes['float']: pass else: raise TypeError("Unsupported sample type: {}.".format(samples.dtype)) return float32_samples class NormalizeAudio(Preprocessor): __provider__ = 'audio_normalization' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'int16mode': BoolField(optional=True, default=False, description="Normalization to int16 range"), }) return parameters def configure(self): self.int16mode = self.get_value_from_config('int16mode') def process(self, image, annotation_meta=None): sound = image.data if self.int16mode: sound = sound / np.float32(0x7fff) else: sound = (sound - np.mean(sound)) / (np.std(sound) + 1e-15) image.data = sound return image class HanningWindow(Preprocessor): __provider__ = 'hanning_window' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'base': NumberField( optional=True, default=512, description="Window length", value_type=int ), }) return parameters def configure(self): self.base = self.get_value_from_config('base') self.window = np.hanning(self.base) def process(self, image, annotation_meta=None): image.data = image.data * self.window return image class AudioSpectrogram(Preprocessor): __provider__ = 'audio_spectrogram' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ 'fftbase': NumberField(optional=True, default=512, description="Base of FFT, samples", value_type=int), 'magnitude_squared': BoolField(optional=True, default=True, description="Square spectrum magnitudes"), 'skip_channels': BoolField(optional=True, default=False, description="Skips channels dimension"), }) return parameters def configure(self): self.fftbase = self.get_value_from_config('fftbase') self.magnutide_squared = self.get_value_from_config('magnitude_squared') self.skip_channels = self.get_value_from_config('skip_channels') def process(self, image, annotation_meta=None): frames = image.data if self.skip_channels: frames = frames.squeeze() pspec = np.absolute(np.fft.rfft(frames, self.fftbase)) # pylint:disable=W9904 if self.magnutide_squared: pspec = np.square(pspec) image.data = pspec return image class TriangleFiltering(Preprocessor): __provider__ = 'audio_triangle_filtering' HZ2MEL = 1127.0 MEL_CUTOFF = 700 @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ "base": NumberField( default=16000, description='Spectrogram length expected by filter bank', value_type=int ), "sample_rate": NumberField( default=16000, description='sample rate value expected by model', value_type=int ), "filterbank_channel_count": NumberField( default=40, description='number of channels in filter bank', value_type=int ), "lower_frequency_limit": NumberField(default=20, description='filter passband lower boundary'), "upper_frequency_limit": NumberField(default=4000, description='filter passband upper boundary'), }) return parameters def configure(self): self.base = self.get_value_from_config('base') self.sample_rate = self.get_value_from_config('sample_rate') self.filterbank_channel_count = self.get_value_from_config('filterbank_channel_count') self.lower_frequency_limit = self.get_value_from_config('lower_frequency_limit') self.upper_frequency_limit = self.get_value_from_config('upper_frequency_limit') self.initialize() def process(self, image, annotation_meta=None): spectrogram = image.data samples, _ = spectrogram.shape kFilterbankFloor = 1e-12 mfcc_output = np.zeros((samples, self.filterbank_channel_count)) for j in range(samples): filtered = self.compute(spectrogram[j, ...]) filtered = np.where(filtered < kFilterbankFloor, kFilterbankFloor, filtered) mfcc_output[j, :] = np.log(filtered) image.data = mfcc_output return image def freq2mel(self, freq): return self.HZ2MEL * np.log1p(freq / self.MEL_CUTOFF) def initialize(self): center_frequencies = np.zeros((self.filterbank_channel_count + 1)) mel_low = self.freq2mel(self.lower_frequency_limit) mel_hi = self.freq2mel(self.upper_frequency_limit) mel_span = mel_hi - mel_low mel_sapcing = mel_span / (self.filterbank_channel_count + 1) for i in range((self.filterbank_channel_count + 1)): center_frequencies[i] = mel_low + (mel_sapcing * (1 + i)) hz_per_sbin = 0.5 * self.sample_rate / (self.base - 1) self.start_index = int(1.5 + (self.lower_frequency_limit / hz_per_sbin)) self.end_index = int(self.upper_frequency_limit / hz_per_sbin) self.band_mapper = np.zeros(self.base) channel = 0 for i in range(self.base): melf = self.freq2mel(i * hz_per_sbin) if ((i < self.start_index) or (i > self.end_index)): self.band_mapper[i] = -2 else: while ((center_frequencies[int(channel)] < melf) and (channel < self.filterbank_channel_count)): channel += 1 self.band_mapper[i] = channel - 1 self.weights = np.zeros(self.base) for i in range(self.base): channel = self.band_mapper[i] if ((i < self.start_index) or (i > self.end_index)): self.weights[i] = 0.0 else: if channel >= 0: self.weights[i] = ((center_frequencies[int(channel) + 1] - self.freq2mel(i * hz_per_sbin))/ (center_frequencies[int(channel) + 1] - center_frequencies[int(channel)])) else: self.weights[i] = ((center_frequencies[0] - self.freq2mel(i * hz_per_sbin)) / (center_frequencies[0] - mel_low)) def compute(self, mfcc_input): output_channels = np.zeros(self.filterbank_channel_count) for i in range(self.start_index, (self.end_index + 1)): spec_val = np.sqrt(mfcc_input[i]) weighted = spec_val * self.weights[i] channel = self.band_mapper[i] if channel >= 0: output_channels[int(channel)] += weighted channel += 1 if channel < self.filterbank_channel_count: output_channels[int(channel)] += (spec_val - weighted) return output_channels class DCT(Preprocessor): __provider__ = 'audio_dct' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ "filterbank_channel_count": NumberField( default=40, description='number of channels in filter bank', value_type=int ), "numceps": NumberField(default=26, description='Number of cepstral coefficients', value_type=int), }) return parameters def configure(self): self.input_length = self.get_value_from_config('filterbank_channel_count') self.dct_coefficient_count = self.get_value_from_config('numceps') self.initialize() def process(self, image, annotation_meta=None): filtered = image.data samples, _ = filtered.shape cepstrum = np.zeros((samples, self.dct_coefficient_count)) for j in range(samples): cepstrum[j, ...] = self.compute(filtered[j, ...]) image.data = cepstrum return image def initialize(self): self.cosine = np.zeros((self.dct_coefficient_count, self.input_length)) fnorm = np.sqrt(2.0 / self.input_length) arg = np.pi / self.input_length for i in range(self.dct_coefficient_count): for j in range(self.input_length): self.cosine[i][j] = fnorm * np.cos(i * arg * (j + 0.5)) def compute(self, filtered): output_dct = np.zeros(self.dct_coefficient_count) base = filtered.shape[0] if base > self.input_length: base = self.input_length for i in range(self.dct_coefficient_count): _sum = 0.0 for j in range(base): _sum += self.cosine[i][j] * filtered[j] output_dct[i] = _sum return output_dct class ClipCepstrum(Preprocessor): __provider__ = 'clip_cepstrum' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ "context": NumberField(default=9, description='number of samples in context window', value_type=int), "numceps": NumberField(default=26, description='Number of input coefficients', value_type=int), }) return parameters def configure(self): self.n_context = self.get_value_from_config('context') self.numceps = self.get_value_from_config('numceps') def process(self, image, annotation_meta=None): mfcc_feat = image.data num_strides, _ = mfcc_feat.shape empty_context = np.zeros((self.n_context, self.numceps), dtype=mfcc_feat.dtype) mfcc_feat = np.concatenate((empty_context, mfcc_feat, empty_context)) window_size = 2 * self.n_context + 1 features = np.lib.stride_tricks.as_strided( mfcc_feat, (num_strides, window_size, self.numceps), (mfcc_feat.strides[0], mfcc_feat.strides[0], mfcc_feat.strides[1]), writeable=False) image.data = features return image class PackCepstrum(Preprocessor): __provider__ = 'pack_cepstrum' @classmethod def parameters(cls): parameters = super().parameters() parameters.update({ "step": NumberField(default=16, description='number of simultaneously processed contexts', value_type=int), }) return parameters def configure(self): self.step = self.get_value_from_config('step') def process(self, image, annotation_meta=None): features = image.data steps, context, numceps = features.shape if steps % self.step: empty_context = np.zeros((self.step - (steps % self.step), context, numceps), dtype=features.dtype) features = np.concatenate((features, empty_context)) steps, context, numceps = features.shape # pylint:disable=E0633 features = np.expand_dims(features, 0) packed = [] for i in range(0, steps, self.step): packed.append(features[:, i:i+self.step, ...]) image.data = packed image.metadata['multi_infer'] = True return image class TrimmingAudio(Preprocessor): __provider__ = 'trim' @classmethod def parameters(cls): params = super().parameters() params.update({ 'top_db': NumberField(value_type=float, optional=True, default=60), 'frame_length': NumberField(value_type=int, optional=True, default=2048, min_value=1), 'hop_length': NumberField(value_type=int, optional=True, default=512, min_value=1) }) return params def configure(self): self.top_db = self.get_value_from_config('top_db') self.frame_length = self.get_value_from_config('frame_length') self.hop_length = self.get_value_from_config('hop_length') def process(self, image, annotation_meta=None): image.data = self.trim(image.data) return image def trim(self, y): def frames_to_samples(frames, hop): return np.floor(np.asanyarray(frames) / hop).astype(int) non_silent = self._signal_to_frame_nonsilent(y) nonzero = np.flatnonzero(non_silent) if nonzero.size > 0: start = int(frames_to_samples(nonzero[0], self.hop_length)) end = min(y.shape[-1], int(frames_to_samples(nonzero[-1] + 1, self.hop_length))) else: # The signal only contains zeros start, end = 0, 0 # Build the mono/stereo index full_index = [slice(None)] * y.ndim full_index[-1] = slice(start, end) return y[tuple(full_index)] def _signal_to_frame_nonsilent(self, y): y_mono = np.asfortranarray(y) if y_mono.ndim > 1: y_mono = np.mean(y-y_mono, axis=0) # Compute the MSE for the signal mse = self.mse(y_mono) amin = 1e-10 magnitude = mse.squeeze() ref_value = np.max(magnitude) log_spec = 10.0 * np.log10(np.maximum(amin, magnitude)) log_spec -= 10.0 * np.log10(np.maximum(amin, ref_value)) return log_spec > (-1 * self.top_db) def mse(self, y_mono): y_mono = np.pad(y_mono, int(self.frame_length // 2), mode='reflect') n_frames = 1 + (y_mono.shape[-1] - self.frame_length) // self.hop_length strides = np.asarray(y_mono.strides) new_stride = np.prod(strides[strides > 0] // y_mono.itemsize) * y_mono.itemsize shape = list(y_mono.shape)[:-1] + [self.frame_length, n_frames] strides = list(strides) + [self.hop_length * new_stride] array = np.lib.stride_tricks.as_strided(y_mono, shape, strides) return np.mean(np.abs(array) ** 2, axis=0, keepdims=True) def as_strided(x, shape, strides): class DummyArray: """Dummy object that just exists to hang __array_interface__ dictionaries and possibly keep alive a reference to a base array. """ def __init__(self, interface, base=None): self.__array_interface__ = interface self.base = base interface = dict(x.__array_interface__) if shape is not None: interface['shape'] = tuple(shape) if strides is not None: interface['strides'] = tuple(strides) array = np.asarray(DummyArray(interface, base=x)) # The route via `__interface__` does not preserve structured # dtypes. Since dtype should remain unchanged, we set it explicitly. array.dtype = x.dtype return array windows = { 'hann': np.hanning, 'hamming': np.hamming, 'blackman': np.blackman, 'bartlett': np.bartlett, 'none': None, } class AudioToMelSpectrogram(Preprocessor): __provider__ = 'audio_to_mel_spectrogram' @classmethod def parameters(cls): params = super().parameters() params.update({ 'window_size': NumberField(optional=True, value_type=float, default=0.02), 'window_stride': NumberField(optional=True, value_type=float, default=0.01), 'window': StringField( choices=windows.keys(), optional=True, default='hann' ), 'n_fft': NumberField(optional=True, value_type=int) }) return params def configure(self): self.window_size = self.get_value_from_config('window_size') self.window_stride = self.get_value_from_config('window_stride') self.n_fft = self.get_value_from_config('n_fft') self.window_fn = windows.get(self.get_value_from_config('window')) self.normalize = 'per_feature' self.preemph = 0.97 self.nfilt = 64 self.lowfreq = 0 self.highfreq = None self.pad_to = 16 self.max_duration = 16.7 self.frame_splicing = 1 self.pad_value = 0 self.mag_power = 2.0 self.dither = 1e-05 self.log = True self.log_zero_guard_type = "add" self.log_zero_guard_value = 2 ** -24 def process(self, image, annotation_meta=None): sample_rate = image.metadata.get('sample_rate') if sample_rate is None: raise RuntimeError( 'Operation "{}" failed: required "sample rate" in metadata.'.format(self.__provider__) ) self.window_length = int(self.window_size * sample_rate) self.hop_length = int(self.window_stride * sample_rate) self.n_fft = self.n_fft or 2 ** np.ceil(np.log2(self.window_length)) self.window = self.window_fn(self.window_length) if self.window_fn is not None else None highfreq = self.highfreq or (sample_rate / 2) filterbanks = np.expand_dims(self.mel( sample_rate, self.n_fft, n_mels=self.nfilt, fmin=self.lowfreq, fmax=highfreq ), 0) x = image.data seq_len = x.shape[-1] # Calculate maximum sequence length max_length = np.ceil(self.max_duration * sample_rate / self.hop_length) max_pad = self.pad_to - (max_length % self.pad_to) if self.pad_to > 0 else 0 self.max_length = max_length + max_pad seq_len = int(np.ceil(seq_len // self.hop_length)) # dither if self.dither > 0: x = x + self.dither * np.random.randn(*x.shape) # do preemphasis if self.preemph is not None: x = np.concatenate((np.expand_dims(x[:, 0], 1), x[:, 1:] - self.preemph * x[:, :-1]), axis=1, ) x = self.stft( x.squeeze(), n_fft=self.n_fft, hop_length=self.hop_length, window=self.window, center=True, dtype=np.float32 ) # get power spectrum if self.mag_power != 1.0: x = x**self.mag_power # dot with filterbank energies x = np.matmul(filterbanks, x) # log features if required if self.log: x = np.log(x + self.log_zero_guard_value) # frame splicing if required if self.frame_splicing > 1: x = self.splice_frames(x, self.frame_splicing) # normalize if required if self.normalize: x = self.normalize_batch(x, seq_len, normalize_type=self.normalize) # mask to zero any values beyond seq_len in batch, pad to multiple of # `pad_to` (for efficiency) max_len = x.shape[-1] mask = np.arange(max_len) mask = mask >= seq_len x[:, :, mask] = self.pad_value del mask pad_to = self.pad_to if pad_to > 0: pad_amt = x.shape[-1] % pad_to if pad_amt != 0: x = np.pad(x, ((0, 0), (0, 0), (0, pad_to - pad_amt)), constant_values=self.pad_value, mode='constant') image.data = x return image def mel(self, sr, n_fft, n_mels=128, fmin=0.0, fmax=None, dtype=np.float32): if fmax is None: fmax = float(sr) / 2 n_mels = int(n_mels) weights = np.zeros((n_mels, int(1 + n_fft // 2)), dtype=dtype) # Center freqs of each FFT bin fftfreqs = np.linspace(0, float(sr) / 2, int(1 + n_fft // 2), endpoint=True) # 'Center freqs' of mel bands - uniformly spaced between limits mel_f = self.mel_frequencies(n_mels + 2, fmin=fmin, fmax=fmax) fdiff = np.diff(mel_f) ramps = np.subtract.outer(mel_f, fftfreqs) for i in range(n_mels): # lower and upper slopes for all bins lower = -ramps[i] / fdiff[i] upper = ramps[i + 2] / fdiff[i + 1] # .. then intersect them with each other and zero weights[i] = np.maximum(0, np.minimum(lower, upper)) # Slaney-style mel is scaled to be approx constant energy per channel enorm = 2.0 / (mel_f[2:n_mels + 2] - mel_f[:n_mels]) weights *= enorm[:, np.newaxis] return weights @staticmethod def mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0): def hz_to_mel(frequencies): frequencies = np.asanyarray(frequencies) f_min = 0.0 f_sp = 200.0 / 3 mels = (frequencies - f_min) / f_sp min_log_hz = 1000.0 min_log_mel = (min_log_hz - f_min) / f_sp logstep = np.log(6.4) / 27.0 if frequencies.ndim: log_t = (frequencies >= min_log_hz) mels[log_t] = min_log_mel + np.log(frequencies[log_t] / min_log_hz) / logstep elif frequencies >= min_log_hz: mels = min_log_mel + np.log(frequencies / min_log_hz) / logstep return mels def mel_to_hz(mels): mels = np.asanyarray(mels) f_min = 0.0 f_sp = 200.0 / 3 freqs = f_min + f_sp * mels min_log_hz = 1000.0 min_log_mel = (min_log_hz - f_min) / f_sp logstep = np.log(6.4) / 27.0 if mels.ndim: log_t = (mels >= min_log_mel) freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel)) elif mels >= min_log_mel: freqs = min_log_hz * np.exp(logstep * (mels - min_log_mel)) return freqs min_mel = hz_to_mel(fmin) max_mel = hz_to_mel(fmax) mels = np.linspace(min_mel, max_mel, n_mels) return mel_to_hz(mels) @staticmethod def stft(y, n_fft, hop_length, window, center=True, dtype=np.complex64, pad_mode='reflect'): # Constrain STFT block sizes to 256 KB MAX_MEM_BLOCK = 2 ** 8 * 2 ** 10 def pad_center(data, size, axis=-1, **kwargs): kwargs.setdefault('mode', 'constant') n = data.shape[axis] lpad = int((size - n) // 2) lengths = [(0, 0)] * data.ndim lengths[axis] = (lpad, int(size - n - lpad)) return np.pad(data, lengths, **kwargs) def frame(x, frame_length=2048, hop_length=512): '''Slice a data array into (overlapping) frames.''' n_frames = (x.shape[-1] - frame_length) // hop_length strides = np.asarray(x.strides) new_stride = np.prod(strides[strides > 0] // x.itemsize) * x.itemsize shape = list(x.shape)[:-1] + [frame_length, n_frames] strides = list(strides) + [hop_length * new_stride] return np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides) fft_window = np.asarray(window) # Pad the window out to n_fft size fft_window = pad_center(fft_window, n_fft) # Reshape so that the window can be broadcast fft_window = fft_window.reshape((-1, 1)) # # Pad the time series so that frames are centered if center: y = np.pad(y, int(n_fft // 2), mode=pad_mode) # Window the time series. y_frames = frame(y, frame_length=n_fft, hop_length=hop_length) # Pre-allocate the STFT matrix stft_matrix = np.empty((int(1 + n_fft // 2), y_frames.shape[1]), dtype=dtype, order='F') # how many columns can we fit within MAX_MEM_BLOCK? n_columns = int(MAX_MEM_BLOCK / (stft_matrix.shape[0] * stft_matrix.itemsize)) for bl_s in range(0, stft_matrix.shape[1], n_columns): bl_t = min(bl_s + n_columns, stft_matrix.shape[1]) # RFFT and Conjugate here to match phase from DPWE code rfft = fft_window * y_frames[:, bl_s:bl_t] stft_matrix[:, bl_s:bl_t] = np.fft.rfft(rfft, axis=0)[:stft_matrix.shape[0]] return stft_matrix @staticmethod def splice_frames(x, frame_splicing): seq = [x] for n in range(1, frame_splicing): seq.append(np.concatenate([x[:, :, :n], x[:, :, n:]], axis=2)) return np.concatenate(seq, axis=1) @staticmethod def normalize_batch(x, seq_len, normalize_type): if normalize_type == "per_feature": x_mean = np.zeros((x.shape[0], x.shape[1]), dtype=x.dtype) x_std = np.zeros((x.shape[0], x.shape[1]), dtype=x.dtype) for i in range(x.shape[0]): x_mean[i, :] = x[i, :seq_len].mean(axis=1) x_std[i, :] = x[i, :seq_len].std(axis=1) # make sure x_std is not zero x_std += 1e-5 return (x - np.expand_dims(x_mean, 2)) / np.expand_dims(x_std, 2) if normalize_type == "all_features": x_mean = np.zeros(seq_len, dtype=x.dtype) x_std = np.zeros(seq_len, dtype=x.dtype) for i in range(x.shape[0]): x_mean[i] = x[i, :, : seq_len[i].item()].mean() x_std[i] = x[i, :, : seq_len[i].item()].std() # make sure x_std is not zero x_std += 1e-5 return x - np.reshape(x_mean, (-1, 1, 1)) / np.reshape(x_std, (-1, 1, 1)) return x
import sys import yaml from collections import OrderedDict def represent_ordereddict(dumper, data): value = [] for item_key, item_value in data.items(): node_key = dumper.represent_data(item_key) node_value = dumper.represent_data(item_value) value.append((node_key, node_value)) return yaml.nodes.MappingNode(u'tag:yaml.org,2002:map', value) yaml.add_representer(OrderedDict, represent_ordereddict) class Regexp(yaml.YAMLObject): yaml_tag = u'!re_match' def __init__(self, regexp): self.regexp = regexp # def __repr__(self): # return "" % ( # self.__class__.__name__, self.name, self.hp, self.ac, self.attacks) old_test = sys.argv[1] new_tests_list = [] with open(old_test) as f: content = yaml.safe_load(f.read()) for test in content: # print(test) new_test = OrderedDict() for test_name, test_data in test.items(): new_test['test_name'] = test_name new_test['strict'] = False new_test['marks'] = [{'usefixtures': ['django_live_url']}] new_stages = [{'type': 'ref', 'id': 'signup'}] for stage in test_data: for url, stage_data in stage.items(): request_data = {'url': '{{django_live_url}}{url}'.format(url=url), 'method': stage_data['method']} content_type = stage_data.get('content_type', None) if 'data' in stage_data: if isinstance(stage_data['data'], dict): for k, v in stage_data['data'].items(): if isinstance(v, str) and 'samples' in v: if 'files' not in request_data: request_data['files'] = {} request_data['files'][k] = f'tests/test_suites/{v}' else: if content_type and 'json' in content_type: if 'json' not in request_data: request_data['json'] = {} request_data['json'][k] = v else: if 'data' not in request_data: request_data['data'] = {} request_data['data'][k] = v else: if content_type and 'json' in content_type: request_data['json'] = stage_data['data'] else: request_data['data'] = stage_data['data'] if 'content_type' in stage_data: request_data['headers'] = {'content-type': stage_data['content_type']} response_data = {'status_code': stage_data['status_code']} if 'response' in stage_data and isinstance(stage_data['response'], dict): for k, v in stage_data['response'].items(): if isinstance(v, str) and v.startswith('{'): if not 'save' in response_data: response_data['save'] = {'json': {}} key = v.replace('{', '').replace('}', '') response_data['save']['json'][key] = k else: if not 'json' in response_data: response_data['json'] = {} response_data['json'][k] = v new_stages.append( { 'name': 'stage', 'request': request_data, 'response': response_data, } ) new_test['stages'] = new_stages new_tests_list.append(new_test) for test in new_tests_list: print('---') print(yaml.dump(test))
<reponame>Sveder/advent_of_code input = """plaid fuchsia bags contain 5 light violet bags, 1 light yellow bag. striped aqua bags contain 2 striped teal bags. clear coral bags contain 2 plaid green bags, 5 mirrored gold bags. dull tan bags contain 4 faded blue bags, 3 faded olive bags, 5 dull salmon bags. plaid green bags contain 3 faded green bags. light tomato bags contain 1 drab chartreuse bag, 1 dotted tomato bag, 3 striped red bags, 2 vibrant violet bags. dim tomato bags contain 4 striped gold bags, 5 bright lavender bags, 1 pale beige bag, 4 pale tan bags. vibrant green bags contain 4 faded teal bags. shiny crimson bags contain 2 dull green bags. vibrant black bags contain 5 dark beige bags, 3 dark bronze bags. light tan bags contain 1 striped tomato bag. vibrant teal bags contain 1 shiny silver bag. pale chartreuse bags contain 2 dotted plum bags. plaid coral bags contain 2 pale green bags, 2 faded tomato bags, 2 dark salmon bags, 1 vibrant magenta bag. dull gray bags contain 1 dark tan bag, 3 dotted tan bags. muted gray bags contain 5 bright indigo bags, 5 dotted purple bags. vibrant red bags contain 4 bright tomato bags, 4 shiny orange bags. faded tan bags contain 1 dull crimson bag, 5 faded red bags. pale magenta bags contain 3 posh chartreuse bags, 4 vibrant purple bags. shiny gray bags contain 2 wavy purple bags. light crimson bags contain 5 clear teal bags. striped turquoise bags contain 3 pale tomato bags, 2 posh teal bags. striped purple bags contain 4 dark silver bags, 4 vibrant gray bags, 2 dim bronze bags, 2 clear aqua bags. muted magenta bags contain 4 striped tomato bags. light teal bags contain 2 faded brown bags, 2 posh purple bags, 1 faded olive bag. clear cyan bags contain 1 clear coral bag, 5 clear aqua bags. dull cyan bags contain 5 wavy crimson bags, 1 pale orange bag. shiny tan bags contain 2 bright red bags, 4 plaid cyan bags. light brown bags contain 3 dim yellow bags, 4 dull orange bags, 1 vibrant yellow bag. pale tan bags contain 2 striped orange bags, 5 dull plum bags. wavy salmon bags contain 2 dark blue bags, 5 dim plum bags. mirrored cyan bags contain 2 plaid turquoise bags, 5 dull plum bags, 3 muted indigo bags, 2 plaid white bags. dark aqua bags contain 3 bright red bags, 2 wavy purple bags, 2 plaid tan bags. wavy purple bags contain 5 wavy brown bags. clear magenta bags contain 4 muted green bags, 3 dull cyan bags, 4 striped teal bags, 2 faded blue bags. bright red bags contain 5 vibrant tomato bags, 2 dull orange bags. pale purple bags contain 3 plaid turquoise bags, 4 light tan bags, 1 faded black bag, 5 light yellow bags. bright orange bags contain 1 mirrored orange bag, 2 faded bronze bags, 1 wavy turquoise bag, 1 bright yellow bag. faded lavender bags contain 1 plaid brown bag. dark salmon bags contain 3 dotted crimson bags, 1 posh bronze bag. mirrored coral bags contain 3 dark red bags, 1 dull fuchsia bag, 2 drab magenta bags, 4 dull indigo bags. clear black bags contain 5 mirrored salmon bags, 3 drab gold bags, 3 muted fuchsia bags. faded fuchsia bags contain 1 shiny silver bag, 2 posh orange bags, 5 plaid bronze bags. dotted red bags contain 4 faded yellow bags, 5 dull brown bags, 3 clear red bags. light purple bags contain 2 plaid magenta bags, 3 vibrant coral bags, 2 wavy black bags. faded beige bags contain no other bags. dull fuchsia bags contain 3 dim lavender bags, 1 dull aqua bag, 2 pale fuchsia bags. wavy olive bags contain 5 dotted cyan bags, 1 dull lime bag. dim teal bags contain 1 dull green bag. dull orange bags contain 5 striped tomato bags, 5 drab blue bags, 5 faded blue bags, 2 pale brown bags. muted brown bags contain 3 dotted orange bags, 1 bright tan bag. vibrant coral bags contain 2 wavy turquoise bags. clear aqua bags contain 5 posh bronze bags, 5 dim orange bags, 5 posh chartreuse bags. dull plum bags contain 4 drab tan bags. wavy tomato bags contain 4 wavy cyan bags, 1 bright silver bag, 3 dotted gray bags, 1 dark tomato bag. shiny fuchsia bags contain 1 dotted silver bag, 5 dull lime bags, 3 drab teal bags. pale fuchsia bags contain 3 pale beige bags. plaid plum bags contain 4 dotted plum bags, 1 mirrored brown bag, 3 dim yellow bags, 2 vibrant bronze bags. posh green bags contain 5 plaid indigo bags, 1 wavy red bag, 5 dim indigo bags, 4 wavy indigo bags. muted aqua bags contain 3 bright tan bags, 3 dull yellow bags, 1 faded blue bag. mirrored white bags contain 5 dark coral bags, 1 plaid red bag, 4 dull violet bags, 5 clear gray bags. dotted aqua bags contain 4 drab aqua bags, 3 faded tomato bags. bright indigo bags contain 4 faded tan bags, 3 clear turquoise bags, 1 plaid indigo bag, 4 bright gray bags. posh silver bags contain 5 striped red bags, 3 faded blue bags, 3 dim plum bags, 3 vibrant beige bags. bright olive bags contain 3 dull silver bags, 5 drab tomato bags. muted beige bags contain 1 drab crimson bag. shiny beige bags contain 3 clear blue bags. wavy brown bags contain 2 striped coral bags, 2 light purple bags. wavy black bags contain 4 faded beige bags, 2 striped red bags, 2 pale brown bags, 3 dull yellow bags. faded salmon bags contain 1 light indigo bag, 5 plaid cyan bags, 2 pale salmon bags. dark gold bags contain 1 mirrored plum bag, 2 dark tomato bags, 5 dull green bags, 2 light lime bags. mirrored lavender bags contain 5 muted brown bags, 1 shiny blue bag, 5 dull blue bags, 3 wavy indigo bags. wavy beige bags contain 3 mirrored purple bags, 3 posh yellow bags, 4 plaid green bags. striped fuchsia bags contain 5 drab bronze bags, 4 posh tomato bags, 1 drab maroon bag, 1 dim beige bag. faded blue bags contain 1 striped tomato bag, 3 dark olive bags, 2 drab tan bags. drab gray bags contain 1 posh teal bag. dim cyan bags contain 4 dark fuchsia bags, 3 wavy maroon bags, 5 posh silver bags, 4 posh chartreuse bags. dotted purple bags contain 3 wavy white bags. shiny brown bags contain 5 light silver bags, 4 light turquoise bags, 4 posh bronze bags. vibrant tomato bags contain 3 dotted cyan bags, 3 posh teal bags, 1 clear magenta bag, 5 dull lime bags. dark bronze bags contain 2 vibrant maroon bags, 2 mirrored olive bags. wavy silver bags contain 4 striped magenta bags, 3 dim fuchsia bags. striped yellow bags contain 5 faded black bags, 5 light beige bags, 1 vibrant beige bag, 2 mirrored beige bags. faded chartreuse bags contain 4 clear gray bags, 5 dotted gray bags. faded tomato bags contain 5 faded gray bags, 4 faded fuchsia bags, 3 drab teal bags. dull gold bags contain 1 dark plum bag, 4 striped black bags. muted turquoise bags contain 1 mirrored bronze bag, 5 shiny aqua bags, 1 clear plum bag. dotted lime bags contain 1 dark black bag, 5 pale brown bags. vibrant violet bags contain 5 faded lime bags, 1 pale fuchsia bag, 5 dull plum bags. faded black bags contain 2 striped teal bags, 5 faded beige bags, 4 wavy black bags, 1 striped lavender bag. drab teal bags contain 1 clear gold bag, 4 muted crimson bags, 1 light teal bag. dull purple bags contain 1 posh crimson bag, 2 clear blue bags. dotted teal bags contain 2 dark tan bags. dark red bags contain 3 dotted cyan bags, 3 posh red bags, 2 bright red bags, 3 faded magenta bags. light black bags contain 5 dull yellow bags. light salmon bags contain 3 faded beige bags. dull brown bags contain 1 light indigo bag, 4 mirrored yellow bags, 5 faded silver bags. dark black bags contain 5 dull yellow bags, 3 dull lime bags, 5 posh aqua bags. faded crimson bags contain 3 light fuchsia bags, 5 muted chartreuse bags. drab yellow bags contain 5 drab indigo bags, 2 shiny brown bags, 4 muted lime bags. muted tomato bags contain 3 posh salmon bags, 2 plaid indigo bags, 5 striped aqua bags. pale teal bags contain 2 muted red bags, 5 mirrored brown bags, 4 mirrored tan bags. posh violet bags contain 4 posh tomato bags. dim plum bags contain 1 faded magenta bag, 5 drab silver bags, 1 pale brown bag. light fuchsia bags contain 2 dotted silver bags, 3 dotted lavender bags, 3 shiny gold bags, 5 clear magenta bags. vibrant orange bags contain 5 shiny blue bags, 5 dull maroon bags. shiny white bags contain 5 mirrored yellow bags, 2 pale fuchsia bags, 4 shiny turquoise bags. drab green bags contain 1 mirrored lavender bag, 3 posh tan bags. faded silver bags contain 5 vibrant coral bags, 3 striped lavender bags, 4 dotted cyan bags, 5 plaid turquoise bags. faded gold bags contain 4 faded magenta bags. dark coral bags contain 3 light maroon bags, 1 drab silver bag. striped olive bags contain 4 dotted maroon bags, 3 wavy brown bags, 1 wavy crimson bag, 5 shiny silver bags. wavy lavender bags contain 3 mirrored yellow bags, 5 shiny crimson bags, 4 dark indigo bags. bright fuchsia bags contain 2 vibrant green bags, 5 drab blue bags. dotted turquoise bags contain 3 striped red bags. drab black bags contain 1 faded tan bag. pale silver bags contain 1 faded yellow bag, 1 drab tan bag, 5 muted salmon bags, 3 shiny white bags. striped magenta bags contain 4 dark turquoise bags, 4 shiny blue bags, 3 shiny crimson bags. dotted beige bags contain 2 mirrored black bags, 2 faded brown bags, 1 bright red bag, 2 clear coral bags. clear maroon bags contain 5 bright bronze bags. shiny olive bags contain 2 dull blue bags. pale violet bags contain 1 light purple bag, 1 pale tomato bag, 4 plaid aqua bags, 4 light magenta bags. dotted white bags contain 3 bright purple bags, 4 dull orange bags, 2 plaid salmon bags. plaid blue bags contain 5 faded blue bags, 4 muted green bags, 4 bright bronze bags. mirrored lime bags contain 1 faded green bag, 4 striped black bags, 1 mirrored purple bag. wavy violet bags contain 1 muted bronze bag. light silver bags contain 2 dull cyan bags, 1 drab tan bag. dark tomato bags contain 1 vibrant tomato bag, 1 striped tomato bag. wavy teal bags contain 5 wavy red bags, 2 drab brown bags, 1 posh olive bag. dim green bags contain 2 striped teal bags, 1 drab blue bag. wavy crimson bags contain no other bags. mirrored aqua bags contain 3 posh tan bags, 5 muted teal bags, 3 light violet bags. light cyan bags contain 4 vibrant chartreuse bags, 1 faded lime bag, 2 drab purple bags, 2 shiny white bags. shiny gold bags contain 4 drab blue bags, 4 posh purple bags, 2 drab silver bags, 4 wavy turquoise bags. plaid chartreuse bags contain 5 mirrored olive bags, 2 vibrant orange bags, 2 shiny purple bags. dim yellow bags contain 1 faded green bag, 4 wavy fuchsia bags. pale turquoise bags contain 1 drab turquoise bag. clear red bags contain 1 pale bronze bag, 4 drab tan bags. shiny teal bags contain 3 bright aqua bags. dotted tomato bags contain 3 dotted orange bags, 5 light silver bags, 2 dull green bags, 5 wavy chartreuse bags. striped tan bags contain 1 light turquoise bag, 2 dotted salmon bags, 4 shiny orange bags, 2 clear red bags. dim bronze bags contain 1 wavy gold bag. posh crimson bags contain 4 posh aqua bags. plaid salmon bags contain 2 dull tan bags. mirrored salmon bags contain 2 muted aqua bags, 5 muted salmon bags. striped blue bags contain 3 wavy white bags, 4 drab blue bags, 1 drab chartreuse bag, 4 dull orange bags. pale red bags contain 1 striped red bag. muted black bags contain 4 faded gold bags. clear orange bags contain 2 faded red bags. mirrored maroon bags contain 2 plaid tan bags. dull aqua bags contain 4 pale gold bags. posh coral bags contain 3 striped gold bags. posh purple bags contain 4 pale orange bags, 5 dull salmon bags, 2 striped teal bags. muted tan bags contain 3 clear coral bags, 4 pale salmon bags. mirrored orange bags contain 5 pale bronze bags. striped teal bags contain no other bags. dark blue bags contain no other bags. clear bronze bags contain 4 vibrant gray bags. light magenta bags contain 4 dim green bags. drab coral bags contain 5 dotted chartreuse bags, 4 vibrant crimson bags, 2 muted green bags. drab brown bags contain 2 dull tomato bags, 5 vibrant bronze bags. bright coral bags contain 1 posh plum bag, 1 wavy gold bag, 2 drab lavender bags, 2 muted lavender bags. dim white bags contain 4 shiny aqua bags. plaid bronze bags contain 4 drab tan bags, 3 plaid salmon bags, 4 striped coral bags. faded teal bags contain 1 vibrant white bag, 5 wavy purple bags. drab turquoise bags contain 3 pale tomato bags, 1 bright indigo bag. muted white bags contain 3 striped brown bags, 1 light blue bag. clear crimson bags contain 1 dark magenta bag. shiny magenta bags contain 4 wavy tomato bags, 4 shiny bronze bags, 4 vibrant coral bags, 5 bright lime bags. bright magenta bags contain 3 wavy brown bags. bright tomato bags contain 4 vibrant fuchsia bags, 1 clear aqua bag. wavy coral bags contain 4 striped gold bags, 1 light purple bag, 4 vibrant purple bags. muted indigo bags contain 2 posh purple bags, 2 light gold bags, 3 striped lavender bags. clear violet bags contain 2 wavy cyan bags, 5 pale brown bags, 4 faded magenta bags, 2 bright purple bags. dull white bags contain 4 wavy olive bags, 3 mirrored olive bags, 3 faded magenta bags, 4 dull green bags. dull magenta bags contain 4 dim beige bags. dotted blue bags contain 4 posh beige bags, 1 pale purple bag, 4 shiny red bags. dotted lavender bags contain 3 posh purple bags. light white bags contain 4 striped lavender bags. dark turquoise bags contain 5 light teal bags. faded turquoise bags contain 5 striped violet bags, 4 dull crimson bags, 2 dim purple bags, 1 light silver bag. striped chartreuse bags contain 3 pale white bags, 3 dim fuchsia bags. pale gold bags contain 2 clear teal bags, 3 wavy turquoise bags, 5 light gold bags. posh blue bags contain 4 muted yellow bags, 1 dull crimson bag, 3 wavy violet bags, 5 mirrored fuchsia bags. dotted gray bags contain 3 wavy fuchsia bags. plaid magenta bags contain 3 plaid black bags. pale beige bags contain 1 pale white bag, 2 dim salmon bags, 5 mirrored gold bags. striped bronze bags contain 2 dull yellow bags, 2 dark blue bags. dark lime bags contain 2 pale magenta bags, 4 clear cyan bags. bright turquoise bags contain 2 light white bags, 3 plaid salmon bags, 2 clear aqua bags, 5 dull silver bags. posh salmon bags contain 1 drab turquoise bag. muted bronze bags contain 1 pale bronze bag, 3 clear maroon bags. faded coral bags contain 1 clear gray bag, 5 plaid gray bags, 3 bright silver bags, 4 posh yellow bags. mirrored gray bags contain 1 dark coral bag, 2 plaid blue bags, 4 mirrored coral bags, 1 mirrored olive bag. vibrant olive bags contain 5 pale chartreuse bags, 4 plaid green bags, 4 dark coral bags. dotted magenta bags contain 4 light chartreuse bags, 3 plaid indigo bags, 2 dull tan bags. light violet bags contain 2 muted green bags. dim fuchsia bags contain 5 dim tan bags, 5 faded black bags, 1 drab white bag. dotted black bags contain 3 bright gold bags, 2 faded gold bags. striped indigo bags contain 3 posh aqua bags. posh cyan bags contain 5 dull fuchsia bags. vibrant turquoise bags contain 2 muted chartreuse bags, 2 clear magenta bags, 5 drab chartreuse bags. mirrored magenta bags contain 1 dull lime bag. mirrored violet bags contain 2 posh magenta bags, 1 plaid white bag, 4 wavy turquoise bags, 5 dull salmon bags. pale tomato bags contain 4 wavy maroon bags, 3 clear aqua bags, 2 striped lavender bags. clear fuchsia bags contain 5 dark cyan bags, 1 plaid cyan bag. drab orange bags contain 3 mirrored purple bags, 1 striped orange bag. bright blue bags contain 1 bright cyan bag, 4 plaid green bags. muted chartreuse bags contain 4 faded beige bags, 3 faded green bags. plaid teal bags contain 2 mirrored orange bags, 5 plaid plum bags. light blue bags contain 4 faded silver bags, 3 light turquoise bags, 2 dim aqua bags, 5 posh silver bags. bright tan bags contain 4 striped coral bags, 1 dark fuchsia bag. shiny black bags contain 1 light green bag. plaid violet bags contain 1 faded magenta bag, 1 shiny bronze bag, 2 vibrant tomato bags. posh bronze bags contain 4 shiny gold bags, 1 bright yellow bag, 1 dull cyan bag. light red bags contain 3 dotted black bags, 5 pale coral bags. striped red bags contain no other bags. clear tan bags contain 2 faded brown bags, 1 bright brown bag, 2 bright gold bags. dull turquoise bags contain 5 mirrored yellow bags, 3 wavy red bags, 5 faded purple bags, 4 clear green bags. plaid yellow bags contain 4 dark red bags, 3 dull tomato bags, 5 faded violet bags. dotted gold bags contain 2 dotted lime bags, 2 faded gray bags, 3 clear coral bags. dull bronze bags contain 2 pale red bags, 3 dim indigo bags. shiny green bags contain 2 pale red bags, 1 mirrored silver bag, 4 bright lime bags, 5 pale indigo bags. bright black bags contain 2 striped plum bags, 1 clear black bag, 4 clear olive bags. bright gold bags contain 3 wavy cyan bags, 1 dotted magenta bag, 1 muted salmon bag, 4 light maroon bags. muted violet bags contain 5 wavy cyan bags, 4 dim tan bags, 1 posh gray bag, 5 vibrant brown bags. dim turquoise bags contain 1 pale tomato bag, 2 dotted silver bags, 5 mirrored coral bags. drab lime bags contain 5 shiny gold bags. wavy bronze bags contain 1 shiny red bag, 4 dotted cyan bags. vibrant purple bags contain 4 drab chartreuse bags, 4 dotted yellow bags. plaid purple bags contain 2 drab beige bags, 3 pale aqua bags, 3 muted magenta bags. faded brown bags contain 3 faded beige bags, 1 light chartreuse bag, 4 mirrored gold bags. pale lavender bags contain 1 mirrored tomato bag, 5 wavy maroon bags, 4 wavy lime bags. posh fuchsia bags contain 5 posh orange bags. drab fuchsia bags contain 1 dim plum bag, 1 dark coral bag, 3 dark red bags. striped crimson bags contain 5 pale orange bags, 5 faded beige bags, 5 faded brown bags. wavy lime bags contain 5 dull crimson bags. vibrant fuchsia bags contain 2 wavy white bags. vibrant plum bags contain 4 dim salmon bags, 2 plaid tan bags, 3 dull blue bags. muted cyan bags contain 3 striped beige bags. clear teal bags contain 2 wavy aqua bags, 3 dotted plum bags. dark maroon bags contain 1 light violet bag, 3 clear plum bags, 5 dotted fuchsia bags, 2 vibrant tomato bags. dull black bags contain 5 muted olive bags. light yellow bags contain 1 dull white bag, 5 dark aqua bags, 3 light purple bags, 4 dim green bags. pale bronze bags contain 1 wavy aqua bag. plaid red bags contain 5 pale plum bags, 2 muted brown bags, 2 dull bronze bags. dim gray bags contain 2 muted lavender bags. plaid gray bags contain 5 muted aqua bags. vibrant blue bags contain 4 light tomato bags, 1 plaid beige bag. clear blue bags contain 5 clear plum bags, 5 drab chartreuse bags. dotted green bags contain 5 plaid white bags, 5 vibrant turquoise bags, 1 drab silver bag. dull crimson bags contain 3 mirrored yellow bags, 3 posh red bags, 3 faded brown bags. striped maroon bags contain 1 shiny magenta bag, 2 light brown bags, 4 dull green bags. dark yellow bags contain 4 faded silver bags, 5 shiny lavender bags, 4 dim crimson bags, 2 plaid bronze bags. pale indigo bags contain 4 plaid salmon bags, 3 striped purple bags, 5 pale magenta bags, 1 dotted lime bag. faded maroon bags contain 5 light silver bags, 5 dim bronze bags, 4 faded tan bags, 5 striped crimson bags. pale green bags contain 4 vibrant white bags. muted maroon bags contain 2 light black bags, 2 mirrored fuchsia bags. pale yellow bags contain 2 dull bronze bags, 4 bright maroon bags, 5 wavy cyan bags, 4 dotted lavender bags. posh white bags contain 3 mirrored turquoise bags, 3 shiny aqua bags, 2 striped blue bags, 4 faded coral bags. wavy orange bags contain 4 wavy crimson bags, 2 bright brown bags, 3 bright magenta bags, 1 dotted gold bag. dark beige bags contain 3 muted white bags. dotted salmon bags contain 5 dim bronze bags, 5 striped orange bags. dotted fuchsia bags contain 1 striped red bag, 4 bright purple bags. pale cyan bags contain 1 dull blue bag. mirrored purple bags contain 5 light turquoise bags, 2 faded silver bags. drab violet bags contain 1 vibrant turquoise bag, 2 muted chartreuse bags, 5 pale bronze bags. wavy gray bags contain 1 dark purple bag, 4 muted green bags. wavy magenta bags contain 5 dark white bags, 4 vibrant black bags, 4 muted coral bags. pale plum bags contain 5 mirrored brown bags, 2 pale red bags. light plum bags contain 4 dark tomato bags, 4 wavy gold bags. pale aqua bags contain 1 striped red bag, 2 dim crimson bags, 3 mirrored orange bags. muted green bags contain 1 mirrored yellow bag. bright purple bags contain 5 light violet bags, 5 clear magenta bags, 1 faded lime bag. dark green bags contain 2 shiny aqua bags. dark orange bags contain 3 striped coral bags. dotted chartreuse bags contain 1 bright lime bag, 1 light olive bag, 4 muted red bags, 1 posh chartreuse bag. shiny chartreuse bags contain 1 bright salmon bag, 1 plaid indigo bag. clear gold bags contain 5 dull lime bags, 4 shiny brown bags, 1 dull plum bag, 4 dull salmon bags. shiny salmon bags contain 2 muted salmon bags, 2 dotted lavender bags. striped cyan bags contain 3 drab tan bags, 5 dotted cyan bags, 1 posh aqua bag, 1 plaid magenta bag. dark plum bags contain 1 clear orange bag, 2 striped black bags. vibrant magenta bags contain 1 plaid tan bag, 3 muted bronze bags, 3 bright chartreuse bags. clear beige bags contain 4 muted tan bags, 1 clear turquoise bag, 4 mirrored turquoise bags, 2 bright silver bags. drab lavender bags contain 1 dotted cyan bag, 4 clear plum bags. shiny coral bags contain 2 drab beige bags. light bronze bags contain 2 mirrored plum bags, 2 light black bags. vibrant yellow bags contain 4 vibrant coral bags, 5 mirrored olive bags, 1 light lime bag, 2 muted crimson bags. vibrant salmon bags contain 4 faded beige bags, 2 faded olive bags, 1 pale brown bag. dim tan bags contain 3 faded beige bags, 4 light tan bags. vibrant silver bags contain 1 dark tomato bag. striped salmon bags contain 5 faded brown bags. shiny purple bags contain 1 pale lavender bag, 3 plaid black bags, 1 drab indigo bag. light turquoise bags contain 4 dark silver bags. dark chartreuse bags contain 5 dark silver bags. mirrored indigo bags contain 5 mirrored gold bags, 1 dotted white bag. faded olive bags contain 1 pale brown bag, 3 faded beige bags, 2 light chartreuse bags. mirrored black bags contain 5 posh purple bags. clear green bags contain 2 dark magenta bags, 5 faded gold bags, 4 striped teal bags, 4 dark purple bags. bright beige bags contain 3 light olive bags, 3 wavy orange bags, 4 dotted lavender bags. plaid brown bags contain 4 dull lavender bags, 3 drab gold bags. vibrant chartreuse bags contain 1 bright bronze bag, 5 wavy crimson bags. posh aqua bags contain 5 muted green bags, 2 dim green bags, 1 dim crimson bag, 1 posh red bag. vibrant gold bags contain 5 wavy chartreuse bags, 3 drab gold bags, 2 striped blue bags, 3 posh yellow bags. posh tan bags contain 1 shiny chartreuse bag, 2 drab bronze bags. bright violet bags contain 1 pale lavender bag, 5 mirrored olive bags, 1 posh turquoise bag. faded lime bags contain 5 pale brown bags, 4 faded black bags, 1 faded beige bag. vibrant gray bags contain 3 vibrant chartreuse bags, 3 bright purple bags. dull silver bags contain 5 pale tomato bags, 5 shiny turquoise bags, 2 mirrored yellow bags. pale maroon bags contain 3 posh red bags, 1 plaid bronze bag, 5 striped red bags. dull lavender bags contain 4 vibrant violet bags, 1 bright yellow bag, 3 bright aqua bags. light aqua bags contain 5 vibrant turquoise bags. striped violet bags contain 4 drab silver bags, 3 posh magenta bags, 3 wavy turquoise bags. bright green bags contain 3 drab teal bags. light coral bags contain 5 dotted violet bags, 4 pale chartreuse bags. muted salmon bags contain 4 vibrant turquoise bags, 5 clear chartreuse bags, 1 dark fuchsia bag, 5 bright bronze bags. wavy cyan bags contain 4 dim orange bags, 1 dull orange bag, 4 plaid indigo bags, 4 dim salmon bags. shiny red bags contain 1 dim blue bag, 4 clear plum bags. vibrant beige bags contain 3 posh red bags. shiny maroon bags contain 3 striped tomato bags, 2 faded lime bags. shiny aqua bags contain 3 bright yellow bags. bright aqua bags contain 5 wavy lavender bags, 4 striped coral bags, 5 dotted cyan bags, 3 drab cyan bags. dim olive bags contain 2 posh blue bags, 5 vibrant violet bags, 3 drab brown bags, 1 dull purple bag. shiny silver bags contain 5 dim green bags, 4 dull cyan bags. dim brown bags contain 1 wavy brown bag, 3 drab black bags. dotted brown bags contain 3 drab crimson bags, 1 shiny red bag. striped coral bags contain 4 striped red bags, 1 dotted cyan bag. dotted plum bags contain 3 faded lime bags, 2 striped lavender bags, 2 wavy crimson bags, 2 faded brown bags. light gold bags contain 1 light silver bag, 3 posh teal bags, 3 dark orange bags, 4 bright bronze bags. dark tan bags contain 5 drab black bags, 2 plaid cyan bags, 3 faded yellow bags, 1 dim blue bag. posh olive bags contain 4 drab olive bags, 5 dull tan bags, 1 wavy chartreuse bag, 5 muted magenta bags. dull red bags contain 1 vibrant teal bag, 4 dim salmon bags, 1 bright violet bag, 1 dark lavender bag. plaid turquoise bags contain 3 faded green bags, 5 wavy crimson bags. plaid cyan bags contain 2 dull yellow bags, 2 dotted cyan bags, 1 light chartreuse bag, 2 faded green bags. dull indigo bags contain 2 faded silver bags. pale brown bags contain no other bags. striped plum bags contain 5 dull lime bags, 2 muted white bags, 3 striped teal bags. dotted coral bags contain 4 faded silver bags, 2 wavy aqua bags, 2 light chartreuse bags, 5 posh indigo bags. mirrored beige bags contain 1 plaid black bag, 2 plaid tan bags, 2 pale bronze bags. vibrant cyan bags contain 4 wavy beige bags, 1 shiny orange bag. wavy fuchsia bags contain 5 pale maroon bags, 3 drab violet bags, 2 shiny orange bags. drab silver bags contain 2 dark blue bags, 3 light chartreuse bags, 3 mirrored gold bags. wavy turquoise bags contain 5 posh red bags, 4 striped teal bags. bright cyan bags contain 4 bright silver bags, 1 muted gray bag, 5 faded aqua bags, 3 wavy aqua bags. wavy green bags contain 4 clear violet bags, 4 dark olive bags, 2 clear magenta bags, 1 mirrored black bag. mirrored gold bags contain 2 dark olive bags. wavy gold bags contain 4 plaid indigo bags. dotted yellow bags contain 3 dull orange bags, 2 faded green bags. light beige bags contain 4 dull cyan bags. bright crimson bags contain 1 faded tan bag, 1 faded chartreuse bag, 5 vibrant brown bags. dotted bronze bags contain 5 striped white bags. mirrored yellow bags contain 3 wavy crimson bags, 4 dark olive bags, 5 drab tan bags. plaid lavender bags contain 1 light tomato bag, 5 dull blue bags, 2 wavy indigo bags, 3 bright gray bags. drab purple bags contain 3 dotted plum bags, 5 drab olive bags, 1 drab tan bag, 3 dark black bags. shiny lime bags contain 2 plaid bronze bags, 1 shiny gold bag. drab chartreuse bags contain 2 bright bronze bags, 4 light teal bags, 1 mirrored yellow bag. bright plum bags contain 3 drab turquoise bags. light orange bags contain 1 shiny lavender bag, 2 dark fuchsia bags, 1 muted olive bag, 4 wavy olive bags. striped beige bags contain 4 dull crimson bags, 5 dotted fuchsia bags. wavy chartreuse bags contain 2 bright salmon bags, 5 faded green bags, 1 mirrored black bag. striped tomato bags contain no other bags. plaid aqua bags contain 1 light magenta bag, 3 pale white bags, 3 clear blue bags, 4 dull crimson bags. plaid tan bags contain 3 dull green bags, 1 light silver bag, 5 dim orange bags, 1 dark blue bag. dotted cyan bags contain 2 wavy black bags, 3 striped teal bags. dull green bags contain 1 plaid magenta bag, 3 dull plum bags, 4 dim green bags. faded purple bags contain 5 mirrored cyan bags, 1 dull beige bag, 4 vibrant purple bags. dotted maroon bags contain 1 vibrant beige bag, 3 plaid magenta bags. faded aqua bags contain 4 plaid gold bags, 1 plaid yellow bag, 2 bright lime bags. pale lime bags contain 1 light blue bag. dark indigo bags contain 1 light gold bag. shiny orange bags contain 2 plaid black bags, 2 faded brown bags, 4 plaid indigo bags. muted olive bags contain 1 wavy chartreuse bag. muted purple bags contain 4 dotted silver bags. plaid black bags contain 3 drab silver bags. striped lavender bags contain 5 wavy crimson bags. posh chartreuse bags contain 5 drab chartreuse bags. clear purple bags contain 3 faded green bags, 2 bright gold bags. dark crimson bags contain 4 plaid teal bags, 4 muted cyan bags. clear silver bags contain 3 pale beige bags, 2 mirrored tomato bags. dotted indigo bags contain 2 dark plum bags, 2 clear magenta bags, 3 light olive bags. dull chartreuse bags contain 2 light turquoise bags, 3 drab brown bags. bright brown bags contain 4 light purple bags, 1 vibrant coral bag. dim salmon bags contain 2 dull salmon bags. muted lime bags contain 4 muted violet bags, 5 shiny white bags. vibrant lime bags contain 2 mirrored bronze bags, 1 dotted crimson bag, 5 dim yellow bags, 2 mirrored gold bags. muted silver bags contain 1 striped orange bag, 3 drab purple bags. mirrored bronze bags contain 4 dull bronze bags. light olive bags contain 4 mirrored olive bags, 2 dim lime bags, 1 clear magenta bag. vibrant tan bags contain 2 shiny teal bags. posh red bags contain 2 bright bronze bags, 5 striped teal bags, 5 faded beige bags, 4 faded olive bags. faded red bags contain 4 striped lavender bags, 4 posh red bags. mirrored brown bags contain 3 dim salmon bags, 4 drab chartreuse bags, 1 wavy tomato bag. dark gray bags contain 1 muted tan bag, 4 faded blue bags, 2 dim chartreuse bags. dark white bags contain 4 vibrant lime bags, 4 pale olive bags. striped silver bags contain 4 dim cyan bags. clear salmon bags contain 5 pale magenta bags, 1 mirrored salmon bag. pale white bags contain 5 wavy crimson bags, 4 plaid indigo bags, 5 striped crimson bags, 3 drab violet bags. vibrant indigo bags contain 1 mirrored gold bag, 1 striped turquoise bag, 3 posh beige bags. drab aqua bags contain 5 faded crimson bags, 3 wavy gold bags, 3 striped tomato bags. clear brown bags contain 5 bright lavender bags. posh indigo bags contain 5 mirrored red bags, 5 clear coral bags. posh black bags contain 4 dim fuchsia bags, 5 muted olive bags, 3 mirrored red bags. shiny lavender bags contain 2 muted aqua bags, 3 striped black bags, 3 wavy salmon bags, 3 mirrored purple bags. vibrant bronze bags contain 1 bright tan bag, 5 faded beige bags, 5 pale red bags, 1 plaid cyan bag. clear chartreuse bags contain 2 shiny gold bags, 1 wavy turquoise bag, 2 muted crimson bags. drab tan bags contain no other bags. posh gold bags contain 5 dotted beige bags, 1 striped crimson bag, 5 drab purple bags, 1 bright gray bag. clear olive bags contain 3 dark tomato bags. dim aqua bags contain 4 wavy black bags, 5 clear chartreuse bags, 5 clear aqua bags. pale coral bags contain 2 shiny orange bags, 5 dark black bags, 3 vibrant coral bags. drab blue bags contain 5 dull salmon bags. vibrant white bags contain 2 mirrored yellow bags. faded indigo bags contain 5 clear aqua bags. posh turquoise bags contain 1 light purple bag, 4 mirrored salmon bags. dotted orange bags contain 5 dark blue bags, 1 shiny lavender bag, 2 dim plum bags, 3 clear violet bags. muted crimson bags contain 4 wavy crimson bags, 1 light magenta bag, 3 clear plum bags. dim coral bags contain 1 vibrant red bag, 2 vibrant magenta bags. mirrored plum bags contain 5 light olive bags. dull violet bags contain 2 dim aqua bags. faded violet bags contain 5 clear violet bags, 5 muted indigo bags, 3 clear red bags, 1 posh tan bag. vibrant crimson bags contain 1 shiny crimson bag. muted plum bags contain 3 drab beige bags, 4 posh maroon bags. dim orange bags contain 5 bright salmon bags. dim blue bags contain 1 mirrored black bag, 3 faded blue bags. mirrored tan bags contain 5 plaid plum bags. pale crimson bags contain 4 dim green bags, 2 pale fuchsia bags. bright white bags contain 2 drab gold bags, 2 shiny maroon bags, 5 mirrored lime bags. dim indigo bags contain 1 mirrored cyan bag, 1 wavy purple bag, 1 drab brown bag. dotted violet bags contain 4 bright teal bags, 2 vibrant plum bags. wavy indigo bags contain 2 drab silver bags, 1 muted chartreuse bag, 1 drab aqua bag, 3 mirrored teal bags. dark cyan bags contain 1 muted magenta bag, 3 vibrant violet bags, 4 mirrored aqua bags, 5 drab violet bags. posh maroon bags contain 5 muted chartreuse bags, 4 dark olive bags. drab tomato bags contain 2 plaid tan bags, 2 posh purple bags, 2 posh beige bags. wavy tan bags contain 5 light cyan bags, 5 muted brown bags, 5 mirrored coral bags, 5 light chartreuse bags. faded bronze bags contain 4 dotted magenta bags. pale blue bags contain 5 pale purple bags. dim magenta bags contain 5 posh aqua bags, 5 dim crimson bags, 4 wavy gold bags, 2 shiny orange bags. dark fuchsia bags contain 2 drab silver bags. wavy white bags contain 4 vibrant turquoise bags, 2 clear violet bags, 1 dull salmon bag. drab maroon bags contain 3 pale tomato bags, 2 dim chartreuse bags, 5 mirrored orange bags, 4 drab violet bags. muted fuchsia bags contain 4 muted bronze bags, 4 plaid brown bags, 1 faded white bag. plaid gold bags contain 3 vibrant bronze bags, 5 striped chartreuse bags. faded green bags contain 2 dull cyan bags, 5 posh purple bags. light indigo bags contain 5 mirrored tomato bags. striped white bags contain 5 clear plum bags. posh magenta bags contain 5 wavy crimson bags, 3 striped coral bags. drab olive bags contain 4 striped orange bags. plaid indigo bags contain 1 plaid turquoise bag. dark brown bags contain 2 faded tan bags, 5 wavy green bags. faded cyan bags contain 2 bright violet bags, 3 mirrored salmon bags. dim lavender bags contain 2 mirrored fuchsia bags, 3 pale magenta bags, 2 dotted tan bags, 4 posh bronze bags. dull maroon bags contain 3 dark silver bags, 5 dim plum bags. dull teal bags contain 3 pale green bags. shiny yellow bags contain 4 dotted fuchsia bags. mirrored crimson bags contain 5 dotted plum bags. drab beige bags contain 3 faded orange bags, 3 dark orange bags, 4 clear orange bags. dull olive bags contain 2 vibrant bronze bags, 4 shiny chartreuse bags. wavy red bags contain 2 wavy brown bags, 1 wavy olive bag, 3 striped cyan bags. light gray bags contain 1 pale salmon bag, 2 plaid bronze bags, 5 dull yellow bags. faded gray bags contain 4 muted green bags, 5 faded red bags, 3 muted magenta bags, 5 bright magenta bags. drab indigo bags contain 1 posh gold bag, 2 dull lime bags, 1 pale orange bag. bright yellow bags contain 4 posh red bags, 4 shiny gold bags. drab bronze bags contain 4 dark indigo bags. striped gold bags contain 3 faded yellow bags, 2 mirrored tomato bags, 1 bright lime bag. muted gold bags contain 4 dim violet bags. plaid olive bags contain 3 wavy fuchsia bags. bright gray bags contain 4 bright bronze bags, 1 plaid white bag, 1 pale bronze bag. clear turquoise bags contain 2 mirrored purple bags, 2 light gold bags, 4 dim cyan bags, 5 wavy olive bags. wavy plum bags contain 4 bright yellow bags. dull blue bags contain 4 dotted lavender bags. posh gray bags contain 4 faded blue bags, 2 dull brown bags, 1 clear cyan bag. pale black bags contain 5 dim cyan bags, 4 bright white bags. wavy blue bags contain 3 faded olive bags, 5 bright lavender bags, 1 wavy black bag, 2 posh magenta bags. posh beige bags contain 2 light cyan bags, 1 wavy violet bag, 1 muted olive bag. clear plum bags contain 3 dull cyan bags. drab cyan bags contain 5 plaid green bags. vibrant aqua bags contain 5 posh maroon bags. dim silver bags contain 5 shiny gold bags, 5 posh magenta bags, 1 light white bag. posh brown bags contain 4 plaid salmon bags, 2 vibrant blue bags, 2 posh olive bags. dark teal bags contain 1 faded brown bag. clear white bags contain 5 vibrant tan bags, 5 light purple bags, 3 posh tan bags, 4 faded beige bags. dim maroon bags contain 2 plaid chartreuse bags, 1 dim gray bag, 2 drab gold bags, 5 light white bags. dull salmon bags contain 5 striped teal bags, 3 dark blue bags, 3 drab tan bags, 5 wavy crimson bags. dull coral bags contain 1 faded red bag, 2 shiny teal bags, 3 bright gray bags, 1 pale brown bag. dark violet bags contain 1 clear cyan bag, 4 mirrored beige bags, 2 vibrant turquoise bags. vibrant maroon bags contain 1 muted magenta bag, 3 muted olive bags, 2 shiny turquoise bags. posh orange bags contain 5 dark black bags, 3 pale maroon bags, 5 dull plum bags. clear indigo bags contain 4 faded tan bags, 3 clear orange bags, 1 vibrant aqua bag. clear gray bags contain 4 dull salmon bags, 5 dark magenta bags. shiny turquoise bags contain 4 muted green bags, 4 vibrant beige bags, 5 mirrored cyan bags, 4 striped blue bags. pale salmon bags contain 1 dark silver bag, 4 dim green bags. striped gray bags contain 3 dark lavender bags. dull yellow bags contain 2 dark blue bags, 4 striped tomato bags, 2 striped red bags, 3 pale brown bags. posh yellow bags contain 1 dull green bag, 1 dull plum bag. plaid white bags contain 3 plaid turquoise bags, 4 dotted cyan bags, 3 shiny gold bags, 5 clear plum bags. faded orange bags contain 1 dull silver bag, 4 clear gray bags, 1 posh tomato bag, 2 wavy yellow bags. dim violet bags contain 4 drab silver bags, 1 dull yellow bag, 3 faded blue bags. light green bags contain 3 drab gold bags, 4 wavy purple bags. dark magenta bags contain 2 light gold bags, 5 drab violet bags. dark purple bags contain 5 plaid beige bags. mirrored blue bags contain 2 plaid tan bags. dim lime bags contain 1 dotted beige bag, 2 striped white bags, 5 dim blue bags, 5 wavy blue bags. bright chartreuse bags contain 3 clear orange bags. vibrant brown bags contain 3 mirrored violet bags, 5 dull green bags, 2 pale magenta bags. drab salmon bags contain 4 muted magenta bags. muted teal bags contain 5 dark black bags, 5 light gold bags. striped lime bags contain 1 dim orange bag. plaid crimson bags contain 4 dim teal bags, 3 dull salmon bags. posh plum bags contain 5 pale gray bags. light maroon bags contain 4 drab violet bags, 2 faded brown bags, 2 striped black bags, 3 striped coral bags. pale gray bags contain 1 dark aqua bag, 3 mirrored tomato bags. light chartreuse bags contain no other bags. dim crimson bags contain 5 faded blue bags, 1 dark blue bag, 2 striped teal bags. dim beige bags contain 5 wavy silver bags, 1 wavy orange bag, 1 dim lime bag, 2 mirrored lime bags. bright teal bags contain 1 dull violet bag, 1 faded beige bag, 3 faded orange bags. striped green bags contain 2 drab gold bags, 5 posh olive bags, 4 light indigo bags, 1 clear yellow bag. striped black bags contain 4 striped crimson bags, 1 pale red bag. plaid beige bags contain 3 pale tomato bags. drab plum bags contain 4 striped coral bags, 3 dotted crimson bags. plaid orange bags contain 4 bright aqua bags. wavy maroon bags contain 1 dim orange bag, 1 dim violet bag, 4 posh chartreuse bags, 5 plaid tan bags. dim purple bags contain 1 mirrored black bag, 1 plaid plum bag, 4 striped teal bags, 1 posh aqua bag. mirrored red bags contain 2 shiny salmon bags, 3 bright salmon bags, 1 vibrant salmon bag. striped brown bags contain 3 light lime bags, 1 drab black bag, 2 dull white bags, 5 drab lavender bags. dim red bags contain 2 mirrored black bags. clear lavender bags contain 5 pale fuchsia bags. bright bronze bags contain 2 striped teal bags, 4 clear plum bags, 3 dim crimson bags, 5 faded black bags. shiny violet bags contain 2 dark gold bags, 3 posh maroon bags. bright lime bags contain 2 clear magenta bags, 3 dark blue bags, 4 striped lavender bags, 1 dull crimson bag. mirrored silver bags contain 1 vibrant tomato bag, 4 dull salmon bags, 5 plaid green bags, 4 wavy brown bags. dotted olive bags contain 5 faded beige bags. posh tomato bags contain 2 faded purple bags. posh teal bags contain 2 drab tan bags, 3 striped red bags, 3 dull salmon bags, 1 striped lavender bag. shiny tomato bags contain 3 posh indigo bags. dotted crimson bags contain 1 pale gray bag. shiny indigo bags contain 1 pale beige bag. plaid lime bags contain 1 light maroon bag. mirrored turquoise bags contain 5 faded bronze bags. drab crimson bags contain 1 vibrant plum bag. dim black bags contain 3 muted tan bags, 3 drab silver bags, 4 dull white bags. faded yellow bags contain 5 faded black bags. faded white bags contain 2 wavy lavender bags, 1 shiny orange bag. plaid tomato bags contain 2 shiny brown bags, 3 clear red bags. drab white bags contain 5 dark yellow bags. mirrored tomato bags contain 2 light gold bags, 1 mirrored gold bag, 4 dim plum bags. plaid maroon bags contain 2 mirrored lime bags, 3 plaid salmon bags, 2 shiny chartreuse bags. drab gold bags contain 1 dim plum bag, 2 mirrored violet bags. muted orange bags contain 3 mirrored lime bags, 1 muted maroon bag, 5 drab violet bags, 2 posh green bags. mirrored fuchsia bags contain 3 dim plum bags, 2 muted olive bags, 2 wavy white bags, 1 dotted cyan bag. plaid silver bags contain 3 pale violet bags, 5 striped purple bags, 5 dull purple bags. dotted silver bags contain 2 vibrant coral bags. shiny cyan bags contain 4 mirrored teal bags, 4 faded magenta bags, 4 bright lime bags, 1 vibrant teal bag. clear yellow bags contain 1 muted brown bag, 5 wavy lime bags. muted red bags contain 5 muted coral bags, 2 light violet bags, 2 muted indigo bags, 4 dotted tan bags. dull beige bags contain 5 plaid black bags, 2 pale white bags, 2 light violet bags, 1 pale crimson bag. vibrant lavender bags contain 3 dark chartreuse bags, 4 bright lavender bags. posh lime bags contain 1 shiny cyan bag, 4 dotted blue bags, 3 mirrored chartreuse bags. shiny blue bags contain 1 dotted magenta bag. muted yellow bags contain 4 plaid salmon bags, 4 dull tomato bags. muted blue bags contain 5 wavy magenta bags, 3 vibrant gray bags. dotted tan bags contain 1 wavy green bag, 1 dim plum bag. drab red bags contain 2 dark olive bags, 5 mirrored tan bags, 3 dull coral bags, 4 plaid yellow bags. dull tomato bags contain 2 clear aqua bags, 2 dark fuchsia bags, 2 light teal bags. bright salmon bags contain 5 dark blue bags. pale olive bags contain 1 light violet bag, 3 shiny bronze bags, 2 dotted magenta bags, 4 posh silver bags. mirrored teal bags contain 4 posh chartreuse bags, 5 vibrant bronze bags. mirrored chartreuse bags contain 3 striped olive bags, 3 mirrored maroon bags, 5 faded black bags, 3 pale plum bags. pale orange bags contain 4 mirrored gold bags, 3 faded brown bags, 2 dark olive bags. dark olive bags contain no other bags. faded plum bags contain 5 bright green bags, 5 shiny beige bags, 2 vibrant indigo bags, 1 mirrored orange bag. drab magenta bags contain 5 dark fuchsia bags, 5 striped salmon bags. dark lavender bags contain 5 mirrored red bags, 4 vibrant aqua bags, 2 dotted tan bags. shiny bronze bags contain 2 clear aqua bags, 2 dull salmon bags, 1 plaid turquoise bag, 3 plaid bronze bags. faded magenta bags contain 2 mirrored gold bags, 5 dim orange bags. light lavender bags contain 3 striped magenta bags, 5 light yellow bags. clear tomato bags contain 3 dark bronze bags, 5 plaid aqua bags, 2 faded lime bags, 2 bright salmon bags. clear lime bags contain 1 mirrored lavender bag, 3 bright silver bags, 3 pale teal bags. light lime bags contain 4 dim crimson bags, 2 vibrant tomato bags, 4 posh red bags. wavy yellow bags contain 3 muted chartreuse bags, 3 drab teal bags, 4 striped tomato bags. dark silver bags contain 5 posh magenta bags, 1 plaid black bag, 3 faded brown bags. bright maroon bags contain 5 dotted turquoise bags, 3 wavy silver bags, 2 dotted lime bags. striped orange bags contain 5 striped coral bags, 3 posh teal bags. bright silver bags contain 3 mirrored violet bags, 5 striped gold bags, 1 striped white bag, 4 clear chartreuse bags. mirrored olive bags contain 4 light silver bags, 1 muted crimson bag. dim gold bags contain 3 clear magenta bags. shiny plum bags contain 5 muted olive bags, 5 dark turquoise bags, 2 dull green bags, 1 plaid magenta bag. mirrored green bags contain 5 striped magenta bags, 1 light lime bag, 2 dim cyan bags. wavy aqua bags contain 4 dull tan bags, 5 vibrant beige bags. posh lavender bags contain 4 muted black bags. dull lime bags contain 2 plaid black bags. dim chartreuse bags contain 4 bright red bags. muted lavender bags contain 5 faded red bags, 5 drab brown bags, 5 clear bronze bags. muted coral bags contain 4 clear red bags, 3 vibrant maroon bags. bright lavender bags contain 4 striped blue bags.""" input = """light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags.""" # # input = """shiny gold bags contain 2 dark red bags. # dark red bags contain 2 dark orange bags. # dark orange bags contain 2 dark yellow bags. # dark yellow bags contain 2 dark green bags. # dark green bags contain 2 dark blue bags. # dark blue bags contain 2 dark violet bags. # dark violet bags contain no other bags.""" input = input.split("\n") class Bag(): def __init__(self, color, contents): self.color = color self.contents = contents # Contents is {color: count} def __str__(self): return "Bag of color %s, with content %s" % (self.color, self.contents) @staticmethod def parse_line(line): tokens = line.split(" ") color = " ".join(tokens[:2]) contents_part = line.split("contain ")[-1] contents = {} if "no other bags" not in contents_part: for content_desc in contents_part.split(", "): desc_parts = content_desc.split(" ") part_color = " ".join(desc_parts[1:3]) amounts = int(desc_parts[0]) contents[part_color] = amounts return Bag(color, contents) def get_all_content_colors(bag, all_bags): if bag.contents == {}: return [] result = list(bag.contents.keys()) for color in bag.contents.keys(): result += get_all_content_colors(all_bags[color], all_bags) return result bags = {} for line in input: bag = Bag.parse_line(line) bags[bag.color] = bag target = "shiny gold" container_count = 0 for bag_color, bag in bags.items(): all_containing = get_all_content_colors(bag, bags) if "shiny gold" in all_containing: container_count += 1 print("Container count:", container_count) def count_bags_in(bag, all_bags): if bag.contents == {}: return 1 result = 1 for color in bag.contents.keys(): result += bag.contents[color] * count_bags_in(all_bags[color], all_bags) return result print('Bag in shiny gold:', count_bags_in(bags["shiny gold"], bags))
import copy import logging import sys import typing from typing import Type import six from dbnd._core.configuration.dbnd_config import config from dbnd._core.current import get_databand_context from dbnd._core.errors import friendly_error from dbnd._core.plugin.dbnd_plugins import is_airflow_enabled from dbnd._core.utils.basics.singleton_context import SingletonContext from dbnd._core.utils.seven import contextlib from dbnd._vendor.snippets.luigi_registry import get_best_candidate, module_parents logger = logging.getLogger(__name__) if typing.TYPE_CHECKING: from dbnd._core.task.task import Task from dbnd._core.task_build.task_definition import TaskDefinition def _validate_no_recursion_in_config(task_name, config_task_type, param): if task_name == config_task_type: raise friendly_error.config.task_name_and_from_are_the_same(task_name, param) class DbndTaskRegistry(SingletonContext): """ Registry of all `dbnd` tasks """ AMBIGUOUS_CLASS = object() def __init__(self): self._fqn_to_task_cls = {} # map between full task class name and class self._task_family_to_task_cls = {} # map between task_family name and class # namespace management self._namespace_map = {} # airflow support self._dag_bag = None def register_task(self, task_cls): td = task_cls.task_definition # type: TaskDefinition self._fqn_to_task_cls[td.full_task_family] = task_cls if td.task_family in self._task_family_to_task_cls: task_cls = self.AMBIGUOUS_CLASS self._task_family_to_task_cls[td.task_family] = task_cls def _get_registered_task_cls(self, name): # type: (str) -> Type[Task] """ Returns an task class based on task_family, or full task class name We don't preload/check anything here """ task_cls = self._fqn_to_task_cls.get(name) if task_cls: return task_cls return self._task_family_to_task_cls.get(name) # used for both tasks and configurations def _get_task_cls(self, task_name): from dbnd._core.utils.basics.load_python_module import load_python_module task_cls = self._get_registered_task_cls(task_name) if task_cls: return task_cls # we are going to check if we have override/definition in config config_task_type = config.get(task_name, "_type", None) if config_task_type: _validate_no_recursion_in_config(task_name, config_task_type, "_type") try: return self._get_task_cls(config_task_type) except Exception: logger.error( "Failed to load type required by [%s] using _type=%s", task_name, config_task_type, ) raise config_task_type = config.get(task_name, "_from", None) if config_task_type: _validate_no_recursion_in_config(task_name, config_task_type, "_from") return self._get_task_cls(config_task_type) if "." in task_name: parts = task_name.split(".") possible_root_task = parts.pop() possible_module = ".".join(parts) # Try to load module and check again for existance load_python_module(possible_module, "task name '%s'" % task_name) task_cls = self._get_registered_task_cls(task_name) if task_cls: return task_cls # Check if task exists but user forgot to decorate method with @task task_module = sys.modules.get(possible_module) if task_module and hasattr(task_module, possible_root_task): user_func = getattr(task_module, possible_root_task) if callable(user_func): # Non-decorated function was found - decorate and return it from dbnd._core.decorator import func_task_decorator decorated_task = func_task_decorator.task(user_func) setattr(task_module, possible_root_task, decorated_task) logger.warning( "Found non-decorated task: %s. " "Please decorate this task with the proper symbol @pipeline \ @task.\n" "Auto-decorating and treating it as @task ...", task_name, ) return decorated_task.task if is_airflow_enabled(): from dbnd_airflow.dbnd_task_executor.airflow_operator_as_dbnd import ( AirflowDagAsDbndTask, ) dag = self._get_aiflow_dag(task_name) if dag: return AirflowDagAsDbndTask return None def get_task_cls(self, task_name): from dbnd._core.errors import friendly_error task_cls = self._get_task_cls(task_name) if task_cls == self.AMBIGUOUS_CLASS: raise friendly_error.ambiguous_task(task_name) if task_cls: return task_cls raise friendly_error.task_registry.task_not_exist( task_name=task_name, alternative_tasks=get_best_candidate( task_name, self._task_family_to_task_cls.keys() ), ) def list_dbnd_task_classes(self): task_classes = [] for task_name, task_cls in six.iteritems(self._task_family_to_task_cls): if task_cls == self.AMBIGUOUS_CLASS: continue td = task_cls.task_definition if td.hidden: continue if td.task_family.startswith("_"): continue task_classes.append(task_cls) task_classes = sorted( task_classes, key=lambda task_cls: task_cls.task_definition.full_task_family ) return task_classes def build_dbnd_task(self, task_name, task_kwargs=None, expected_type=None): task_kwargs = task_kwargs or dict() task_kwargs.setdefault("task_name", task_name) task_cls = self.get_task_cls(task_name) # type: Type[Task] if is_airflow_enabled(): from dbnd_airflow.dbnd_task_executor.airflow_operator_as_dbnd import ( AirflowDagAsDbndTask, ) if issubclass(task_cls, AirflowDagAsDbndTask): # we are running old style dag dag = self._get_aiflow_dag(task_name) airflow_task = AirflowDagAsDbndTask.build_dbnd_task_from_dag(dag=dag) return airflow_task try: logger.debug("Building %s task", task_cls.task_definition.full_task_family) obj = task_cls(**task_kwargs) except Exception: exc = get_databand_context().settings.log.format_exception_as_str( sys.exc_info(), isolate=True ) logger.error("Failed to build %s: \n\n%s", task_cls.get_task_family(), exc) raise if expected_type and not issubclass(task_cls, expected_type): raise friendly_error.task_registry.wrong_type_for_task( task_name, task_cls, expected_type ) return obj def _get_aiflow_dag(self, dag_id): if not self._dag_bag: from airflow.models import DagBag self._dag_bag = DagBag() if dag_id in self._dag_bag.dags: return self._dag_bag.dags[dag_id] return None ######## ## NAMESPACE MANAGEMENT def get_namespace(self, module_name): for parent in module_parents(module_name): # if module is a.b.c -> a.b can have namespace defined entry = self._namespace_map.get(parent) if entry: return entry # by default we don't have namespace return "" def register_namespace(self, scope, namespace): self._namespace_map[scope] = namespace _REGISTRY = DbndTaskRegistry.try_instance() def build_task_from_config(task_name, expected_type=None): tr = get_task_registry() return tr.build_dbnd_task(task_name=task_name, expected_type=expected_type) def register_config_cls(config_cls): logger.debug("Registered config %s", config_cls) def register_task(task): logger.debug("Registered task %s", task) def get_task_registry(): # type: ()-> DbndTaskRegistry return DbndTaskRegistry.get_instance() @contextlib.contextmanager def tmp_dbnd_registry(): current = get_task_registry() new_tmp_registry = DbndTaskRegistry() # copy all old values new_tmp_registry._fqn_to_task_cls = copy.copy(current._fqn_to_task_cls) new_tmp_registry._task_family_to_task_cls = copy.copy( current._task_family_to_task_cls ) new_tmp_registry._namespace_map = copy.copy(current._namespace_map) with DbndTaskRegistry.new_context( _context=new_tmp_registry, allow_override=True ) as r: # assign already known tasks yield r
#===========================================# #===========>>Python Lists<<================# #===========================================# list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, list1] list3 = [True, False, list2] # Length of the list length = len(list3) print(length, list3[-1][-1][1]) #=========================================== thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist) #=========================================== thislist = ["apple", "banana", "cherry"] thislist.insert(2, "watermelon") print(thislist) #=========================================== thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) #============================================= thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist) #=============================================== thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) print(thislist) #=============================================== thislist = ["apple", "banana", "cherry"] thislist.remove("banana") print(thislist) #============================================ thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist) #=========================================== thislist = ["apple", "banana", "cherry"] del thislist[0] print(thislist) #=========================================== thislist = ["apple", "banana", "cherry"] del thislist print(thislist) #============================================ thislist = ["apple", "banana", "cherry"] thislist.clear() print(thislist) #========================================== thislist = ["apple", "banana", "cherry"] for x in thislist: print(x) #=========================================== thislist = ["apple", "banana", "cherry"] for i in range(len(thislist)): print(thislist[i]) #============================================= thislist = ["apple", "banana", "cherry"] i = 0 while i < len(thislist): print(thislist[i]) i = i + 1 #=============================================== thislist = ["apple", "banana", "cherry"] [print(x) for x in thislist] #================================================= fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) print(newlist) #================================================ fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] print(newlist) #================================================ fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if x != "apple"] print(newlist) #================================================= fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits] print(newlist) #=============================================== newlist = [x for x in range(10)] print(newlist) #================================================ newlist = [x for x in range(10) if x < 5] print(newlist) #================================================= fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = ['hello' for x in fruits] print(newlist) #=============================================== fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x if x != "banana" else "orange" for x in fruits] print(newlist) #================================================ thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort(reverse = True) print(thislist) #================================================= thislist = [100, 50, 65, 82, 23] thislist.sort(reverse = True) print(thislist) #================================================= def myfunc(n): return abs(n - 50) thislist = [100, 50, 65, 82, 23] thislist.sort(key = myfunc) print(thislist) #================================================= thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.sort() print(thislist) #================================================= thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.sort(key = str.lower) print(thislist) #================================================ thislist = ["banana", "Orange", "Kiwi", "cherry"] thislist.reverse() print(thislist) #========================================= thislist = ["apple", "banana", "cherry"] mylist = thislist.copy() print(mylist) #=========================================== thislist = ["apple", "banana", "cherry"] mylist = list(thislist) print(mylist) #============================================ list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) #=========================================== list1 = ["a", "b" , "c"] list2 = [1, 2, 3] for x in list2: list1.append(x) print(list1) #================================================= list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1) #=========================================
<reponame>99Kies/allura<gh_stars>1-10 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. '''IRC Chatbot Plugin ''' #-*- python -*- from __future__ import unicode_literals from __future__ import absolute_import import logging from datetime import date, time, datetime, timedelta # Non-stdlib imports from tg import expose, validate, redirect, flash from tg.decorators import with_trailing_slash from tg import tmpl_context as c, request from formencode import validators # Pyforge-specific imports from allura.app import Application, ConfigOption, SitemapEntry, DefaultAdminController from allura.lib import helpers as h from allura.lib.search import search_app from allura.lib.decorators import require_post from allura.lib.security import require_access from allura.lib.widgets.search import SearchResults, SearchHelp from allura import model as M from allura.controllers import BaseController # Local imports from forgechat import model as CM from forgechat import version log = logging.getLogger(__name__) class ForgeChatApp(Application): __version__ = version.__version__ tool_label = 'Chat' tool_description = 'IRC chat integration' status = 'alpha' default_mount_label = 'Chat' default_mount_point = 'chat' ordinal = 13 permissions = ['configure', 'read'] permissions_desc = { 'configure': 'Set monitored IRC channel. Requires admin permission.', 'read': 'View chat logs.', } config_options = Application.config_options + [ ConfigOption('channel', str, ''), ] has_notifications = False icons = { 24: 'images/chat_24.png', 32: 'images/chat_32.png', 48: 'images/chat_48.png' } def __init__(self, project, config): Application.__init__(self, project, config) self.channel = CM.ChatChannel.query.get(app_config_id=config._id) self.root = RootController() self.admin = AdminController(self) def main_menu(self): return [SitemapEntry(self.config.options.mount_label, '.')] @property @h.exceptionless([], log) def sitemap(self): menu_id = self.config.options.mount_label with h.push_config(c, app=self): return [ SitemapEntry(menu_id, '.')[self.sidebar_menu()]] @h.exceptionless([], log) def sidebar_menu(self): return [ SitemapEntry('Home', '.'), SitemapEntry('Search', 'search'), ] def admin_menu(self): return super(ForgeChatApp, self).admin_menu() def install(self, project): 'Set up any default permissions and roles here' super(ForgeChatApp, self).install(project) role_admin = M.ProjectRole.by_name('Admin')._id role_anon = M.ProjectRole.anonymous()._id self.config.acl = [ M.ACE.allow(role_anon, 'read'), M.ACE.allow(role_admin, 'configure'), ] CM.ChatChannel( project_id=self.config.project_id, app_config_id=self.config._id, channel=self.config.options['channel']) def uninstall(self, project): "Remove all the tool's artifacts from the database" CM.ChatChannel.query.remove(dict( project_id=self.config.project_id, app_config_id=self.config._id)) super(ForgeChatApp, self).uninstall(project) class AdminController(DefaultAdminController): @with_trailing_slash def index(self, **kw): redirect(request.referer or '/') @expose() @require_post() def configure(self, channel=None): with h.push_config(c, app=self.app): require_access(self.app, 'configure') chan = CM.ChatChannel.query.get( project_id=self.app.config.project_id, app_config_id=self.app.config._id) chan.channel = channel flash('Chat options updated') super(AdminController, self).configure(channel=channel) class RootController(BaseController): @expose() def index(self, **kw): now = datetime.utcnow() redirect(c.app.url + now.strftime('%Y/%m/%d/')) @with_trailing_slash @expose('jinja:forgechat:templates/chat/search.html') @validate(dict(q=validators.UnicodeString(if_empty=None), project=validators.StringBool(if_empty=False))) def search(self, q=None, project=None, limit=None, page=0, **kw): c.search_results = SearchResults() c.help_modal = SearchHelp(comments=False, history=False, fields={'sender_t': 'username', 'text': '"Message text"', }) search_params = kw search_params.update({ 'q': q or '', 'project': project, 'limit': limit, 'page': page, 'allowed_types': ['Chat Message'], }) d = search_app(**search_params) d['search_comments_disable'] = True d['search_history_disable'] = True return d @expose() def _lookup(self, y, m, d, *rest): y, m, d = int(y), int(m), int(d) return DayController(date(y, m, d)), rest class DayController(RootController): def __init__(self, day): self.day = day @expose('jinja:forgechat:templates/chat/day.html') def index(self, **kw): q = dict( timestamp={ '$gte': datetime.combine(self.day, time.min), '$lte': datetime.combine(self.day, time.max)}) messages = CM.ChatMessage.query.find(q).sort('timestamp').all() prev = c.app.url + (self.day - timedelta(days=1)).strftime('%Y/%m/%d/') next = c.app.url + (self.day + timedelta(days=1)).strftime('%Y/%m/%d/') return dict( day=self.day, messages=messages, prev=prev, next=next)
<reponame>maghniem/redtide<filename>src/tradebot.py import numpy as np from time import sleep, time from datetime import datetime from collections import defaultdict from analysis.financials import FinancialAnalysis from src.common import get_wallstreet_time from src.models import Stocks from src.api import HoodAPI class TradeBot(object): """ Trade automatically on Robinhood Main strategy is modified scalping: no upper bound, but moving lower bound as price increase. 1. Identify companies with great earning histories and meet all following criteria - Positive net profit past 4 years - Positive net profit past 4 quarters - high market cap, 2 billion - high daily volume 1 million 2. Identify ones that opened high and remained high with no down slope during first 10 minutes since market open, and sort them by this criteria (note: of the stocks opened higher than previous close, the ones with smallest high/close ratio are selected - this is based on personal observation, my guess is if it opens too high, there's less room to go up more??) Also, only 3 x n_splits will be selected, so we don't have to track too many stocks. 3. Of these, select top N stocks and evenly distribute allowance among them. N >= 10 and shares >= 1 Use (allowance / N) > cost_per_share to scan the list of stocks from top to bottom and retrieve ones that qualifies. If reached the end and still partitions left unassigned, assign them to already assigned stock by simply scanning the list again The goal is to maximize diversity, chances are diversity is more important than any other metrics 4. Onces the stocks are selected and their shares to buy are calculated, make these order immediately with market price. 5. Make sell order only if price drops below lower bound (i.e. -0.5%) of the previously polled value, which include buy order price 6. Once a buy-sell is complete, this partition is free to be assigned to any stock (not currently assigned). Take the top 10 qualifying stocks (price < partition) and monitor their movement for 3 minutes, then reassign this partition if trend is good as evaluated before. 7. Repeat step 6. until market close. S1. Watch the overall market trend. If all the assigned stocks are all going down, then sell everything and stop. Watch the market using the top N (in step 2) as representatives. If market goes back up, then do step 6. """ def __init__(self, trader=None, allowance=1000, n_splits=10, max_loss=0.95): print('Initializing TradeBotAPI ...') # initialize trader if trader == 'robinhood': self.trader = HoodAPI() elif trader == 'paper': # TODO - paper trade system self.trader = None else: self.trader = None self.trade_end_offset = (0, 10) # offset by 10 min self.allowance = allowance self.net_worth = allowance self.max_loss = allowance * max_loss self.n_splits = n_splits self.partition_size = np.floor(self.allowance / self.n_splits) self.fa = FinancialAnalysis() self.symbols_qualified = [s for s in self.fa.greats if self.fa.price(s) and self.fa.price(s) < self.partition_size] self.stocks = Stocks(self.symbols_qualified) self.holding = {} # dict of buy price self.pending_buy = [] self.pending_sell = [] self.pending_cancel = [] self.__watch_interval_sec = 45 self.__watch_iters = 10 self.__trend_window = 5 self.__paritions_used = 0 # increment when buy order made, decrement only when sold or buy order canceled self.lb_ratio = -0.005 self.cached_price = {} print('TradeBotAPI initialized.') def run(self): wst = get_wallstreet_time() if not wst['is_market_open']: print("Waiting {:.2f} hours for market to open".format(wst['open_in']/3600)) sleep(wst['open_in']) print('Market now open') if self.trader is not None: self.begin_trade() else: print('No trader') def begin_trade(self): """ Call this at market open to find stocks to scalp. Watch the first 10 iterations before calculating trend. :return: """ print('\nBegin trading ...\n') # 1. scan for open-high stocks # Take 60 - 75 sec for 342 stocks # About 5 sec for 30 print('Scanning %d stocks for open-high ...' % self.stocks.n_stocks) t0 = time() self.stocks.update() remove_stocks = [] for symb, stock in self.stocks.stocks.items(): if stock.open_close_change is None or stock.open_close_change <= 0: remove_stocks.append(symb) for s in remove_stocks: self.stocks.remove(s) print('|- scan took {:.2f} sec'.format(time() - t0)) # 2. Sort open-close ratio from low to high # take the first N-split X 3 to watch for # It seems like the ones that open too high do not growth much # but the ones the open slighly high are more likely to grow symbs = np.array(self.stocks.symbols) changes = np.array([self.stocks.get_stock(s).open_close_change for s in symbs]) idx = np.argsort(changes) n_track = 3 * self.n_splits if len(symbs) > n_track: remove_stocks = symbs[idx][n_track:] for s in remove_stocks: self.stocks.remove(s) self.symbols_qualified = self.stocks.symbols print('Tracking %d qualifying stocks' % self.stocks.n_stocks) # 3. Conitnue to monitor the qualifying stocks for # more iterations for i_iter in range(self.__watch_iters): sleep(self.__watch_interval_sec) self.stocks.update() print('|- watch iter {} / {}'.format(i_iter+1, self.__watch_iters)) # 4. run sequence until trade end or if there are pendings wst = get_wallstreet_time(offset_close=self.trade_end_offset) while wst['is_market_open'] or self.has_pending: self.trade_sequence() if self.net_worth <= self.max_loss: print('! Reach max loss, selling/cancelling everything.') if self.pending_buy: self.cancel_all_pending(method='buy') if self.holding: self.batch_order(list(self.holding.keys()), 'sell') break sleep(self.__watch_interval_sec) # 5. close trader self.trader.quit() print('\nHappy trade day!') print('${:,.2f} ===> ${:,.2f}'.format(self.allowance, self.net_worth)) def sort_buyables(self): wst = get_wallstreet_time(offset_close=self.trade_end_offset) if not wst['is_market_open']: # prevent buy when near end of day return None rvalues = [self.stocks.get_stock(s).price_trend(k=self.__trend_window).rvalue for s in self.stocks.symbols] idx = np.argsort(rvalues)[::-1] symbs = np.array(self.stocks.symbols)[idx] buy_symbs = [] for s in symbs: if s not in self.holding \ and s not in self.pending_buy \ and s not in self.pending_sell \ and s not in self.pending_cancel: buy_symbs.append(s) return buy_symbs def sell_criteria(self, symbol): wst = get_wallstreet_time(offset_close=self.trade_end_offset) if wst['is_market_open']: # sell everything by end of day return True if symbol not in self.holding or symbol in self.pending_sell: return False stat = self.stocks.price_trend(symbol, k=self.__trend_window) stock = self.stocks.get_stock(symbol) # diff is relative to previous cached price diff = stock.price - self.cached_price[symbol] lb = self.lb_ratio * stock.open_price print(': {} rval={:.5f} pval={:.5f} diff={:.2f} lb={:.2f}'.format( symbol, stat.rvalue, stat.pvalue, diff, lb)) if diff <= lb: print('sell criteria ({}): below lower bound'.format(symbol)) return True # elif stat.pvalue <= 0.1 and stat.rvalue < 0: # # Too sensitive at the moment # print('sell criteria ({}): trending down'.format(symbol)) # return True return False @property def partitions_remain(self): return self.n_splits - self.__paritions_used @property def has_pending(self): if self.pending_buy: return True elif self.pending_sell: return True elif self.pending_cancel: return True return False def trade_sequence(self): print('\n___ sequence {} ______'.format(datetime.now())) # check pending status self.get_all_pending_status() # get updates on qualified stocks # don't update cached_price yet, # need the previous cached_price # to determine sell criteria self.stocks.update() # check if there are stocks that should be # sold off for s in self.stocks.symbols: # sell stocks that should be dumped off if self.sell_criteria(s) and self.sell(s): self.pending_sell.append(s) # check global trend and make sure still in trade period # TODO - sell/buy criteria are bad! Need to figure out # a decent strategy stat = self.stocks.price_trend(k=self.__trend_window) global_statistic = stat.statistic global_pvalue = stat.pvalue print(': Global stat={} pval={}'.format(global_statistic, global_pvalue)) wst = get_wallstreet_time(offset_close=self.trade_end_offset) if wst['is_market_open'] and global_statistic > 4 and global_pvalue < 1e-4: # see if there are partitions available # to buy stocks that are worth it if self.partitions_remain > 0: # get all the symbols worth investing buyable_symbols = self.sort_buyables() # this tracks N x parition for each symbol # so if there are more partitions left than # buyable_symbols, same symbol can be assigned # more than 1 partition stock_partitions = defaultdict(int) if buyable_symbols: for i in range(self.partitions_remain): symb = buyable_symbols[i % len(buyable_symbols)] stock_partitions[symb] += 1 for symb, p in stock_partitions.items(): if self.buy(symb, p * self.partition_size): self.pending_buy.append(symb) elif not wst['is_market_open'] or (global_statistic < -4 and global_pvalue < 1e-4): if not wst['is_market_open']: print('! End of day soon, selling everything...') # sell all and cancel all buy orders if self.pending_buy: self.cancel_all_pending('buy') if self.holding: self.batch_order(list(self.holding.keys()), 'sell') else: print('! Does not meet buy or sell criteria, continue watching market ...') # update cached_price for s in self.cached_price: if self.stocks.get_stock(s).price: self.cached_price[s] = self.stocks.get_stock(s).price def _check_order_complete_status(self, symbol, target='Done', max_try=10): if target not in ['Done', 'Canceled']: raise ValueError('target arg must be either Done or Canceled') status = self.trader.order_status(symbol) if status is None: print('>>> lost track of order for {} <<<'.format(symbol)) return False i_try = 0 while status['status'] != target and i_try < max_try: sleep(1) status = self.trader.order_status(symbol) i_try += 1 if status['status'] == target: recent_order = self.trader.orders.stock_recent_order(symbol) # update cached order status recent_order.status = status if target == 'Canceled': msg_head = '[x] Canceled {} order'.format(symbol) elif status.get('type'): if 'Buy' in status.get('type'): msg_head = '[+] Bought {} shared of {} at {}'.format(status.get('shares'), symbol, status.get('price')) elif 'Sell' in status.get('type'): msg_head = '[-] Sold {} shares of {} at {}'.format(status.get('shares'), symbol, status.get('price')) else: print('[?] Unknown status type for {}: {}'.format(symbol, status.get('type'))) return False else: print('[?] Status for {} is missing type'.format(symbol)) return False print(msg_head, 'succesfully!') return True else: print('[?] Cannot confirm if status of {} order is {}'.format(symbol, target)) return False def buy(self, symbol, partition_size=None): if partition_size is None: partition_size = self.partition_size shares = int(np.floor(partition_size / self.stocks.get_stock(symbol).update().price)) try: print('Buying {} shares of {} ...'.format(shares, symbol)) if self.trader.make_order('buy', symbol, shares=shares, order_type='market'): print('|- sent buy order') else: print('|- failed to send buy order') return False except Exception as e: print('|- failed to buy {} ({} shares), exception: {}'.format(symbol, shares, e)) return False self.__paritions_used += 1 return True def sell(self, symbol): if not self.trader.orders.has_stock(symbol): print('No {} shares to sell'.format(symbol)) return False shares = self.trader.orders.stock_recent_order(symbol).shares try: print('Selling {} shares of {} ...'.format(shares, symbol)) if self.trader.make_order('sell', symbol, order_type='market'): print('|- sent sell order') else: print('|- failed to send sell order') return False except Exception as e: print('|- failed to sell {}, exception: {}'.format(symbol, e)) return False return True def cancel(self, symbol): if symbol in self.pending_buy: if self.trader.cancel_order(symbol): self.pending_buy.remove(symbol) self.pending_cancel.append(symbol) return True elif symbol in self.pending_sell: if self.trader.cancel_order(symbol): self.pending_sell.remove(symbol) self.pending_cancel.append(symbol) return True else: print('! No pending buy or sell for {}'.format(symbol)) return False def cancel_all_pending(self, method): if method not in ['buy', 'sell']: raise ValueError('method must be either buy or sell') if method == 'buy': for symbol in self.pending_buy: if self.trader.cancel_order(symbol): self.pending_buy.remove(symbol) self.pending_cancel.append(symbol) else: for symbol in self.pending_sell: if self.trader.cancel_order(symbol): self.pending_sell.remove(symbol) self.pending_cancel.append(symbol) self.get_all_pending_status() def batch_order(self, symbols, method, gap_sec=1): """ This make batch orders, but does not check status :param symbols: :param method: :param gap_sec: :return: """ if method not in ['buy', 'sell']: raise ValueError('method must be either buy or sell') for symbol in symbols: if method == 'buy': if symbol not in self.holding \ and symbol not in self.pending_buy \ and symbol not in self.pending_sell \ and symbol not in self.pending_cancel: if self.buy(symbol): self.pending_buy.append(symbol) sleep(gap_sec) else: print('! Cannot buy: already pending or holding {}'.format(symbol)) else: if symbol in self.holding and symbol not in self.pending_sell: if self.sell(symbol): self.pending_sell.append(symbol) sleep(gap_sec) else: print('! Cannot sell: not holding {}'.format(symbol)) def update_net_worth(self, buy_value, sell_value): trade_value = sell_value - buy_value self.net_worth += trade_value if trade_value > 0: msg = '[ GAIN ]' elif trade_value < 0: msg = '[ LOSS ]' else: msg = '[ EVEN ]' msg += ' ${:,.2f} ==> net ${:,.2f}'.format(trade_value, self.net_worth) print(msg) def get_all_pending_status(self): for symbol in self.pending_buy: if self._check_order_complete_status(symbol, 'Done'): self.pending_buy.remove(symbol) order = self.trader.orders.stock_recent_order(symbol) self.holding[symbol] = order.value self.cached_price[symbol] = order.price for symbol in self.pending_sell: if self._check_order_complete_status(symbol, 'Done'): self.__paritions_used -= 1 self.pending_sell.remove(symbol) order = self.trader.orders.stock_recent_order(symbol) self.update_net_worth(self.holding[symbol], order.value) self.holding.pop(symbol) self.cached_price.pop(symbol) self.trader.close_tab_by_stock(symbol) for symbol in self.pending_cancel: if self._check_order_complete_status(symbol, 'Canceled'): self.pending_cancel.remove(symbol) order = self.trader.orders.stock_recent_order(symbol) if 'Buy' in order.method: self.__paritions_used -= 1 self.trader.close_tab_by_stock(symbol)
<filename>server.py import torch from torch import nn, optim import torch.nn.functional as F import time import copy import numpy as np import torch from torch import nn, optim import torch.nn.functional as F import time import copy import numpy as np from utils import init_dict, save_dict, curve_save, time_mark, print_cz, update_lr def avg_freq( weights, L=0.1, is_conv=True ): client_num = len(weights) if is_conv: N, C, D1, D2 = weights[0].size() else: N = 1 C = 1 D1, D2 = weights[0].size() #print(N, C, D1, D2) temp_low = np.zeros((C*D1, D2*N), dtype=float) for i in range(client_num): # N, C, D1, D2 = weights[i].size() #weights[i] = weights[i].cpu().numpy() if is_conv: weights[i] = weights[i].permute(1, 2, 3, 0).reshape((C*D1, D2*N)) weights[i] = weights[i].cpu().numpy() client_fft = np.fft.fft2(weights[i], axes=(-2, -1)) amp_fft, pha_fft = np.abs(client_fft), np.angle(client_fft) # FFT low_part = np.fft.fftshift(amp_fft, axes=(-2, -1)) temp_low += low_part temp_low = temp_low / 4 # avg the low-frequency for i in range(client_num): client_fft = np.fft.fft2(weights[i], axes=(-2, -1)) amp_fft, pha_fft = np.abs(client_fft), np.angle(client_fft) low_part = np.fft.fftshift(amp_fft, axes=(-2, -1)) h, w = low_part.shape b_h = (np.floor(h *L / 2)).astype(int) b_w = (np.floor(w *L / 2)).astype(int) c_h = np.floor(h/2.0).astype(int) c_w = np.floor(w/2.0).astype(int) h1 = c_h-b_h h2 = c_h+b_h w1 = c_w-b_w w2 = c_w+b_w low_part[h1:h2,w1:w2] = temp_low[h1:h2,w1:w2] # averaged low-freq + individual high-freq low_part = np.fft.ifftshift(low_part, axes=(-2, -1)) fft_back_ = low_part * np.exp(1j * pha_fft) # # get the mutated image fft_back_ = np.fft.ifft2(fft_back_, axes=(-2, -1)) weights[i] = torch.FloatTensor(np.real(fft_back_)) if is_conv: weights[i] = weights[i].reshape(C, D1, D2, N).permute(3, 0, 1, 2) return weights def PFA( weights, L, is_conv ): return avg_freq(weights=weights, L=L, is_conv=is_conv) ################# Key Function ######################## def communication( args, server_model, models, original_models, client_weights, a_iter ): pfa_rate = args.l_rate + (a_iter / args.iters) * (0.95 - args.l_rate) client_num = len(client_weights) # with torch.no_grad(): # aggregate params for key in server_model.state_dict().keys(): if 'bn' not in key: #not bn if 'conv' in key and 'weight' in key: temp_weights = PFA( [ models[0].state_dict()[key].data, models[1].state_dict()[key].data, models[2].state_dict()[key].data, models[3].state_dict()[key].data ], L=pfa_rate, is_conv=True ) for client_idx in range(client_num): # copy from server to each client models[client_idx].state_dict()[key].data.copy_(temp_weights[client_idx]) elif 'linear' in key and 'weight' in key: temp_weights = PFA( [ models[0].state_dict()[key].data, models[1].state_dict()[key].data, models[2].state_dict()[key].data, models[3].state_dict()[key].data ], L=pfa_rate, is_conv=False ) for client_idx in range(client_num): # models[client_idx].state_dict()[key].data.copy_(temp_weights[client_idx]) else: print(key, '\t not bn, conv, fc layer, with param!') temp = torch.zeros_like(server_model.state_dict()[key], dtype=torch.float32) for client_idx in range(client_num): temp += client_weights[client_idx] * models[client_idx].state_dict()[key] server_model.state_dict()[key].data.copy_(temp) # non-bn layer,update the server model for client_idx in range(client_num): # non-bn layer, from server to each client models[client_idx].state_dict()[key].data.copy_(server_model.state_dict()[key]) return server_model, models
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import dataclasses import glob import json import logging import os import shutil import site import subprocess import sys from dataclasses import dataclass, field from logging import Logger from pathlib import Path from typing import ( Any, Dict, Iterable, List, Optional, Sequence, Set, Type, TypeVar, Union, ) import psutil from .. import command_arguments, dataclasses_merge, find_directories from ..filesystem import expand_global_root, expand_relative_path from ..find_directories import ( BINARY_NAME, CONFIGURATION_FILE, get_relative_local_root, LOCAL_CONFIGURATION_FILE, LOG_DIRECTORY, ) from . import ( exceptions, ide_features as ide_features_module, platform_aware, python_version as python_version_module, search_path as search_path_module, shared_memory as shared_memory_module, site_packages, unwatched, ) LOG: Logger = logging.getLogger(__name__) T = TypeVar("T") def _get_optional_value(source: Optional[T], default: T) -> T: return source if source is not None else default def _expand_and_get_existent_ignore_all_errors_path( ignore_all_errors: Iterable[str], project_root: str ) -> List[str]: expanded_ignore_paths = [] for path in ignore_all_errors: expanded = glob.glob(expand_global_root(path, global_root=project_root)) if not expanded: expanded_ignore_paths.append(path) else: expanded_ignore_paths.extend(expanded) paths = [] for path in expanded_ignore_paths: if os.path.exists(path): paths.append(path) else: LOG.warning(f"Nonexistent paths passed in to `ignore_all_errors`: `{path}`") if _is_glob(path): LOG.warning( f"Within `ignore_all_errors`, no matches found to glob pattern: `{path}`" ) else: LOG.warning( f"Nonexistent paths passed in to `ignore_all_errors`: `{path}`" ) return paths def _is_glob(path: str) -> bool: if ("*" in path) or ("?" in path) or (("[" in path) and ("]" in path)): return True return False @dataclasses.dataclass class ExtensionElement: suffix: str include_suffix_in_module_qualifier: bool def command_line_argument(self) -> str: options = "" if self.include_suffix_in_module_qualifier: options = "$" + "include_suffix_in_module_qualifier" return self.suffix + options @staticmethod def from_json(json: Union[str, Dict[str, Union[str, bool]]]) -> "ExtensionElement": if isinstance(json, str): return ExtensionElement( suffix=json, include_suffix_in_module_qualifier=False ) elif isinstance(json, dict): include_suffix_in_module_qualifier = False if "include_suffix_in_module_qualifier" in json: value = json["include_suffix_in_module_qualifier"] if isinstance(value, bool): include_suffix_in_module_qualifier = value if "suffix" in json: suffix = json["suffix"] if isinstance(suffix, str): return ExtensionElement( suffix=suffix, include_suffix_in_module_qualifier=include_suffix_in_module_qualifier, ) raise exceptions.InvalidConfiguration(f"Invalid extension element: {json}") def get_default_site_roots() -> List[str]: try: return [site.getusersitepackages()] + site.getsitepackages() except AttributeError: # There are a few Python versions that ship with a broken venv, # where `getsitepackages` is not available. LOG.warning( "Either `site.getusersitepackages()` or `site.getsitepackages()` " + "is not available in your virtualenv. This is a known virtualenv " + 'bug and as a workaround please explicitly specify `"site_root"` ' + "in your Pyre configuration." ) return [] @dataclasses_merge.dataclass_merge @dataclass(frozen=True) class PartialConfiguration: binary: Optional[str] = None buck_mode: Optional[platform_aware.PlatformAware[str]] = field( default=None, metadata={"merge_policy": platform_aware.PlatformAware.merge_optional}, ) do_not_ignore_errors_in: Sequence[str] = field( default_factory=list, metadata={"merge_policy": dataclasses_merge.Policy.PREPEND}, ) dot_pyre_directory: Optional[Path] = None excludes: Sequence[str] = field( default_factory=list, metadata={"merge_policy": dataclasses_merge.Policy.PREPEND}, ) extensions: Sequence[ExtensionElement] = field( default_factory=list, metadata={"merge_policy": dataclasses_merge.Policy.PREPEND}, ) ide_features: Optional[ide_features_module.IdeFeatures] = field( default=None, metadata={"merge_policy": ide_features_module.IdeFeatures.merge_optional}, ) ignore_all_errors: Sequence[str] = field( default_factory=list, metadata={"merge_policy": dataclasses_merge.Policy.PREPEND}, ) isolation_prefix: Optional[str] = None logger: Optional[str] = None number_of_workers: Optional[int] = None oncall: Optional[str] = None other_critical_files: Sequence[str] = field( default_factory=list, metadata={"merge_policy": dataclasses_merge.Policy.PREPEND}, ) pysa_version_hash: Optional[str] = None python_version: Optional[python_version_module.PythonVersion] = None search_path: Sequence[search_path_module.RawElement] = field( default_factory=list, metadata={"merge_policy": dataclasses_merge.Policy.PREPEND}, ) shared_memory: shared_memory_module.SharedMemory = ( shared_memory_module.SharedMemory() ) site_package_search_strategy: Optional[site_packages.SearchStrategy] = None site_roots: Optional[Sequence[str]] = None source_directories: Optional[Sequence[search_path_module.RawElement]] = field( default=None, metadata={"merge_policy": dataclasses_merge.Policy.RAISE_WHEN_OVERWRITTEN}, ) strict: Optional[bool] = None taint_models_path: Sequence[str] = field( default_factory=list, metadata={"merge_policy": dataclasses_merge.Policy.PREPEND}, ) targets: Optional[Sequence[str]] = field( default=None, metadata={"merge_policy": dataclasses_merge.Policy.RAISE_WHEN_OVERWRITTEN}, ) typeshed: Optional[str] = None unwatched_dependency: Optional[unwatched.UnwatchedDependency] = None use_buck2: Optional[bool] = None version_hash: Optional[str] = None @staticmethod def _get_depreacted_map() -> Dict[str, str]: return {"do_not_check": "ignore_all_errors"} @staticmethod def _get_extra_keys() -> Set[str]: return { "create_open_source_configuration", "saved_state", "stable_client", "taint_models_path", "unstable_client", } @staticmethod def from_command_arguments( arguments: command_arguments.CommandArguments, ) -> "PartialConfiguration": strict: Optional[bool] = True if arguments.strict else None source_directories = [ search_path_module.SimpleRawElement(element) for element in arguments.source_directories ] or None targets: Optional[List[str]] = ( arguments.targets if len(arguments.targets) > 0 else None ) python_version_string = arguments.python_version ide_features = ( ide_features_module.IdeFeatures( hover_enabled=arguments.enable_hover, go_to_definition_enabled=arguments.enable_go_to_definition, find_symbols_enabled=arguments.enable_find_symbols, ) if arguments.enable_hover is not None or arguments.enable_go_to_definition is not None else None ) return PartialConfiguration( binary=arguments.binary, buck_mode=platform_aware.PlatformAware.from_json( arguments.buck_mode, "buck_mode" ), do_not_ignore_errors_in=arguments.do_not_ignore_errors_in, dot_pyre_directory=arguments.dot_pyre_directory, excludes=arguments.exclude, extensions=[], ide_features=ide_features, ignore_all_errors=[], isolation_prefix=arguments.isolation_prefix, logger=arguments.logger, number_of_workers=arguments.number_of_workers, oncall=None, other_critical_files=[], pysa_version_hash=None, python_version=( python_version_module.PythonVersion.from_string(python_version_string) if python_version_string is not None else None ), search_path=[ search_path_module.SimpleRawElement(element) for element in arguments.search_path ], shared_memory=shared_memory_module.SharedMemory( heap_size=arguments.shared_memory_heap_size, dependency_table_power=arguments.shared_memory_dependency_table_power, hash_table_power=arguments.shared_memory_hash_table_power, ), site_package_search_strategy=None, site_roots=None, source_directories=source_directories, strict=strict, taint_models_path=[], targets=targets, typeshed=arguments.typeshed, unwatched_dependency=None, use_buck2=arguments.use_buck2, version_hash=None, ) @staticmethod def from_string(contents: str) -> "PartialConfiguration": def is_list_of_string(elements: object) -> bool: return isinstance(elements, list) and all( isinstance(element, str) for element in elements ) def ensure_option_type( json: Dict[str, Any], name: str, expected_type: Type[T] ) -> Optional[T]: result = json.pop(name, None) if result is None: return None elif isinstance(result, expected_type): return result raise exceptions.InvalidConfiguration( f"Configuration field `{name}` is expected to have type " f"{expected_type} but got: `{result}`." ) def ensure_optional_string_or_string_dict( json: Dict[str, Any], name: str ) -> Optional[Union[Dict[str, str], str]]: result = json.pop(name, None) if result is None: return None elif isinstance(result, str): return result elif isinstance(result, Dict): for value in result.values(): if not isinstance(value, str): raise exceptions.InvalidConfiguration( f"Configuration field `{name}` is expected to be a " + f"dict of strings but got `{result}`." ) return result raise exceptions.InvalidConfiguration( f"Configuration field `{name}` is expected to be a string or a " + f"dict of strings but got `{result}`." ) def ensure_optional_string_list( json: Dict[str, Any], name: str ) -> Optional[List[str]]: result = json.pop(name, None) if result is None: return None elif is_list_of_string(result): return result raise exceptions.InvalidConfiguration( f"Configuration field `{name}` is expected to be a list of " + f"strings but got `{result}`." ) def ensure_string_list( json: Dict[str, Any], name: str, allow_single_string: bool = False ) -> List[str]: result = json.pop(name, []) if allow_single_string and isinstance(result, str): result = [result] if is_list_of_string(result): return result raise exceptions.InvalidConfiguration( f"Configuration field `{name}` is expected to be a list of " + f"strings but got `{result}`." ) def ensure_list(json: Dict[str, object], name: str) -> List[object]: result = json.pop(name, []) if isinstance(result, list): return result raise exceptions.InvalidConfiguration( f"Configuration field `{name}` is expected to be a list but got `{result}`." ) try: configuration_json = json.loads(contents) dot_pyre_directory = ensure_option_type( configuration_json, "dot_pyre_directory", str ) search_path_json = configuration_json.pop("search_path", []) if isinstance(search_path_json, list): search_path = [ search_path_module.create_raw_element(json) for json in search_path_json ] else: search_path = [search_path_module.create_raw_element(search_path_json)] python_version_json = configuration_json.pop("python_version", None) if python_version_json is None: python_version = None elif isinstance(python_version_json, str): python_version = python_version_module.PythonVersion.from_string( python_version_json ) else: raise exceptions.InvalidConfiguration( "Expect python version to be a string but got" + f"'{python_version_json}'" ) shared_memory_json = ensure_option_type( configuration_json, "shared_memory", dict ) if shared_memory_json is None: shared_memory = shared_memory_module.SharedMemory() else: shared_memory = shared_memory_module.SharedMemory( heap_size=ensure_option_type(shared_memory_json, "heap_size", int), dependency_table_power=ensure_option_type( shared_memory_json, "dependency_table_power", int ), hash_table_power=ensure_option_type( shared_memory_json, "hash_table_power", int ), ) for unrecognized_key in shared_memory_json: LOG.warning(f"Unrecognized configuration item: {unrecognized_key}") source_directories_json = ensure_option_type( configuration_json, "source_directories", list ) if isinstance(source_directories_json, list): source_directories = [ search_path_module.create_raw_element(json) for json in source_directories_json ] else: source_directories = None site_package_search_strategy_json = ensure_option_type( configuration_json, "site_package_search_strategy", str ) if site_package_search_strategy_json is None: site_package_search_strategy = None else: site_package_search_strategy = site_packages.SearchStrategy.from_string( site_package_search_strategy_json ) if site_package_search_strategy is None: raise exceptions.InvalidConfiguration( "Invalid value for `site_package_search_strategy`: " f"{site_package_search_strategy_json}. Available choices: " f"{[str(x) for x in site_packages.SearchStrategy]}." ) ide_features_json = ensure_option_type( configuration_json, "ide_features", dict ) if ide_features_json is None: ide_features = None else: ide_features = ide_features_module.IdeFeatures.create_from_json( ide_features_json ) unwatched_dependency_json = ensure_option_type( configuration_json, "unwatched_dependency", dict ) if unwatched_dependency_json is None: unwatched_dependency = None else: unwatched_dependency = unwatched.UnwatchedDependency.from_json( unwatched_dependency_json ) partial_configuration = PartialConfiguration( binary=ensure_option_type(configuration_json, "binary", str), buck_mode=platform_aware.PlatformAware.from_json( ensure_optional_string_or_string_dict( configuration_json, "buck_mode" ), "buck_mode", ), do_not_ignore_errors_in=ensure_string_list( configuration_json, "do_not_ignore_errors_in" ), dot_pyre_directory=Path(dot_pyre_directory) if dot_pyre_directory is not None else None, excludes=ensure_string_list( configuration_json, "exclude", allow_single_string=True ), extensions=[ # pyre-fixme[6]: we did not fully verify the type of `json` ExtensionElement.from_json(json) for json in ensure_list(configuration_json, "extensions") ], ide_features=ide_features, ignore_all_errors=ensure_string_list( configuration_json, "ignore_all_errors" ), isolation_prefix=ensure_option_type( configuration_json, "isolation_prefix", str ), logger=ensure_option_type(configuration_json, "logger", str), number_of_workers=ensure_option_type( configuration_json, "workers", int ), oncall=ensure_option_type(configuration_json, "oncall", str), other_critical_files=ensure_string_list( configuration_json, "critical_files" ), pysa_version_hash=ensure_option_type( configuration_json, "pysa_version", str ), python_version=python_version, search_path=search_path, shared_memory=shared_memory, site_package_search_strategy=site_package_search_strategy, site_roots=ensure_optional_string_list( configuration_json, "site_roots" ), source_directories=source_directories, strict=ensure_option_type(configuration_json, "strict", bool), taint_models_path=ensure_string_list( configuration_json, "taint_models_path", allow_single_string=True ), targets=ensure_optional_string_list(configuration_json, "targets"), typeshed=ensure_option_type(configuration_json, "typeshed", str), unwatched_dependency=unwatched_dependency, use_buck2=ensure_option_type(configuration_json, "use_buck2", bool), version_hash=ensure_option_type(configuration_json, "version", str), ) # Check for deprecated and unused keys for ( deprecated_key, replacement_key, ) in PartialConfiguration._get_depreacted_map().items(): if deprecated_key in configuration_json: configuration_json.pop(deprecated_key) LOG.warning( f"Configuration file uses deprecated item `{deprecated_key}`. " f"Please migrate to its replacement `{replacement_key}`" ) extra_keys = PartialConfiguration._get_extra_keys() for unrecognized_key in configuration_json: if unrecognized_key not in extra_keys: LOG.warning(f"Unrecognized configuration item: {unrecognized_key}") return partial_configuration except json.JSONDecodeError as error: raise exceptions.InvalidConfiguration(f"Invalid JSON file: {error}") @staticmethod def from_file(path: Path) -> "PartialConfiguration": try: contents = path.read_text(encoding="utf-8") return PartialConfiguration.from_string(contents) except OSError as error: raise exceptions.InvalidConfiguration(f"Error when reading {path}: {error}") def expand_relative_paths(self, root: str) -> "PartialConfiguration": binary = self.binary if binary is not None: binary = expand_relative_path(root, binary) logger = self.logger if logger is not None: logger = expand_relative_path(root, logger) source_directories = self.source_directories if source_directories is not None: source_directories = [ path.expand_relative_root(root) for path in source_directories ] typeshed = self.typeshed if typeshed is not None: typeshed = expand_relative_path(root, typeshed) unwatched_dependency = self.unwatched_dependency if unwatched_dependency is not None: files = unwatched_dependency.files unwatched_dependency = unwatched.UnwatchedDependency( change_indicator=unwatched_dependency.change_indicator, files=unwatched.UnwatchedFiles( root=expand_relative_path(root, files.root), checksum_path=files.checksum_path, ), ) return PartialConfiguration( binary=binary, buck_mode=self.buck_mode, do_not_ignore_errors_in=[ expand_relative_path(root, path) for path in self.do_not_ignore_errors_in ], dot_pyre_directory=self.dot_pyre_directory, excludes=self.excludes, extensions=self.extensions, ide_features=self.ide_features, ignore_all_errors=[ expand_relative_path(root, path) for path in self.ignore_all_errors ], isolation_prefix=self.isolation_prefix, logger=logger, number_of_workers=self.number_of_workers, oncall=self.oncall, other_critical_files=[ expand_relative_path(root, path) for path in self.other_critical_files ], pysa_version_hash=self.pysa_version_hash, python_version=self.python_version, search_path=[path.expand_relative_root(root) for path in self.search_path], shared_memory=self.shared_memory, site_package_search_strategy=self.site_package_search_strategy, site_roots=self.site_roots, source_directories=source_directories, strict=self.strict, taint_models_path=[ expand_relative_path(root, path) for path in self.taint_models_path ], targets=self.targets, typeshed=typeshed, unwatched_dependency=unwatched_dependency, use_buck2=self.use_buck2, version_hash=self.version_hash, ) def merge_partial_configurations( base: PartialConfiguration, override: PartialConfiguration ) -> PartialConfiguration: try: # pyre-ignore[16]: Pyre does not understand `dataclass_merge` return PartialConfiguration.merge(base, override) except dataclasses_merge.DataclassMergeError as error: raise exceptions.InvalidConfiguration(str(error)) @dataclass(frozen=True) class Configuration: project_root: str dot_pyre_directory: Path binary: Optional[str] = None buck_mode: Optional[platform_aware.PlatformAware[str]] = None do_not_ignore_errors_in: Sequence[str] = field(default_factory=list) excludes: Sequence[str] = field(default_factory=list) extensions: Sequence[ExtensionElement] = field(default_factory=list) ide_features: Optional[ide_features_module.IdeFeatures] = None ignore_all_errors: Sequence[str] = field(default_factory=list) isolation_prefix: Optional[str] = None logger: Optional[str] = None number_of_workers: Optional[int] = None oncall: Optional[str] = None other_critical_files: Sequence[str] = field(default_factory=list) pysa_version_hash: Optional[str] = None python_version: Optional[python_version_module.PythonVersion] = None relative_local_root: Optional[str] = None search_path: Sequence[search_path_module.RawElement] = field(default_factory=list) shared_memory: shared_memory_module.SharedMemory = ( shared_memory_module.SharedMemory() ) site_package_search_strategy: site_packages.SearchStrategy = ( site_packages.SearchStrategy.NONE ) site_roots: Optional[Sequence[str]] = None source_directories: Optional[Sequence[search_path_module.RawElement]] = None strict: bool = False taint_models_path: Sequence[str] = field(default_factory=list) targets: Optional[Sequence[str]] = None typeshed: Optional[str] = None unwatched_dependency: Optional[unwatched.UnwatchedDependency] = None use_buck2: bool = False version_hash: Optional[str] = None @staticmethod def from_partial_configuration( project_root: Path, relative_local_root: Optional[str], partial_configuration: PartialConfiguration, ) -> "Configuration": search_path = partial_configuration.search_path return Configuration( project_root=str(project_root), dot_pyre_directory=_get_optional_value( partial_configuration.dot_pyre_directory, project_root / LOG_DIRECTORY ), binary=partial_configuration.binary, buck_mode=partial_configuration.buck_mode, do_not_ignore_errors_in=partial_configuration.do_not_ignore_errors_in, excludes=partial_configuration.excludes, extensions=partial_configuration.extensions, ide_features=partial_configuration.ide_features, ignore_all_errors=partial_configuration.ignore_all_errors, isolation_prefix=partial_configuration.isolation_prefix, logger=partial_configuration.logger, number_of_workers=partial_configuration.number_of_workers, oncall=partial_configuration.oncall, other_critical_files=partial_configuration.other_critical_files, pysa_version_hash=partial_configuration.pysa_version_hash, python_version=partial_configuration.python_version, relative_local_root=relative_local_root, search_path=[ path.expand_global_root(str(project_root)) for path in search_path ], shared_memory=partial_configuration.shared_memory, site_package_search_strategy=partial_configuration.site_package_search_strategy or site_packages.SearchStrategy.NONE, site_roots=partial_configuration.site_roots, source_directories=partial_configuration.source_directories, strict=_get_optional_value(partial_configuration.strict, default=False), taint_models_path=partial_configuration.taint_models_path, targets=partial_configuration.targets, typeshed=partial_configuration.typeshed, unwatched_dependency=partial_configuration.unwatched_dependency, use_buck2=_get_optional_value( partial_configuration.use_buck2, default=False ), version_hash=partial_configuration.version_hash, ) @property def log_directory(self) -> str: if self.relative_local_root is None: return str(self.dot_pyre_directory) return str(self.dot_pyre_directory / self.relative_local_root) @property def local_root(self) -> Optional[str]: if self.relative_local_root is None: return None return os.path.join(self.project_root, self.relative_local_root) def to_json(self) -> Dict[str, object]: """ This method is for display purpose only. Do *NOT* expect this method to produce JSONs that can be de-serialized back into configurations. """ binary = self.binary buck_mode = self.buck_mode isolation_prefix = self.isolation_prefix logger = self.logger number_of_workers = self.number_of_workers oncall = self.oncall pysa_version_hash = self.pysa_version_hash python_version = self.python_version relative_local_root = self.relative_local_root source_directories = self.source_directories site_package_search_strategy = self.site_package_search_strategy site_roots = self.site_roots targets = self.targets typeshed = self.typeshed unwatched_dependency = self.unwatched_dependency version_hash = self.version_hash return { "global_root": self.project_root, "dot_pyre_directory": str(self.dot_pyre_directory), **({"binary": binary} if binary is not None else {}), **({"buck_mode": buck_mode.to_json()} if buck_mode is not None else {}), "do_not_ignore_errors_in": list(self.do_not_ignore_errors_in), "excludes": list(self.excludes), "extensions": list(self.extensions), "ignore_all_errors": list(self.ignore_all_errors), **( {"isolation_prefix": isolation_prefix} if isolation_prefix is not None else {} ), **({"logger": logger} if logger is not None else {}), **({"oncall": oncall} if oncall is not None else {}), **({"workers": number_of_workers} if number_of_workers is not None else {}), "other_critical_files": list(self.other_critical_files), **( {"pysa_version_hash": pysa_version_hash} if pysa_version_hash is not None else {} ), **( {"python_version": python_version.to_string()} if python_version is not None else {} ), **( {"relative_local_root": relative_local_root} if relative_local_root is not None else {} ), "search_path": [str(path) for path in self.search_path], **( {"shared_memory": self.shared_memory.to_json()} if self.shared_memory != shared_memory_module.SharedMemory() else {} ), **( {"site_package_search_strategy": site_package_search_strategy} if site_package_search_strategy is not None else {} ), "site_roots": site_roots if site_roots is not None else [], **( {"source_directories": [str(path) for path in source_directories]} if source_directories is not None else {} ), "strict": self.strict, "taint_models_path": list(self.taint_models_path), **({"targets": list(targets)} if targets is not None else {}), **({"typeshed": typeshed} if typeshed is not None else {}), **( {"unwatched_dependency": unwatched_dependency.to_json()} if unwatched_dependency is not None else {} ), "use_buck2": self.use_buck2, **({"version_hash": version_hash} if version_hash is not None else {}), } def get_existent_unwatched_dependency( self, ) -> Optional[unwatched.UnwatchedDependency]: unwatched_dependency = self.unwatched_dependency if unwatched_dependency is None: return None unwatched_root = Path(unwatched_dependency.files.root) try: if not unwatched_root.is_dir(): LOG.warning( "Nonexistent directory passed in to `unwatched_dependency`: " f"`{unwatched_root}`" ) return None checksum_path = unwatched_root / unwatched_dependency.files.checksum_path if not checksum_path.is_file(): LOG.warning( "Nonexistent file passed in to `unwatched_dependency`: " f"`{checksum_path}`" ) return None return self.unwatched_dependency except PermissionError as error: LOG.warning(str(error)) return None def get_site_roots(self) -> Sequence[str]: site_roots = self.site_roots if site_roots is not None: return site_roots return get_default_site_roots() def expand_and_get_existent_search_paths( self, ) -> List[search_path_module.Element]: site_roots = self.get_site_roots() existent_paths = search_path_module.process_raw_elements( self.search_path, site_roots ) site_packages_paths = site_packages.search_for_paths( self.site_package_search_strategy, site_roots ) typeshed_root = self.get_typeshed_respecting_override() if typeshed_root is None: return existent_paths + site_packages_paths typeshed_paths: List[search_path_module.Element] = [ search_path_module.SimpleElement(str(element)) for element in find_directories.find_typeshed_search_paths( Path(typeshed_root) ) ] return existent_paths + site_packages_paths + typeshed_paths def expand_and_get_existent_source_directories( self, ) -> List[search_path_module.Element]: source_directories = self.source_directories if source_directories is not None: return search_path_module.process_raw_elements( source_directories, self.get_site_roots() ) else: return [] def get_existent_do_not_ignore_errors_in_paths(self) -> List[str]: """ This is a separate method because we want to check for existing files at the time this is called, not when the configuration is constructed. """ ignore_paths = [ expand_global_root(path, global_root=self.project_root) for path in self.do_not_ignore_errors_in ] paths = [] for path in ignore_paths: if os.path.exists(path): paths.append(path) else: LOG.debug( "Filtering out nonexistent paths in `do_not_ignore_errors_in`: " f"{path}" ) return paths def get_existent_ignore_all_errors_paths(self) -> List[str]: """ This is a separate method because we want to check for existing files at the time this is called, not when the configuration is constructed. """ return _expand_and_get_existent_ignore_all_errors_path( self.ignore_all_errors, self.project_root ) def get_binary_respecting_override(self) -> Optional[str]: binary = self.binary if binary is not None: return binary LOG.info(f"No binary specified, looking for `{BINARY_NAME}` in PATH") binary_candidate = shutil.which(BINARY_NAME) if binary_candidate is None: binary_candidate_name = os.path.join( os.path.dirname(sys.argv[0]), BINARY_NAME ) binary_candidate = shutil.which(binary_candidate_name) if binary_candidate is not None: return binary_candidate return None def get_typeshed_respecting_override(self) -> Optional[str]: typeshed = self.typeshed if typeshed is not None: return typeshed LOG.info("No typeshed specified, looking for it...") auto_determined_typeshed = find_directories.find_typeshed() if auto_determined_typeshed is None: LOG.warning( "Could not find a suitable typeshed. Types for Python builtins " "and standard libraries may be missing!" ) return None else: LOG.info(f"Found: `{auto_determined_typeshed}`") return str(auto_determined_typeshed) def get_version_hash_respecting_override(self) -> Optional[str]: overriding_version_hash = os.getenv("PYRE_VERSION_HASH") if overriding_version_hash: LOG.warning(f"Version hash overridden with `{overriding_version_hash}`") return overriding_version_hash return self.version_hash def get_binary_version(self) -> Optional[str]: binary = self.get_binary_respecting_override() if binary is None: return None status = subprocess.run( [binary, "-version"], stdout=subprocess.PIPE, universal_newlines=True ) return status.stdout.strip() if status.returncode == 0 else None def get_number_of_workers(self) -> int: number_of_workers = self.number_of_workers if number_of_workers is not None and number_of_workers > 0: return number_of_workers # pyre-fixme[28]: Unexpected keyword argument `logical`. number_of_physical_cores = psutil.cpu_count(logical=False) if number_of_physical_cores is None: default_number_of_workers = 1 else: default_number_of_workers = max(1, number_of_physical_cores - 1) LOG.info( "Could not determine the number of Pyre workers from configuration. " f"Auto-set the value to {default_number_of_workers}." ) if default_number_of_workers <= 1: LOG.info( "Consider setting the `--sequential` flag instead when the number " "of parallel workers is not greater than 1." ) return default_number_of_workers def is_hover_enabled(self) -> bool: if self.ide_features is None: return ide_features_module.IdeFeatures.DEFAULT_HOVER_ENABLED return self.ide_features.is_hover_enabled() def is_go_to_definition_enabled(self) -> bool: if self.ide_features is None: return ide_features_module.IdeFeatures.DEFAULT_GO_TO_DEFINITION_ENABLED return self.ide_features.is_go_to_definition_enabled() def is_find_symbols_enabled(self) -> bool: if self.ide_features is None: return ide_features_module.IdeFeatures.DEFAULT_FIND_SYMBOLS_ENABLED return self.ide_features.is_find_symbols_enabled() def get_valid_extension_suffixes(self) -> List[str]: vaild_extensions = [] for extension in self.extensions: if not extension.suffix.startswith("."): LOG.warning( "Filtering out extension which does not start with `.`: " f"`{extension.suffix}`" ) else: vaild_extensions.append(extension.command_line_argument()) return vaild_extensions def get_isolation_prefix_respecting_override(self) -> Optional[str]: """We need this to disable an isolation prefix set in a configuration. Merely omitting the CLI flag would not disable the isolation prefix because we would just fall back to the configuration value. With this, we can pass `--isolation-prefix ''` as a CLI argument or override `isolation_prefix` as `""` in a local configuration.""" return None if self.isolation_prefix == "" else self.isolation_prefix def get_python_version(self) -> python_version_module.PythonVersion: python_version = self.python_version if python_version is not None: return python_version else: version_info = sys.version_info return python_version_module.PythonVersion( major=version_info.major, minor=version_info.minor, micro=version_info.micro, ) def create_configuration( arguments: command_arguments.CommandArguments, base_directory: Path ) -> Configuration: local_root_argument = arguments.local_configuration search_base = ( base_directory if local_root_argument is None else base_directory / local_root_argument ) found_root = find_directories.find_global_and_local_root(search_base) # If the local root was explicitly specified but does not exist, return an # error instead of falling back to current directory. if local_root_argument is not None: if found_root is None: raise exceptions.InvalidConfiguration( "A local configuration path was explicitly specified, but no" + f" {CONFIGURATION_FILE} file was found in {search_base}" + " or its parents." ) elif found_root.local_root is None: raise exceptions.InvalidConfiguration( "A local configuration path was explicitly specified, but no" + f" {LOCAL_CONFIGURATION_FILE} file was found in {search_base}" + " or its parents." ) command_argument_configuration = PartialConfiguration.from_command_arguments( arguments ).expand_relative_paths(str(Path.cwd())) if found_root is None: project_root = Path.cwd() relative_local_root = None partial_configuration = command_argument_configuration else: project_root = found_root.global_root relative_local_root = None partial_configuration = PartialConfiguration.from_file( project_root / CONFIGURATION_FILE ).expand_relative_paths(str(project_root)) local_root = found_root.local_root if local_root is not None: relative_local_root = get_relative_local_root(project_root, local_root) partial_configuration = merge_partial_configurations( base=partial_configuration, override=PartialConfiguration.from_file( local_root / LOCAL_CONFIGURATION_FILE ).expand_relative_paths(str(local_root)), ) partial_configuration = merge_partial_configurations( base=partial_configuration, override=command_argument_configuration, ) return Configuration.from_partial_configuration( project_root, relative_local_root, partial_configuration ) def check_nested_local_configuration(configuration: Configuration) -> None: """ Raises `InvalidConfiguration` if the check fails. """ local_root = configuration.local_root if local_root is None: return def is_subdirectory(child: Path, parent: Path) -> bool: return parent == child or parent in child.parents # We search from the parent of the local root, looking for another local # configuration file that lives above the current one local_root_path = Path(local_root).resolve() current_directory = local_root_path.parent while True: found_root = find_directories.find_global_and_local_root(current_directory) if found_root is None: break nesting_local_root = found_root.local_root if nesting_local_root is None: break nesting_configuration = PartialConfiguration.from_file( nesting_local_root / LOCAL_CONFIGURATION_FILE ).expand_relative_paths(str(nesting_local_root)) nesting_ignored_all_errors_path = ( _expand_and_get_existent_ignore_all_errors_path( nesting_configuration.ignore_all_errors, str(found_root.global_root) ) ) if not any( is_subdirectory(child=local_root_path, parent=Path(path)) for path in nesting_ignored_all_errors_path ): error_message = ( "Local configuration is nested under another local configuration at " f"`{nesting_local_root}`.\nPlease add `{local_root_path}` to the " "`ignore_all_errors` field of the parent, or combine the sources " "into a single configuration, or split the parent configuration to " "avoid inconsistent errors." ) raise exceptions.InvalidConfiguration(error_message) current_directory = nesting_local_root.parent
<reponame>fyellin/pds-opus ################################################################################ # validate.py # # Perform various validations on the database. ################################################################################ import impglobals def validate_param_info(namespace): # Every column in every obs_ table should have an entry in the param_info # table except for id and obs_general_id. # Exceptions are: # volume_id in tables other than obs_pds # instrument_id in tables other than obs_general db = impglobals.DATABASE logger = impglobals.LOGGER logger.log('debug', 'Validating param_info table') obs_table_names = sorted(list(db.table_names(namespace, prefix='obs_'))) pi_table_name = db.convert_raw_to_namespace(namespace, 'param_info') q = db.quote_identifier for obs_table_name in obs_table_names: if obs_table_name == 'obs_files': # Not really a user-visible table so no param_info needed continue column_list = db.table_info(namespace, obs_table_name) field_names = [x['field_name'] for x in column_list] for column in column_list: field_name = column['field_name'] if (field_name == 'id' or field_name == 'timestamp' or field_name == 'obs_general_id' or field_name.startswith('d_') or 'd_'+field_name in field_names or (field_name == 'opus_id' and obs_table_name != 'obs_general') or (field_name.startswith('mult_'))): continue if field_name == 'volume_id' and obs_table_name != 'obs_pds': continue if (field_name == 'instrument_id' and obs_table_name != 'obs_general'): continue cmd = f""" COUNT(*) FROM {q(pi_table_name)} WHERE CATEGORY_NAME='{obs_table_name}' AND NAME='{field_name}'""" res = db.general_select(cmd) count = res[0][0] if count == 0: logger.log('error', f'OBS field "{obs_table_name}.{field_name}" missing param_info entry') # Every param_info entry should have a unique disp_order # This is a hideous query that looks for duplicate disp_order fields # within a given category as long as the field is displayed cmd = f""" {q('category_name')}, {q('name')} FROM {q(pi_table_name)} {q('pi1')} WHERE EXISTS (SELECT 1 FROM {q(pi_table_name)} {q('pi2')} WHERE {q('pi1')}.{q('category_name')}={q('pi2')}.{q('category_name')} AND {q('pi1')}.{q('disp_order')}={q('pi2')}.{q('disp_order')} AND ({q('pi1')}.display=1 OR {q('pi1')}.{q('display_results')}=1) AND ({q('pi2')}.display=1 OR {q('pi2')}.{q('display_results')}=1) AND {q('pi1')}.{q('id')}!={q('pi2')}.{q('id')} LIMIT 1,1)""" res = db.general_select(cmd) for cat_name, field_name in res: logger.log('error', f'PARAM_INFO field "{cat_name}.{field_name}" has duplicate disp_order') # Every param_info entry should have a unique slug. Period. cmd = f""" {q('category_name')}, {q('name')} FROM {q(pi_table_name)} {q('pi1')} WHERE EXISTS (SELECT 1 FROM {q(pi_table_name)} {q('pi2')} WHERE {q('pi1')}.{q('slug')}={q('pi2')}.{q('slug')} AND {q('pi1')}.{q('id')}!={q('pi2')}.{q('id')} LIMIT 1,1)""" res = db.general_select(cmd) for cat_name, field_name in res: logger.log('error', f'PARAM_INFO field "{cat_name}.{field_name}" has duplicate slug') def validate_nulls(namespace): # Look for columns in OBS tables that don't contain nulls and yet the # column is marked as NULLS-OK and suggest the column type be changed. # We ignore obs_surface_geometry__ tables because they all come from a # single template so are harder to analyze. db = impglobals.DATABASE logger = impglobals.LOGGER logger.log('debug', 'Validating non-NULL columns') obs_table_names = sorted(list(db.table_names(namespace, prefix='obs_'))) q = db.quote_identifier for obs_table_name in obs_table_names: if obs_table_name.startswith('obs_surface_geometry__'): continue column_list = db.table_info(namespace, obs_table_name) for column in column_list: field_name = column['field_name'] notnull = column['field_notnull'] if notnull: continue # OK the column allows nulls...are there any? full_obs_table_name = db.convert_raw_to_namespace(namespace, obs_table_name) cmd = f""" count(*) FROM {q(full_obs_table_name)} WHERE {q(field_name)} is NULL""" res = db.general_select(cmd) count = res[0][0] if count == 0: logger.log('info', f'Column "{full_obs_table_name}.{field_name}" allows NULLs but none found '+ '- suggest changing column attributes') def validate_min_max_order(namespace): # Look for pairs of columns X1/X2 and check to make sure that X1 <= X2 in # all non-NULL cases. db = impglobals.DATABASE logger = impglobals.LOGGER logger.log('debug', 'Validating MIN/MAX columns') obs_table_names = sorted(list(db.table_names(namespace, prefix='obs_'))) pi_table_name = db.convert_raw_to_namespace(namespace, 'param_info') q = db.quote_identifier for obs_table_name in obs_table_names: full_obs_table_name = db.convert_raw_to_namespace(namespace, obs_table_name) column_list = db.table_info(namespace, obs_table_name) column_list.sort(key=lambda x:x['field_name']) for column in column_list: field_name1 = column['field_name'] if not field_name1.endswith('1'): continue field_name2 = field_name1[:-1] + '2' if field_name2 not in [x['field_name'] for x in column_list]: logger.log('error', f'Column "{full_obs_table_name}.{field_name1}" present but there is no ' +f'{field_name2}') continue # Check param_info to see if this is a longitude field cmd = f""" form_type FROM {q(pi_table_name)} WHERE CATEGORY_NAME='{obs_table_name}' AND NAME='{field_name1}'""" res = db.general_select(cmd) if len(res) == 0: logger.log('error', f'No param_info entry for "{full_obs_table_name}.{field_name1}"') continue if len(res) > 1: logger.log('error', f'More than one param_info entry for "{full_obs_table_name}.{field_name1}"') continue pi_form_type = res[0][0] if pi_form_type is None or pi_form_type.startswith('LONG'): continue cmd = f""" opus_id FROM {q(full_obs_table_name)} WHERE {q(field_name2)} < {q(field_name1)}""" res = db.general_select(cmd) if len(res): opus_ids = [x[0] for x in res] logger.log('error', f'Column "{full_obs_table_name}.{field_name1}" has values greater than '+ f'{field_name2} for some OPUS IDs; first 100: ' + ' '.join(opus_ids[:100])) def validate_filter_wavelength_consistency(namespace): # For each mission and instrument, then for each filter, look at the # wavelength table and see if the wl1 and wl2 fields contain only a single # value. db = impglobals.DATABASE logger = impglobals.LOGGER logger.log('debug', 'Validating filter/wavelength consistency') obs_table_names = sorted(list(db.table_names(namespace, prefix='obs_'))) q = db.quote_identifier wl_table = q('obs_wavelength') wl_fields = ('wavelength1', 'wavelength2', 'wave_res1', 'wave_res2', 'wave_no1', 'wave_no2', 'wave_no_res1', 'wave_no_res2', 'spec_size') for obs_table_name in obs_table_names: full_obs_table_name = db.convert_raw_to_namespace(namespace, obs_table_name) column_list = db.table_info(namespace, obs_table_name) for column in column_list: field_name = column['field_name'] if field_name not in ('filter_name', 'combined_filter'): continue # Select obs_wavelength entries that match, group by filter name, # and check the range for the various wavelength fields if obs_table_name == 'obs_instrument_coiss': cmd = f"{q('camera')}, {q(field_name)}" start_col = 2 else: cmd = f"{q(field_name)}" start_col = 1 for wl_field in wl_fields: cmd += f", MIN(IFNULL({q(wl_field)}, 'NULL'))" cmd += f", MAX(IFNULL({q(wl_field)}, 'NULL'))" cmd += f""" FROM {q(full_obs_table_name)} LEFT JOIN {wl_table} ON {q(full_obs_table_name)}.{q('obs_general_id')} = {wl_table}.{q('obs_general_id')}""" if obs_table_name == 'obs_instrument_coiss': cmd += f"GROUP BY {q('camera')}, {q(field_name)}" else: cmd += f"GROUP BY {q(field_name)}" res = db.general_select(cmd) for row in res: for col in range(start_col, len(row)-1, 2): pretty_filter = ':'.join(row[0:start_col]) if row[col] != row[col+1]: logger.log('warning', f'"obs_wavelength.{wl_fields[(col-start_col)//2]}" has inconsistent' +f' values for {full_obs_table_name} filter "{pretty_filter}": ' +f'{row[col]} and {row[col+1]}') def do_validate(namespace='perm'): impglobals.LOGGER.open( 'Performing database validation', limits={'info': -1, 'debug': -1}) validate_param_info(namespace) validate_nulls(namespace) validate_min_max_order(namespace) validate_filter_wavelength_consistency(namespace) impglobals.LOGGER.close()
import random import networkx as nx class Graph: def __init__(self, n=100, e=200, p=0.001, init_scale=None): self.n = n if e > n * (n - 1) / 2: self.e = n * (n - 1) / 2 else: self.e = e self.graph = nx.empty_graph(self.n) self.nodes = list(self.graph.nodes) self.edges = [] self.p = p self.init_scale = init_scale def print_nodes(self): print(self.nodes) def random_graph(self): i = self.e self.edges = [] while i > 0: st_rand = random.choice(self.nodes) nd_rand = random.choice(self.nodes) if st_rand != nd_rand: tmp_p = random.uniform(0, 1) if tmp_p < self.p and not self.graph.has_edge(*(nd_rand, st_rand)): self.graph.add_edge(*(st_rand, nd_rand)) i = i - 1 return self.edges def create_random_graph(self): return self.random_graph() def get_graph(self): return self.graph def create_scale_free_graph(self): self.graph = nx.complete_graph(self.init_scale) self.nodes = list(self.graph.nodes) j = self.n i = self.init_scale while i < j: if not self.graph.has_node(i): self.graph.add_node(i) st_rand = i nd_rand = random.choice(self.nodes) prob = self.graph.degree(int(nd_rand)) / len(self.graph.edges) if self.add_edge(st_rand, nd_rand, prob): i = i + 1 i = self.e - len(self.graph.edges) while i > 0: st_rand = random.choice(list(self.graph.nodes)) nd_rand = random.choice(list(self.graph.nodes)) graph_deg = len(self.graph.edges) nd_rand_deg = self.graph.degree(int(nd_rand)) prob = nd_rand_deg / graph_deg if self.add_edge(st_rand, nd_rand, prob): i = i - 1 def create_scale_free_motif(self): self.graph = nx.complete_graph(2) self.nodes = list(self.graph.nodes) j = self.n i = self.init_scale while i < j: if not self.graph.has_node(i): self.graph.add_node(i) st_rand = i nd_rand = random.choice(self.nodes) prob = self.graph.degree(int(nd_rand)) / len(self.graph.edges) if self.add_edge(st_rand, nd_rand, prob): i = i + 1 i = self.e - len(self.graph.edges) while i > 0: st_rand = random.choice(list(self.graph.nodes)) nd_rand = random.choice(list(self.graph.nodes)) graph_deg = len(self.graph.edges) nd_rand_deg = self.graph.degree(int(nd_rand)) prob = nd_rand_deg / graph_deg if self.add_edge(st_rand, nd_rand, prob): i = i - 1 def add_edge(self, st_rand, nd_rand, prob, graph=None): if not graph: graph = self.graph if st_rand != nd_rand: tmp_p = random.uniform(0, 1) if tmp_p < prob and not graph.has_edge(*(st_rand, nd_rand)): graph.add_edge(*(st_rand, nd_rand)) return True return False def compose_graph(self, nd_graph): mapping = {} tmp_nodes = [] st_graph = self.graph for i in range(0, self.n): mapping[i] = self.n + i tmp_nodes.append(i + self.n) st_graph = nx.relabel_nodes(st_graph, mapping) tmp_g = nx.compose(st_graph, nd_graph) st_graph_nodes = list(st_graph.node) nd_graph_nodes = list(nd_graph.node) edges_cnt = self.e while edges_cnt > 0: st_rand = random.choice(st_graph_nodes) nd_rand = random.choice(nd_graph_nodes) if self.add_edge(st_rand, nd_rand, self.p, tmp_g): edges_cnt = edges_cnt - 1 return tmp_g
#print("Initializing NEW 3-head model") import sys from pyprojroot import here proj_path = here() #these next three lines are to important important TSM module functionality sys.path.append(str(proj_path / "MULTITASK_FILES/TSM_FILES/temporal-shift-module/")) from ops.basic_ops import ConsensusModule from ops.transforms import * import torch.nn as nn import torch import math from torch.nn.functional import softmax import torch.utils.model_zoo as model_zoo from torchvision.ops import nms from torchvision.models.video.resnet import VideoResNet, _video_resnet r2p1d = torchvision.models.video.r2plus1d_18(pretrained=False, progress=True, num_classes=4) layer4_r2p1d = r2p1d.layer1 avgpool_r2p1d = r2p1d.avgpool fc_r2p1d = r2p1d.fc print("MODEL IS", r2p1d) print("New layers are", layer4_r2p1d, avgpool_r2p1d, "THEN", fc_r2p1d) print("Imported _make_layer!") from retinanet.utils import BasicBlock, Bottleneck, BBoxTransform, ClipBoxes from retinanet.anchors import Anchors from retinanet import losses model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', } class PyramidFeatures(nn.Module): def __init__(self, C3_size, C4_size, C5_size, feature_size=256): super(PyramidFeatures, self).__init__() # upsample C5 to get P5 from the FPN paper self.P5_1 = nn.Conv2d(C5_size, feature_size, kernel_size=1, stride=1, padding=0) self.P5_upsampled = nn.Upsample(scale_factor=2, mode='nearest') self.P5_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) # add P5 elementwise to C4 self.P4_1 = nn.Conv2d(C4_size, feature_size, kernel_size=1, stride=1, padding=0) self.P4_upsampled = nn.Upsample(scale_factor=2, mode='nearest') self.P4_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) # add P4 elementwise to C3 self.P3_1 = nn.Conv2d(C3_size, feature_size, kernel_size=1, stride=1, padding=0) self.P3_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1) # "P6 is obtained via a 3x3 stride-2 conv on C5" self.P6 = nn.Conv2d(C5_size, feature_size, kernel_size=3, stride=2, padding=1) # "P7 is computed by applying ReLU followed by a 3x3 stride-2 conv on P6" self.P7_1 = nn.ReLU() self.P7_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=2, padding=1) def forward(self, inputs): C3, C4, C5 = inputs P5_x = self.P5_1(C5) P5_upsampled_x = self.P5_upsampled(P5_x) P5_x = self.P5_2(P5_x) P4_x = self.P4_1(C4) P4_x = P5_upsampled_x + P4_x P4_upsampled_x = self.P4_upsampled(P4_x) P4_x = self.P4_2(P4_x) P3_x = self.P3_1(C3) P3_x = P3_x + P4_upsampled_x P3_x = self.P3_2(P3_x) P6_x = self.P6(C5) P7_x = self.P7_1(P6_x) P7_x = self.P7_2(P7_x) return [P3_x, P4_x, P5_x, P6_x, P7_x] class ActionModel(nn.Module): def __init__(self, num_actions=4): super(ActionModel, self).__init__() self.r2p1d_block = layer4_r2p1d #self.avgpool = avgpool_r2p1d #nn.AdaptiveAvgPool2d(1) self.avgpool = nn.AdaptiveAvgPool2d(1) #self.fc = nn.Dropout(p=0.8) self.new_fc = nn.Linear(in_features=2048, out_features=4, bias=True) self.consensus = ConsensusModule("avg") def forward(self, x): #print("Entering into action head with size", x.shape) x = x.unsqueeze(0) #print("Unsqueezed to", x.shape) x = self.r2p1d_block(x) print("After R(2+1)D block", x.shape) x = self.avgpool(x) x = self.new_fc(x.squeeze()) x = x.view((-1, 8) + x.size()[1:]) out = self.consensus(x) return out.squeeze(1) class RegressionModel(nn.Module): def __init__(self, num_features_in, num_anchors=9, feature_size=256): super(RegressionModel, self).__init__() self.conv1 = nn.Conv2d(num_features_in, feature_size, kernel_size=3, padding=1) self.act1 = nn.ReLU() self.conv2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1) self.act2 = nn.ReLU() self.conv3 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1) self.act3 = nn.ReLU() self.conv4 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1) self.act4 = nn.ReLU() self.output = nn.Conv2d(feature_size, num_anchors * 4, kernel_size=3, padding=1) def forward(self, x): out = self.conv1(x) out = self.act1(out) out = self.conv2(out) out = self.act2(out) out = self.conv3(out) out = self.act3(out) out = self.conv4(out) out = self.act4(out) out = self.output(out) # out is B x C x W x H, with C = 4*num_anchors out = out.permute(0, 2, 3, 1) return out.contiguous().view(out.shape[0], -1, 4) class ClassificationModel(nn.Module): def __init__(self, num_features_in, num_anchors=9, num_classes=80, prior=0.01, feature_size=256): super(ClassificationModel, self).__init__() self.num_classes = num_classes self.num_anchors = num_anchors self.conv1 = nn.Conv2d(num_features_in, feature_size, kernel_size=3, padding=1) self.act1 = nn.ReLU() self.conv2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1) self.act2 = nn.ReLU() self.conv3 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1) self.act3 = nn.ReLU() self.conv4 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1) self.act4 = nn.ReLU() self.output = nn.Conv2d(feature_size, num_anchors * num_classes, kernel_size=3, padding=1) self.output_act = nn.Sigmoid() def forward(self, x): out = self.conv1(x) out = self.act1(out) out = self.conv2(out) out = self.act2(out) out = self.conv3(out) out = self.act3(out) out = self.conv4(out) out = self.act4(out) out = self.output(out) out = self.output_act(out) # out is B x C x W x H, with C = n_classes + n_anchors out1 = out.permute(0, 2, 3, 1) batch_size, width, height, channels = out1.shape out2 = out1.view(batch_size, width, height, self.num_anchors, self.num_classes) return out2.contiguous().view(x.shape[0], -1, self.num_classes) class ResNet(nn.Module): def __init__(self, num_classes, block, layers): self.num_batches = 1 self.inplanes = 64 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(64) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) if block == BasicBlock: fpn_sizes = [self.layer2[layers[1] - 1].conv2.out_channels, self.layer3[layers[2] - 1].conv2.out_channels, self.layer4[layers[3] - 1].conv2.out_channels] elif block == Bottleneck: fpn_sizes = [self.layer2[layers[1] - 1].conv3.out_channels, self.layer3[layers[2] - 1].conv3.out_channels, self.layer4[layers[3] - 1].conv3.out_channels] else: raise ValueError(f"Block type {block} not understood") self.fpn = PyramidFeatures(fpn_sizes[0], fpn_sizes[1], fpn_sizes[2]) ###################################################### self.regressionModel = RegressionModel(256) self.classificationModel = ClassificationModel(256, num_classes=num_classes) ###################################################### self.regressionModel_hands = RegressionModel(256) self.classificationModel_hands = ClassificationModel(256, num_classes=num_classes) ###################################################### ######CREATE ACTION HEAD##### #print("Creating action head") self.action_model = ActionModel() self.action_loss_criterion = nn.BCELoss() ############################# self.anchors = Anchors() self.regressBoxes = BBoxTransform() self.clipBoxes = ClipBoxes() self.focalLoss = losses.FocalLoss() for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() prior = 0.01 self.classificationModel.output.weight.data.fill_(0) self.classificationModel.output.bias.data.fill_(-math.log((1.0 - prior) / prior)) self.regressionModel.output.weight.data.fill_(0) self.regressionModel.output.bias.data.fill_(0) self.classificationModel_hands.output.weight.data.fill_(0) self.classificationModel_hands.output.bias.data.fill_(-math.log((1.0 - prior) / prior)) self.regressionModel_hands.output.weight.data.fill_(0) self.regressionModel_hands.output.bias.data.fill_(0) self.freeze_bn() def train(self, mode=True): """ Override the default train() to freeze the BN parameters :return: """ super(ResNet, self).train(mode) count = 0 if mode: #print("Freezing BN layers as we enter training mode!") for m in self.modules(): if isinstance(m, nn.BatchNorm2d): count += 1 if count >= 2: m.eval() m.weight.requires_grad = False m.bias.requires_grad = False def _make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [block(self.inplanes, planes, stride, downsample)] self.inplanes = planes * block.expansion for i in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) def freeze_bn(self): '''Freeze BatchNorm layers.''' for layer in self.modules(): if isinstance(layer, nn.BatchNorm2d): layer.eval() def forward(self, inputs): if self.training: img_batch, annotations = inputs else: img_batch = inputs x = self.conv1(img_batch) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x1 = self.layer1(x) x2 = self.layer2(x1) x3 = self.layer3(x2) x4 = self.layer4(x3) features = self.fpn([x2, x3, x4]) regression_tools = torch.cat([self.regressionModel(feature) for feature in features], dim=1) classification_tools = torch.cat([self.classificationModel(feature) for feature in features], dim=1) regression_hands = torch.cat([self.regressionModel_hands(feature) for feature in features], dim=1) classification_hands = torch.cat([self.classificationModel_hands(feature) for feature in features], dim=1) anchors = self.anchors(img_batch) if self.training: hand_annotations = annotations.clone() for b in range(hand_annotations.shape[0]): for a in range(hand_annotations.shape[1]): if int(hand_annotations[b, a, 4]) in {0, 1, 2}: hand_annotations[b, a, :] = -1 tool_annotations = annotations.clone() for b in range(tool_annotations.shape[0]): for a in range(tool_annotations.shape[1]): if int(tool_annotations[b, a, 4]) in {3}: tool_annotations[b, a, :] = -1 ####WORKING WITH ACTION HEAD #### if x4.shape[0] >= 8: action_logits = self.action_model(x4) action_logits = action_logits.view(-1, int(action_logits.shape[0]/self.num_batches), action_logits.shape[1]) action_logits = action_logits.mean(1) action_logits = softmax(action_logits) #print("LOGITS ARE", action_logits) else: action_logits = torch.tensor([0, 0, 0, 0]) #print("ACTION LOGITS ARE", action_logits) ################################# class_loss_hand, reg_loss_hand = self.focalLoss(classification_hands, regression_hands, anchors, hand_annotations) class_loss_tool, reg_loss_tool = self.focalLoss(classification_tools, regression_tools, anchors, tool_annotations) #had to add one term to the return statement below here for actions return 0.5*(class_loss_hand + class_loss_tool), 0.5*(reg_loss_hand + reg_loss_tool), action_logits else: ##########Finally#inference#on#actions#head########## if img_batch.shape[0] > 1: #this is what we do if we're evaluating the action head ####WORKING WITH ACTION HEAD #### action_logits = self.action_model(x4) action_logits = action_logits.view(-1, int(action_logits.shape[0]/self.num_batches), action_logits.shape[1]) action_logits = action_logits.mean(1) action_logits = softmax(action_logits) ################################# else: #this is what we'll do if we're evaluating the detection head on a single frame action_logits = None ###################################################### final_nms_scores = [] final_nms_class = [] final_transformed_anchors = [] for i in range(classification_hands.shape[0]): #STAGE 1: Analysis of hands transformed_anchors_hands = self.regressBoxes(anchors, regression_hands) transformed_anchors_hands = self.clipBoxes(transformed_anchors_hands, img_batch) #grab max scores for each box, across four classes (although really we should only look at column 4...) will still work #think the 0 means its the value, not the arg scores_hands = torch.max(classification_hands, dim=2, keepdim=True)[0] scores_over_thresh_hands = (scores_hands > 0.05)[i, :, 0] frame_classification_hands = classification_hands[:, scores_over_thresh_hands, :] transformed_anchors_hands = transformed_anchors_hands[:, scores_over_thresh_hands, :] scores_hands = scores_hands[:, scores_over_thresh_hands, :] anchors_nms_idx_hands = nms(transformed_anchors_hands[i,:,:], scores_hands[i,:,0], 0.5) if len(anchors_nms_idx_hands) == 0: #if found no reasonable hand indices nms_scores_hands, nms_class_hands = torch.zeros([1]).cuda(0), torch.zeros([1]).cuda(0) frame_anchors_hands = torch.zeros([1,4]).cuda(0) else: frame_anchors_hands = transformed_anchors_hands[i, anchors_nms_idx_hands, :] nms_scores_hands, nms_class_hands = frame_classification_hands[i, anchors_nms_idx_hands, :].max(dim=1) #STAGE 2: Analysis of tools transformed_anchors_tools = self.regressBoxes(anchors, regression_tools) transformed_anchors_tools = self.clipBoxes(transformed_anchors_tools, img_batch) #grab max scores for each box, across four classes (although really we should only look at column 4...) will still work #think the 0 means its the value, not the arg scores_tools = torch.max(classification_tools, dim=2, keepdim=True)[0] scores_over_thresh_tools = (scores_tools > 0.05)[i, :, 0] frame_classification_tools = classification_tools[:, scores_over_thresh_tools, :] transformed_anchors_tools = transformed_anchors_tools[:, scores_over_thresh_tools, :] scores_tools = scores_tools[:, scores_over_thresh_tools, :] anchors_nms_idx_tools = nms(transformed_anchors_tools[i,:,:], scores_tools[i,:,0], 0.5) if len(anchors_nms_idx_tools) == 0: #found no reasonable tool indices in the current frame nms_scores_tools, nms_class_tools = torch.zeros([1]).cuda(0), torch.zeros([1]).cuda(0) frame_anchors_tools = torch.zeros([1,4]).cuda(0) else: frame_anchors_tools = transformed_anchors_tools[i, anchors_nms_idx_tools, :] nms_scores_tools, nms_class_tools = frame_classification_tools[i, anchors_nms_idx_tools, :].max(dim=1) #STAGE 3: Concatenate hands and tools, and append to the growing list frame by frame #append classes and scores, therefore making a list with hands and tools frame_class = torch.cat((nms_class_hands, nms_class_tools), 0) frame_scores = torch.cat((nms_scores_hands, nms_scores_tools), 0) frame_anchors_total = torch.cat((frame_anchors_hands, frame_anchors_tools), 0) #add it to the batches inference final_nms_scores.append(frame_scores) final_nms_class.append(frame_class) final_transformed_anchors.append(frame_anchors_total) return [final_nms_scores, final_nms_class, final_transformed_anchors, action_logits] def resnet18(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(num_classes, BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'], model_dir='.'), strict=False) return model def resnet34(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(num_classes, BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'], model_dir='.'), strict=False) return model def resnet50(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(num_classes, Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'], model_dir='.'), strict=False) return model def resnet101(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(num_classes, Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'], model_dir='.'), strict=False) return model def resnet152(num_classes, pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(num_classes, Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'], model_dir='.'), strict=False) return model
<gh_stars>0 import copy import inspect import math import cv2 import mmcv import numpy as np from numpy import random from mmdet.core import PolygonMasks from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from ..builder import PIPELINES @PIPELINES.register_module() class RandomRotate: ''' modify by randomaffine,and normal ''' def __init__(self, max_rotate_degree=180.0, max_translate_ratio=0.3, scaling_ratio_range=(0.5, 1.5), max_shear_degree=2.0, border=(0, 0), border_val=(114, 114, 114), min_bbox_size=2, min_area=20, min_bboxscaling=0.2 # max_aspect_ratio=20 ): assert 0 <= max_translate_ratio <= 1 assert scaling_ratio_range[0] <= scaling_ratio_range[1] assert scaling_ratio_range[0] > 0 self.max_rotate_degree = max_rotate_degree self.max_translate_ratio = max_translate_ratio self.scaling_ratio_range = scaling_ratio_range self.max_shear_degree = max_shear_degree self.border = border self.border_val = border_val self.min_bbox_size = min_bbox_size self.min_area = min_area self.min_bboxscaling=min_bboxscaling # self.max_aspect_ratio = max_aspect_ratio def __call__(self, results): img = results['img'] height = img.shape[0] + self.border[0] * 2 width = img.shape[1] + self.border[1] * 2 # Center center_matrix = np.eye(3, dtype=np.float32) # Identity matrix center_matrix[0, 2] = -img.shape[1] / 2 # x translation (pixels),center as origin center_matrix[1, 2] = -img.shape[0] / 2 # y translation (pixels) # Rotation rotation_degree = random.uniform(-self.max_rotate_degree, self.max_rotate_degree) rotation_matrix = self._get_rotation_matrix(rotation_degree) # Scaling scaling_ratio = random.uniform(self.scaling_ratio_range[0], self.scaling_ratio_range[1]) scaling_matrix = self._get_scaling_matrix(scaling_ratio) # Shear x_degree = random.uniform(-self.max_shear_degree, self.max_shear_degree) y_degree = random.uniform(-self.max_shear_degree, self.max_shear_degree) shear_matrix = self._get_shear_matrix(x_degree, y_degree) # Translation trans_x = random.uniform(0.5 - self.max_translate_ratio, 0.5 + self.max_translate_ratio) * width trans_y = random.uniform(0.5 - self.max_translate_ratio, 0.5 + self.max_translate_ratio) * height translate_matrix = self._get_translation_matrix(trans_x, trans_y) warp_matrix = ( translate_matrix @ shear_matrix @ rotation_matrix @ scaling_matrix @ center_matrix) # Matrix multiplication img = cv2.warpPerspective( img, warp_matrix, dsize=(width, height), borderValue=self.border_val) results['img'] = img results['img_shape'] = img.shape # print(results['img_info']) for key in results.get('bbox_fields', []): polygons = results[key] num_polygons = len(polygons) if num_polygons: # homogeneous coordinates ,advanced indexing xs = polygons[:, [0, 2, 4, 6]].reshape(num_polygons * 4) # [x1,x2,x3,x4,...] ys = polygons[:, [1, 3, 5, 7]].reshape(num_polygons * 4) # [y1,y2,y3,y4,...] ones = np.ones_like(xs) points = np.vstack([xs, ys, ones]) warp_points = warp_matrix @ points warp_points = warp_points[:2] / warp_points[2] # xs = warp_points[0].reshape(num_polygons, 4) # [[x1,x2,x3,x4],...] # ys = warp_points[1].reshape(num_polygons, 4) # [[],...] xs = warp_points[0] # [x1,x2,x3,...] ys = warp_points[1] # [y1,y2,y3,...] warp_polygons=np.zeros(num_polygons*8) # print(warp_polygons.size,xs.size) warp_polygons[0::2]=xs warp_polygons[1::2]=ys warp_polygons=warp_polygons.reshape(num_polygons,8) # warp_polygons=[(x/width,y/height) for x in xs for y in ys] #and normalization # warp_polygons=np.float32(np.array(warp_polygons)).reshape(num_polygons, 4) # [[(x1,y1),(x2,y2),(x3,y3),(x4,y4)],...] # poly = np.float32(np.array(poly)) # bboxs=[] # for poly in warp_polygons: # rect = cv2.minAreaRect(poly) # 得到最小外接矩形的(中心(x,y), (宽,高), 旋转角度) # # box = np.float32(cv2.boxPoints(rect)) # 返回rect四个点的值 # # c_x = rect[0][0] # c_y = rect[0][1] # w = rect[1][0] # h = rect[1][1] # theta = rect[-1] # Range for angle is [-90,0) # # trans_data = self.cvminAreaRect2longsideformat(c_x, c_y, w, h, theta) # if not trans_data: # if theta != 90: # Θ=90说明wh中有为0的元素,即gt信息不完整,无需提示异常,直接删除 # print('opencv表示法转长边表示法出现异常,已将第%d个box排除,问题出现在该图片中:%s' % (i, img_fullname)) # num_gt = num_gt - 1 # continue # else: # # range:[-180,0) # c_x, c_y, longside, shortside, theta_longside = trans_data # # if (sum(bbox <= 0) + sum(bbox[:2] >= 1)) >= 1: # 0<xy<1, 0<side<=1 # print('bbox[:2]中有>= 1的元素,bbox中有<= 0的元素,已将第%d个box排除,问题出现在该图片中:%s' % (i, img_fullname)) # print('出问题的longside形式数据:[%.16f, %.16f, %.16f, %.16f, %.1f]' % ( # c_x, c_y, longside, shortside, theta_longside)) # num_gt = num_gt - 1 # continue # if (obj['name'] in extractclassname): # id = extractclassname.index(obj['name']) # id=类名的索引 比如'plane'对应id=0 # else: # print('预定类别中没有类别:%s;已将该box排除,问题出现在该图片中:%s' % (obj['name'], fullname)) # num_gt = num_gt - 1 # continue # theta_label = int(theta_longside + 180.5) # range int[0,180] 四舍五入 # if theta_label == 180: # range int[0,179] # theta_label = 179 # # outline='id x y longside shortside Θ' # bbox=[c_x, c_y, longside, shortside,theta_label] # # bbox = np.array((c_x, c_y, longside, shortside,theta_label)) # # warp_bboxs = np.vstack( # # (xs.min(1), ys.min(1), xs.max(1), ys.max(1))).T #left top right bottom # bboxs.append(bbox) # # warp_bboxes=np.array(bboxs) # # warp_bboxes[:, [0, 2]] = warp_bboxes[:, [0, 2]].clip(0, width) # # warp_bboxes[:, [1, 3]] = warp_bboxes[:, [1, 3]].clip(0, height) # warp_bboxes[:, [4]] = warp_bboxes[:, [4]].clip(0, 179) # for warp_poly in warp_polygons: # idx1=warp_poly[0]<width&warp_poly[1]<height # idx2=warp_poly[2]<width&warp_poly[3]<height # idx3=warp_poly[4]<width&warp_poly[5]<height # idx4=warp_poly[6]<width&warp_poly[7]<height warp_polygons[:,[0,2,4,6]]=warp_polygons[:,[0,2,4,6]].clip(0,width) warp_polygons[:,[1,3,5,7]]=warp_polygons[:,[1,3,5,7]].clip(0,height) # filter polygons # valid_index = self.filter_gt_ploygons(polygons,warp_polygons) # print(valid_index) valid_index=np.repeat(valid_index,2,axis=1) results[key] = warp_polygons[valid_index] if key in ['gt_polygons']: if 'gt_labels' in results: results['gt_labels'] = results['gt_labels'][ valid_index] return results def filter_gt_ploygons(self, origin_polygons,wrapped_polygons): origin_w = np.maximum(origin_polygons[:, [0, 2, 4, 6]],1) - np.minimum(origin_polygons[:, [0, 2, 4, 6]],1) origin_h = np.maximum(origin_polygons[:, [1, 3, 5, 7]],1) - np.minimum(origin_polygons[:, [1, 3, 5, 7]],1) # origin_w = origin_bboxes[:, 2] - origin_bboxes[:, 0] # origin_h = origin_bboxes[:, 3] - origin_bboxes[:, 1] # wrapped_w = wrapped_bboxes[:, 2] - wrapped_bboxes[:, 0] # wrapped_h = wrapped_bboxes[:, 3] - wrapped_bboxes[:, 1] wrapped_w=np.maximum(wrapped_polygons[:,[0,2,4,6]],1)-np.minimum(wrapped_polygons[:,[0,2,4,6]],1) wrapped_h=np.maximum(wrapped_polygons[:,[1,3,5,7]],1)-np.minimum(wrapped_polygons[:,[1,3,5,7]],1) # aspect_ratio = np.maximum(wrapped_w / (wrapped_h + 1e-16), # wrapped_h / (wrapped_w + 1e-16)) wh_valid_idx = (wrapped_w > self.min_bbox_size) & \ (wrapped_h > self.min_bbox_size) scal_valid_idx = wrapped_w * wrapped_h / (origin_w * origin_h + 1e-16) > self.min_bboxscaling area_valid_idx = wrapped_w * wrapped_h>self.min_area # aspect_ratio_valid_idx = aspect_ratio < self.max_aspect_ratio return wh_valid_idx & area_valid_idx & scal_valid_idx# & aspect_ratio_valid_idx def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(max_rotate_degree={self.max_rotate_degree}, ' repr_str += f'max_translate_ratio={self.max_translate_ratio}, ' repr_str += f'scaling_ratio={self.scaling_ratio_range}, ' repr_str += f'max_shear_degree={self.max_shear_degree}, ' repr_str += f'border={self.border}, ' repr_str += f'border_val={self.border_val}, ' repr_str += f'min_bbox_size={self.min_bbox_size}, ' repr_str += f'min_area_ratio={self.min_area_ratio}, ' repr_str += f'max_aspect_ratio={self.max_aspect_ratio})' return repr_str @staticmethod def _get_rotation_matrix(rotate_degrees): radian = math.radians(rotate_degrees) rotation_matrix = np.array( [[np.cos(radian), -np.sin(radian), 0.], [np.sin(radian), np.cos(radian), 0.], [0., 0., 1.]], dtype=np.float32) return rotation_matrix @staticmethod def _get_scaling_matrix(scale_ratio): scaling_matrix = np.array( [[scale_ratio, 0., 0.], [0., scale_ratio, 0.], [0., 0., 1.]], dtype=np.float32) return scaling_matrix @staticmethod def _get_share_matrix(scale_ratio): scaling_matrix = np.array( [[scale_ratio, 0., 0.], [0., scale_ratio, 0.], [0., 0., 1.]], dtype=np.float32) return scaling_matrix @staticmethod def _get_shear_matrix(x_shear_degrees, y_shear_degrees): x_radian = math.radians(x_shear_degrees) y_radian = math.radians(y_shear_degrees) shear_matrix = np.array([[1, np.tan(x_radian), 0.], [np.tan(y_radian), 1, 0.], [0., 0., 1.]], dtype=np.float32) return shear_matrix @staticmethod def _get_translation_matrix(x, y): translation_matrix = np.array([[1, 0., x], [0., 1, y], [0., 0., 1.]], dtype=np.float32) return translation_matrix # @staticmethod # def cvminAreaRect2longsideformat(x_c, y_c, width, height, theta): # ''' # trans minAreaRect(x_c, y_c, width, height, θ) to longside format(x_c, y_c, longside, shortside, θ) # 两者区别为: # 当opencv表示法中width为最长边时(包括正方形的情况),则两种表示方法一致 # 当opencv表示法中width不为最长边 ,则最长边表示法的角度要在opencv的Θ基础上-90度 # @param x_c: center_x # @param y_c: center_y # @param width: x轴逆时针旋转碰到的第一条边 # @param height: 与width不同的边 # @param theta: x轴逆时针旋转与width的夹角,由于原点位于图像的左上角,逆时针旋转角度为负 [-90, 0) # @return: # x_c: center_x # y_c: center_y # longside: 最长边 # shortside: 最短边 # theta_longside: 最长边和x轴逆时针旋转的夹角,逆时针方向角度为负 [-180, 0) # ''' # ''' # 意外情况:(此时要将它们恢复符合规则的opencv形式:wh交换,Θ置为-90) # 竖直box:box_width < box_height θ=0 # 水平box:box_width > box_height θ=0 # ''' # if theta == 0: # theta = -90 # buffer_width = width # width = height # height = buffer_width # # if theta > 0: # if theta != 90: # Θ=90说明wh中有为0的元素,即gt信息不完整,无需提示异常,直接删除 # print('θ计算出现异常,当前数据为:%.16f, %.16f, %.16f, %.16f, %.1f;超出opencv表示法的范围:[-90,0)' % (x_c, y_c, width, height, theta)) # return False # # if theta < -90: # print('θ计算出现异常,当前数据为:%.16f, %.16f, %.16f, %.16f, %.1f;超出opencv表示法的范围:[-90,0)' % (x_c, y_c, width, height, theta)) # return False # # if width != max(width, height): # 若width不是最长边 # longside = height # shortside = width # theta_longside = theta - 90 # else: # 若width是最长边(包括正方形的情况) # longside = width # shortside = height # theta_longside = theta # # if longside < shortside: # print('旋转框转换表示形式后出现问题:最长边小于短边;[%.16f, %.16f, %.16f, %.16f, %.1f]' % (x_c, y_c, longside, shortside, theta_longside)) # return False # if (theta_longside < -180 or theta_longside >= 0): # print('旋转框转换表示形式时出现问题:θ超出长边表示法的范围:[-180,0);[%.16f, %.16f, %.16f, %.16f, %.1f]' % (x_c, y_c, longside, shortside, theta_longside)) # return False # # return x_c, y_c, longside, shortside, theta_longside
# NOTE: bad django practice but /ee specifically depends on /posthog so it should be fine from datetime import datetime, timedelta from typing import Any, Dict, List, Optional, Tuple from dateutil.relativedelta import relativedelta from django.db.models.expressions import F from django.utils import timezone from rest_framework import serializers from rest_framework.decorators import action from rest_framework.request import Request from rest_framework.response import Response from sentry_sdk.api import capture_exception from ee.clickhouse.client import sync_execute from ee.clickhouse.models.action import format_action_filter, format_entity_filter from ee.clickhouse.models.cohort import format_filter_query from ee.clickhouse.models.person import ClickhousePersonSerializer from ee.clickhouse.models.property import parse_prop_clauses from ee.clickhouse.queries.util import get_trunc_func_ch, parse_timestamps from ee.clickhouse.sql.person import ( GET_LATEST_PERSON_SQL, INSERT_COHORT_ALL_PEOPLE_THROUGH_DISTINCT_SQL, PEOPLE_SQL, PEOPLE_THROUGH_DISTINCT_SQL, PERSON_STATIC_COHORT_TABLE, PERSON_TREND_SQL, ) from ee.clickhouse.sql.stickiness.stickiness_people import STICKINESS_PEOPLE_SQL from posthog.api.action import ActionSerializer, ActionViewSet from posthog.api.utils import get_target_entity from posthog.constants import ENTITY_ID, ENTITY_TYPE, TREND_FILTER_TYPE_ACTIONS from posthog.models.action import Action from posthog.models.cohort import Cohort from posthog.models.entity import Entity from posthog.models.filters import Filter from posthog.models.filters.stickiness_filter import StickinessFilter from posthog.models.property import Property from posthog.models.team import Team class ClickhouseActionSerializer(ActionSerializer): is_calculating = serializers.SerializerMethodField() def get_count(self, action: Action) -> Optional[int]: if self.context.get("view") and self.context["view"].action != "list": query, params = format_action_filter(action) if query == "": return None return sync_execute( "SELECT count(1) FROM events WHERE team_id = %(team_id)s AND {}".format(query), {"team_id": action.team_id, **params}, )[0][0] return None def get_is_calculating(self, action: Action) -> bool: return False class ClickhouseActionsViewSet(ActionViewSet): serializer_class = ClickhouseActionSerializer # Don't calculate actions in Clickhouse as it's on the fly def _calculate_action(self, action: Action) -> None: pass def list(self, request: Request, *args: Any, **kwargs: Any) -> Response: actions = self.get_queryset() actions_list: List[Dict[Any, Any]] = self.serializer_class(actions, many=True, context={"request": request}).data # type: ignore return Response({"results": actions_list}) @action(methods=["GET"], detail=False) def people(self, request: Request, *args: Any, **kwargs: Any) -> Response: team = self.team filter = Filter(request=request) entity = get_target_entity(request) current_url = request.get_full_path() serialized_people = calculate_entity_people(team, entity, filter) current_url = request.get_full_path() next_url: Optional[str] = request.get_full_path() offset = filter.offset if len(serialized_people) > 100 and next_url: if "offset" in next_url: next_url = next_url[1:] next_url = next_url.replace("offset=" + str(offset), "offset=" + str(offset + 100)) else: next_url = request.build_absolute_uri( "{}{}offset={}".format(next_url, "&" if "?" in next_url else "?", offset + 100) ) else: next_url = None return Response( { "results": [{"people": serialized_people[0:100], "count": len(serialized_people[0:99])}], "next": next_url, "previous": current_url[1:], } ) def _handle_date_interval(filter: Filter) -> Filter: # adhoc date handling. parsed differently with django orm date_from = filter.date_from or timezone.now() data = {} if filter.interval == "month": data.update( {"date_to": (date_from + relativedelta(months=1) - timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")} ) elif filter.interval == "week": data.update({"date_to": (date_from + relativedelta(weeks=1)).strftime("%Y-%m-%d %H:%M:%S")}) elif filter.interval == "hour": data.update({"date_to": date_from + timedelta(hours=1)}) elif filter.interval == "minute": data.update({"date_to": date_from + timedelta(minutes=1)}) return Filter(data={**filter._data, **data}) def _process_content_sql(team: Team, entity: Entity, filter: Filter): filter = _handle_date_interval(filter) parsed_date_from, parsed_date_to, _ = parse_timestamps(filter=filter, team_id=team.pk) entity_sql, entity_params = format_entity_filter(entity=entity) person_filter = "" person_filter_params: Dict[str, Any] = {} if filter.breakdown_type == "cohort" and filter.breakdown_value != "all": cohort = Cohort.objects.get(pk=filter.breakdown_value) person_filter, person_filter_params = format_filter_query(cohort) person_filter = "AND distinct_id IN ({})".format(person_filter) elif ( filter.breakdown_type == "person" and isinstance(filter.breakdown, str) and isinstance(filter.breakdown_value, str) ): person_prop = Property(**{"key": filter.breakdown, "value": filter.breakdown_value, "type": "person"}) filter.properties.append(person_prop) prop_filters, prop_filter_params = parse_prop_clauses( filter.properties, team.pk, filter_test_accounts=filter.filter_test_accounts ) params: Dict = {"team_id": team.pk, **prop_filter_params, **entity_params, "offset": filter.offset} content_sql = PERSON_TREND_SQL.format( entity_filter=f"AND {entity_sql}", parsed_date_from=parsed_date_from, parsed_date_to=parsed_date_to, filters=prop_filters, breakdown_filter="", person_filter=person_filter, ) return content_sql, {**params, **person_filter_params} def calculate_entity_people(team: Team, entity: Entity, filter: Filter): content_sql, params = _process_content_sql(team, entity, filter) people = sync_execute( PEOPLE_THROUGH_DISTINCT_SQL.format( content_sql=content_sql, latest_person_sql=GET_LATEST_PERSON_SQL.format(query="") ), params, ) serialized_people = ClickhousePersonSerializer(people, many=True).data return serialized_people def insert_entity_people_into_cohort(cohort: Cohort, entity: Entity, filter: Filter): content_sql, params = _process_content_sql(cohort.team, entity, filter) sync_execute( INSERT_COHORT_ALL_PEOPLE_THROUGH_DISTINCT_SQL.format( cohort_table=PERSON_STATIC_COHORT_TABLE, content_sql=content_sql, latest_person_sql=GET_LATEST_PERSON_SQL.format(query=""), ), {"cohort_id": cohort.pk, "_timestamp": datetime.now(), **params}, ) class LegacyClickhouseActionsViewSet(ClickhouseActionsViewSet): legacy_team_compatibility = True
#!/usr/bin/env python # coding: utf-8 # # Frequentist vs Bayesian # # <p style="color:blue"> <NAME></p> # <p style="color:blue">Station10 Ltd</p> # ```{image} ./Bayesian-vs-frequentist.png # :class: bg-primary mb-1 # :width: 500px # :align: center # ``` # ## 1. The problem formulation # In a marketing campaign, a retailer sends a coupon to the customer. How likely is it that the customer will buy the product? Maybe we should give it a shot since it won't cost us a lot. Statistically, we can make some experiments, estimate the probability, and then decide how to mark targets based on the results. Global warming is a big topic that is relevant to all people on the planet. As we are an independent thinker, not the ones who follow the crowd, we would like to ask: Is it possible to still do some random experiments for the conclusion? Maybe it is absolutely impossible. # # We need impeccable logic and support from data! # # Generally speaking, there are two schools of thought in the field of data science and machine learning: the Bayesian and the frequentist. By analyzing their basic assumptions, this blog will explain the theoretical foundations and backgrounds of these two schools. # # # Suppose there is system$f_\theta$, $\theta$ is a vector. The random variable $X$ is generated from the system. # # $$ # X \sim p(x|\theta) # $$ # How to estate the parameter $\theta$ from the observation $x$ from frequentist and Bayesian? # ## 2、Frequentist # ```{image} ./god-prospective.jpg # :class: bg-primary mb-1 # :width: 500px # :align: center # ``` # A frequentist believes that the world is determinstic. There is an ontology, and its true value is constant. Our goal is to determine this value or the range in which it lies. However, the true values are unknown. The only way to estimate true values are through the random phenomena that result from them. # # In a jar with seven red balls and three blue balls, for example, if we randomly take out one ball and record it before putting it back in the jar. The probability that we will take out the red ball each time is $70\%$. The probability, no matter how the experiment is performed, is objective and unique. It is this objective fact that underpins the series of observations. Let us assume the unknown probability is $\theta$ and we can estimate it. If we perform $100$ experiments and get a red ball $72$ times, we can intuitively estimate that it is $72\%$ red, and since there are only $10$ balls in the jar, we can determine that the most plausable estimation is that there are $7$ red balls. # # This is in fact an optimization problem with a maximum likelihood function. # # Suppose the probability of getting out red ball is $\theta$, which is the Bernolli distribution: # # $$ # p(x_i, \theta) = \theta^{x_i}(1-\theta)^{(1-x_i)} # $$ # # $x_i = 1$ indicates that we get read ball, and $x_i = 0$ for blue ball # # # Suppose we perform $n$ experiments. In theory, $\theta$ can take any value between $0$ and $1$, including $0$ and $1$. This is $\theta\in[0, 1]$. The $n$ experiments can produce arbitrary permutations of length $n$ sequence with elements of $0$s and $1$s. The total number of sequences is the permutations is $2^n$. But, after one round of our experiments, we only get one of $2^n$ possibility in the sequence $0,1$. # # Why did we get this sequence and not any other in one experiment? It is the physical reality that there are $10$ balls in the jar, $7$ of which are red balls which makes the observation happened. This objective reality determines $\theta$, and $\theta$ in turn determines which sequence is most likely to be observed. That is, $\theta$ makes the most likely sequence to occur. Represent this idea using mathematical formulation: # # $$ # \theta = argmax_\theta\prod_{i=1}^N\theta^{x_i}(1-\theta)^{1-x_i} # $$ # # For ease of calculation, take the logarithm of the above equation: # # $$ # \theta = \underset{\theta}{\operatorname{argmax}}\sum_{i=1}^Nlog(\theta^{x_i}(1-\theta)^{1-x_i}) = \underset{\theta}{\operatorname{argmax}}(-\sum_{i=1}^Nlog(\theta^{x_i}(1-\theta)^{1-x_i})) # $$ # # Let $L=-\sum_{i=1}^Nlog(\theta^{x_i}(1-\theta)^{1-x_i})$, and we calculate the derivative of $L$ with respect to $\theta$: # # $$ # \frac{\partial L}{\partial \theta} = -\sum_{i=1}^N(\frac{x_i}{\theta} + (1-x_i)\frac{-1}{1-\theta}) = 0 # $$ # # We get: # # $$ # \hat \theta = \frac{\sum_i^N x_i}{N} # $$ # # # # ## 3. Bayesian # ```{image} ./bayesian.jpg # :class: bg-primary mb-1 # :width: 500px # :align: center # ``` # The Bayesian does not attempt to say that 'events themselves are random', or that 'the world is somehow random in its ontology'. It starts from the point of 'imperfect knowledge of the observer' and constructs a framework for making inferences based on uncertain of the knowledge. # # The random event in the eyes of frequentist is not random any more in the view of Bayesian, but is only unknown to the observer. So, the observer makes inferring from the observed evidence. The randomness is not arising from whether the event itself occurred or not, but merely describes the state of the observer's knowledge of the event. # # Bayesian probabilities are based on limited knowledge, while frequentists describe the ontology. An observer's knowledge is updated when a new observation is made according to a Bayesian theorem. In Bayesian probability theory, it is assumed that the observer has limited knowledge of the event (for instance, Tom believes *a priori* that a coin is even based on his daily observations and feelings). Once the observer gets new observations (Tom tosses the coin over and over again and discovers that out of 100 tosses, only 20 come up heads), that will affect the observer's original beliefs in the form of logical uncertainty (Tom doubts the coin is even and even begins to conclude it is not even). Because incomplete information prevents the observer from relying on simple logic to form inferences, he must turn to plausible reasoning, which assigns plausibility to a range of possible outcomes. # # # By way of example, Bayesian analysis describes the above process as the observer holding a particular prior belief, gaining new evidence through observation, and combining the new observed evidence and prior knowledge to arrive at a posterior belief, which reflects an updated state of knowledge. Bayesian probabilistic inference is concerned with building a logical system from incomplete knowledge and an assertion as a measure of plausibility. An observer's beliefs or knowledge about a variable is called a probability distribution by a frequentist. In a Bayesian approach, representations of human knowledge are constructed rather than representations of the objective world. Bayesian probabilistic inference is, therefore, in many cases a better approach to solving the problem of observer inference in machine learning and bypasses the discussion about ontology. # # The mathematical representation of the above discussion is: # # # $$ # p(\theta|x) = \frac{p(x|\theta)p(\theta)}{p(x)} # $$ # # where, # # # $$ # p(x) = \int p(x|\theta)p(\theta)d\theta # $$ # # By using the likelihood function, Bayes' theorem relates the prior probability to the posterior probability. We can get the maximum posterior probability: # # $$ # \hat \theta = \theta_{max} = \underset{\theta}{\operatorname{argmax}} p(\theta|x) # = \underset{\theta}{\operatorname{argmax}}\frac{p(x|\theta)p(\theta)}{p(x)} # = \underset{\theta}{\operatorname{argmax}} p(x|\theta)p(\theta) # $$ # # # The powerful and fascinating part of Bayesian reasoning is that we start with subjective *a priori* beliefs and acquire an objective knowledge of the world by objective iterative observation. For example, we can obtain the posterior probabilities by combining evidence and prior probabilities. However, if we receive new evidence again, we can update our posterior probabilities by combining the previously obtained posterior probabilities with the new evidence. It can be is an iterative process. # # Below I will use one simple example to show the process of iterative. # # # Incidence of breast cancer $0.1\%$ in the some place. If the person has breast cancer, the test positive is $90\%$ and if the person has no breast cancer, the test nagative is $90\%$. Suppose, these is a woman, whose the first time test is positive. How much posibility she has breast cancer? How about if the second time her test is still positive? How do you make decision if you were the doctor? # # If we have no information, we randomly take one person, who has the probability of $0.001$ to have breast cancer. This is the prior probability. $p(c)=0.001$. The person has cancer and the test is positive, which means $p(+|c) = 0.9$. So $p(-|c) = 0.1$. If a person has no cancer, the $p(-|\bar c) = 0.9$ and $p(-|\bar c) = 0.1$. # # So, after the first test is positive. # # $$ # p(c|+) = \frac{p(c)p(+|c)}{p(c)p(+|c) + p(\bar c)p(+|\bar c)} = \frac{0.001x0.9}{0.001x0.9 + 0.999x0.1} \approx 0.9\% # $$ # # So, the first test as positive only means that she has 0.9% probability to have cancer. Maybe at this time the doctor can't confirm the woman has cancer. # # How about if the second time is still positive? # # We take posterior probability($p(c|+) \approx 0.009$) as the prior probability of second time test. So, $p(c) = 0.009$ now. # # $$ # p(c|+) = \frac{p(c)p(+|c)}{p(c)p(+|c) + p(\bar c)p(+|\bar c)} = \frac{0.009x0.9}{0.009x0.9 + 0.991x0.1} \approx 7.6\% # $$ # # Maybe now the doctor stll can't confirm the woman has cancer. She will need further test # # This example shows the process of how to update our beliefs with new evidence using Bayesian reasoning. # ## 4. Comments # We'll get the method based on how we look at the problem. The frequentist believes that the parameters are objective and do not change, even if they are unknown. The optimization of the likelihood function based on the observations can sometimes produce very extreme results. The Bayesian, on the other hand, believes that all parameters have random values and thus have probability distributions. Bayesian estimates of posterior distributions based on prior knowledge combined with new evidence do not produce extreme results. Because all parameters are random variables with distributions, Bayesians can use some sampling algorithm (e.g., MCMC), making it easier to build complex models.
<filename>dataviva/apps/models.py # -*- coding: utf-8 -*- from flask import g from dataviva import db, __latest_year__ from dataviva.utils.auto_serialize import AutoSerialize from dataviva.utils.title_case import title_case from dataviva.attrs.models import Bra, Isic, Hs, Cbo, Wld import ast, re build_ui = db.Table('apps_build_ui', db.Column('build_id', db.Integer,db.ForeignKey('apps_build.id')), db.Column('ui_id', db.Integer,db.ForeignKey('apps_ui.id')) ) class App(db.Model, AutoSerialize): __tablename__ = 'apps_app' id = db.Column(db.Integer, primary_key = True) type = db.Column(db.String(20)) name_en = db.Column(db.String(20)) name_pt = db.Column(db.String(20)) viz_whiz = db.Column(db.String(20)) color = db.Column(db.String(7)) def name(self): lang = getattr(g, "locale", "en") return getattr(self,"name_"+lang) def serialize(self, **kwargs): auto_serialized = super(App, self).serialize() del auto_serialized["name_en"] del auto_serialized["name_pt"] auto_serialized["name"] = self.name() return auto_serialized class Build(db.Model, AutoSerialize): __tablename__ = 'apps_build' id = db.Column(db.Integer, primary_key = True) dataset = db.Column(db.String(20)) bra = db.Column(db.String(20)) filter1 = db.Column(db.String(20)) filter2 = db.Column(db.String(20)) output = db.Column(db.String(20)) title_en = db.Column(db.String(120)) title_pt = db.Column(db.String(120)) app_id = db.Column(db.Integer, db.ForeignKey(App.id)) ui = db.relationship('UI', secondary=build_ui, backref=db.backref('Builds'), lazy='dynamic') app = db.relationship('App', backref=db.backref('Builds', lazy='dynamic')) def get_ui(self, ui_type): return self.ui.filter(UI.type == ui_type).first() def set_bra(self, bra_id): '''If build requires 2 bras and only 1 is given, supply a 2nd''' if isinstance(self.bra, list): return if bra_id == 'bra': bra_id = 'all' if "_" in self.bra and "_" not in bra_id: if bra_id == "rj": bra_id = bra_id + "_mg" else: bra_id = bra_id + "_rj" elif "_" not in self.bra and "_" in bra_id: bra_id = bra_id.split("_")[0] self.bra = [] for i, b in enumerate(bra_id.split("_")): if b == "all": self.bra.append(Wld.query.get("sabra")) self.bra[i].id = "all" else: if "." in b: split = b.split(".") b = split[0] dist = split[1] else: dist = 0 state = b[:2] if self.output == "bra" and len(b) == 8 and dist == 0: b = state dist = 0 self.bra.append(Bra.query.get(b)) self.bra[i].distance = dist self.bra[i].neighbor_ids = [b.bra_id_dest for b in self.bra[i].get_neighbors(dist)] # raise Exception([b.id for b in self.bra[i].pr.all()]) self.bra[i].pr_ids = [b.id for b in self.bra[i].pr.all()] def set_filter1(self, filter): if self.filter1 != "all": if self.dataset == "rais": self.isic = [] for i, f in enumerate(filter.split("_")): if Isic.query.get(f): self.isic.append(Isic.query.get(f)) else: self.isic.append(Isic.query.get('r9000')) self.filter1 = "_".join([i.id for i in set(self.isic)]) elif self.dataset == "secex": self.hs = [] for i, f in enumerate(filter.split("_")): if Hs.query.get(f): self.hs.append(Hs.query.get(f)) else: self.hs.append(Hs.query.get('178703')) self.filter1 = "_".join([h.id for h in set(self.hs)]) def set_filter2(self, filter): if self.filter2 != "all": if self.dataset == "rais": self.cbo = [] for i, f in enumerate(filter.split("_")): if Cbo.query.get(f): self.cbo.append(Cbo.query.get(f)) else: self.cbo.append(Cbo.query.get('2211')) self.filter2 = "_".join([c.id for c in set(self.cbo)]) elif self.dataset == "secex": self.wld = [] for i, f in enumerate(filter.split("_")): if Wld.query.get(f): self.wld.append(Wld.query.get(f)) else: self.wld.append(Wld.query.get('aschn')) self.filter2 = "_".join([w.id for w in set(self.wld)]) '''Returns the URL for the specific build.''' def url(self, **kwargs): if isinstance(self.bra,(list,tuple)): bras = [] for b in self.bra: if b.id != "all" and b.distance > 0: bras.append(b.id+"."+b.distance) else: bras.append(b.id) bra_id = "_".join(bras) else: bra_id = "<bra>" url = '{0}/{1}/{2}/{3}/{4}/{5}/'.format(self.app.type, self.dataset, bra_id, self.filter1, self.filter2, self.output) return url '''Returns the data URL for the specific build. This URL will return the data required for building a viz of this app. ''' def data_url(self, **kwargs): bras = [] if isinstance(self.bra,(list,tuple)): for b in self.bra: if b.id != "all" and b.distance > 0: bras.append(b.id+"."+b.distance) else: bras.append(b.id) bra = "_".join(bras) else: bra = "<bra>" if self.output == "bra": if bra == "all" and self.app.type == "geo_map": bra = "show.2" elif bra == "all": bra = "show.8" else: bra = bra + ".show.8" filter1 = self.filter1 if filter1 == "all" or self.app.type == "rings": if self.output == "isic": filter1 = "show.5" elif self.output == "hs": filter1 = "show.6" filter2 = self.filter2 if filter2 == "all" or self.app.type == "rings": if self.output == "cbo": filter2 = "show.4" elif self.output == "wld": filter2 = "show.5" data_url = '{0}/all/{1}/{2}/{3}/'.format(self.dataset, bra, filter1, filter2) return data_url '''Returns the data table required for this build''' def data_table(self): from dataviva.rais.models import Ybi, Ybo, Yio, Yb_rais, Yi, Yo from dataviva.secex.models import Ybp, Ybw, Ypw, Yb_secex, Yp, Yw # raise Exception(self.output) if self.dataset == "rais": # raise Exception(self.bra[0], self.filter1, self.filter2, self.output) if self.bra[0].id == "all" and self.output != "bra": return Yio elif self.output == "isic" or (self.output == "bra" and self.filter2 == "all"): return Ybi elif self.output == "cbo" or (self.output == "bra" and self.filter1 == "all"): return Ybo elif self.dataset == "secex": if self.bra[0].id == "all" and self.output != "bra": return Ypw elif self.output == "hs" or (self.output == "bra" and self.filter2 == "all"): return Ybp elif self.output == "wld" or (self.output == "bra" and self.filter1 == "all"): return Ybw if self.filter1 == "all": return Ybw elif self.filter1 == "all": return Ybp '''Returns the english language title of this build.''' def title(self, **kwargs): lang = g.locale if "lang" in kwargs: lang = kwargs["lang"] title_lang = "title_en" if lang == "en" else "title_pt" name_lang = "name_en" if lang == "en" else "name_pt" title = getattr(self, title_lang) depths = {"en":{"plural":{},"single":{}},"pt":{"plural":{},"single":{}}} depths["en"]["single"] = {"2":u"State","4":u"Mesoregion","8":u"Municipality"} depths["en"]["plural"] = {"2":u"States","4":u"Mesoregions","8":u"Municipalities"} depths["pt"]["single"] = {"2":u"Estado","4":u"Mesorregião","8":u"Município"} depths["pt"]["plural"] = {"2":u"Estados","4":u"Mesorregiões","8":u"Municípios"} if "depth" in kwargs and u"bra_" in kwargs["depth"][0] and kwargs["depth"][0] != "bra_8": if depths[lang]["plural"]["8"] in title: title = title.replace(depths[lang]["plural"]["8"],depths[lang]["plural"][kwargs["depth"][0][4:]]) if depths[lang]["single"]["8"] in title: title = title.replace(depths[lang]["single"]["8"],depths[lang]["single"][kwargs["depth"][0][4:]]) if self.output == "bra" and isinstance(self.bra,(list,tuple)) and self.bra[0].id == "all": title = title.replace(depths[lang]["plural"]["8"],depths[lang]["plural"]["2"]) title = title.replace(depths[lang]["single"]["8"],depths[lang]["single"]["2"]) if self.app_id != 2: if "year" in kwargs: year = kwargs["year"] else: year = __latest_year__[self.dataset] title += " ({0})".format(year) def get_article(attr, article): if attr.article_pt: if attr.gender_pt == "m": if article == "em": new_article = "no" if article == "de": new_article = "do" if article == "para": new_article = "para o" elif attr.gender_pt == "f": if article == "em": new_article = "na" if article == "de": new_article = "da" if article == "para": new_article = "para a" if attr.plural_pt: new_article = new_article + "s" return new_article else: return article if title: if lang == "pt": joiner = " e " else: joiner = " and " if "<bra>" in title and isinstance(self.bra,(list,tuple)): bras = [] for b in self.bra: name = title_case(getattr(b, name_lang)) if b.id != "all" and b.distance > 0: name = name + " "+b.distance+"km" bras.append(name) article_search = re.search('<bra_(\w+)>', title) if article_search: title = title.replace(" <bra>", "") title = title.replace(article_search.group(0), joiner.join([get_article(b, article_search.group(1)) + " " + bras[i] for i, b in enumerate(self.bra)])) else: title = title.replace("<bra>", joiner.join(bras)) if "<isic>" in title and hasattr(self,"isic"): title = title.replace("<isic>", joiner.join([title_case(getattr(i, name_lang)) for i in self.isic])) article_search = re.search('<isic_(\w+)>', title) if article_search: title = title.replace(article_search.group(0), joiner.join([get_article(b, article_search.group(1)) for b in self.isic])) if "<hs>" in title and hasattr(self,"hs"): title = title.replace("<hs>", joiner.join([title_case(getattr(h, name_lang)) for h in self.hs])) article_search = re.search('<hs_(\w+)>', title) if article_search: title = title.replace(article_search.group(0), joiner.join([get_article(b, article_search.group(1)) for b in self.hs])) if "<cbo>" in title and hasattr(self,"cbo"): title = title.replace("<cbo>", joiner.join([title_case(getattr(c, name_lang)) for c in self.cbo])) article_search = re.search('<cbo_(\w+)>', title) if article_search: title = title.replace(article_search.group(0), joiner.join([get_article(b, article_search.group(1)) for b in self.cbo])) if "<wld>" in title and hasattr(self,"wld"): title = title.replace("<wld>", joiner.join([title_case(getattr(w, name_lang)) for w in self.wld])) article_search = re.search('<wld_(\w+)>', title) if article_search: title = title.replace(article_search.group(0), joiner.join([get_article(b, article_search.group(1)) for b in self.wld])) return title def serialize(self, **kwargs): auto_serialized = super(Build, self).serialize() if isinstance(self.bra,(list,tuple)): auto_serialized["bra"] = [b.serialize() for b in self.bra] for i,b in enumerate(auto_serialized["bra"]): if b["id"] != "all" and self.bra[i].distance: b["distance"] = self.bra[i].distance b["neighbor_ids"] = self.bra[i].neighbor_ids elif b["id"] != "all" and len(self.bra[i].pr_ids): b["pr_ids"] = self.bra[i].pr_ids if hasattr(self, "isic"): auto_serialized["isic"] = [i.serialize() for i in self.isic] if hasattr(self, "hs"): auto_serialized["hs"] = [h.serialize() for h in self.hs] if hasattr(self, "cbo"): auto_serialized["cbo"] = [c.serialize() for c in self.cbo] if hasattr(self, "wld"): auto_serialized["wld"] = [w.serialize() for w in self.wld] del auto_serialized["title_en"] del auto_serialized["title_pt"] auto_serialized["title"] = self.title() #auto_serialized["id_item"] = self.title() auto_serialized["data_url"] = self.data_url() auto_serialized["url"] = self.url() auto_serialized["ui"] = [ui.serialize() for ui in self.ui.all()] auto_serialized["app"] = self.app.serialize() return auto_serialized def __repr__(self): return '<Build %s:%r: %s/%s/%s>' % (self.id, self.app.type, self.filter1, self.filter2, self.output) class UI(db.Model, AutoSerialize): __tablename__ = 'apps_ui' id = db.Column(db.Integer, db.ForeignKey(Build.id), primary_key = True) type = db.Column(db.String(20)) values = db.Column(db.String(255)) def serialize(self, **kwargs): auto_serialized = super(UI, self).serialize() auto_serialized["values"] = ast.literal_eval(self.values) return auto_serialized def __repr__(self): return '<Build %r: %r>' % (self.type, self.values)
from pyb import I2C import uasyncio as asyncio import ustruct as struct from utils import Timer import ulogging as logging logger = logging.Logger(__name__) class Motor: """A class to represent a motor and offers an API to control it. Additionnal documentation can be found here: - http://learn.makeblock.com/en/me-encoder-motor-driver/ - https://github.com/Makeblock-official/Makeblock-Libraries/blob/master/src/MeEncoderMotor.cpp """ HEADER = [0xA5, 0x01] END = 0x5A CMD_MOVE_SPD = 0x05 CMD_MOVE_SPD_TIME = 0x08 CMD_RESET = 0x07 CMD_MOVE_AGL = 0x11 def __init__(self, pin: int, addr: int, slot: int): """Initialize I2C communication to motor. Args: pin: I2C bus' pin (2 or 4) addr: slave's address slot: motor's slot (1 or 2) """ self.__slot = slot - 1 self.__addr = addr self.__i2c = I2C(pin) self.__i2c.init(I2C.MASTER) self.__speed = 0 self._stopper = Timer(callback=self.stop) @property def speed(self): return self.__speed async def __send_data(self, data: list): """Creates a trame from the data and send it to motor via I2C. Args: data: [slot, CMD, args]: data to send """ lrc = self._lrc_calc(data) data_size = self._to_bytes("l", len(data)) trame = Motor.HEADER + data_size + data + [lrc, Motor.END] self.__i2c.send(bytearray(trame), self.__addr) await asyncio.sleep_ms(20) # A few wait time is needed for the motor. def __recv_data(self, length: int) -> bytearray: """Receives data from I2C slave's address Args: length number of bytes to receive Returns: buffer: data received in bytes """ buffer = bytearray(length) self.__i2c.recv(buffer, self.__addr) return buffer def scan(self) -> list: """Scan slaves connected to the current I2C pin. Returns: list_of_slaves: addresses of slaves that respond """ list_of_slaves = self.__i2c.scan() return list_of_slaves async def run(self, speed: float, time=None) -> None: """Controls motor rotation with speed given for an optional time. Args: speed: rotation speed (RPM) in [-200, +200] time: in seconds, runs for a specified time """ if self.__i2c.is_ready(self.__addr): # Sets time limits to [-200 , +200] and convert it in bytes if speed < -200: speed = -200 elif speed > 200: speed = 200 if speed != self.__speed: speed_bytes = self._to_bytes("f", speed) data = [self.__slot, Motor.CMD_MOVE_SPD] + speed_bytes self.__speed = speed await self.__send_data(data) if time: self._stopper.cancel() self._stopper.start(timeout=time) else: raise RuntimeError("Motor {} cannot be run.".format(self.__slot)) async def move(self, angle: float, speed: float) -> None: """Move motor of angle degrees at a speed given. Args: speed: rotation speed (RPM) in [-200, +200] angle: angle in degrees to rotate. """ if speed < -200: speed = -200 elif speed > 200: speed = 200 if speed != self.__speed: self.__speed = speed time = (angle / 360 * 60) / speed await self.run(speed, time) async def stop(self): """Reset motor position to 0 and reinitialize data received.""" data = [self.__slot, Motor.CMD_RESET] await self.__send_data(data) self.__speed = 0 @staticmethod def _lrc_calc(data) -> int: """Calculate the Longitudinal Redondancy Check (LRC) Returns: lrc: the value of LRC """ lrc = 0x00 for byte in data: lrc ^= byte return lrc @staticmethod def _to_bytes(fmt: str, data) -> list: """Convert and pack data with a given format The list of available formats can be found here: https://docs.python.org/3/library/struct.html Args: fmt: string used to pack the data from a given format. data: data to be converted to bytes. Returns: data_bytes: a list of each element of data converted to bytes. """ data_bytes = list(struct.pack(fmt, data)) return data_bytes
import torch as th from torch import nn import models import math import time import timeit class RNN_builtin(nn.Module): def __init__(self, win, wrec, wout, brec, bout): super(RNN_builtin, self).__init__() s = win.shape self.rnn = nn.RNN(s[0], s[1], 1) self.rnn.weight_ih_l0.data = win.t().clone() self.rnn.weight_hh_l0.data = wrec.t().clone() self.wout = nn.Parameter(wout.clone(), requires_grad=True) self.rnn.bias_ih_l0.data[:] = 0 self.rnn.bias_ih_l0.requires_grad_(False) self.rnn.bias_hh_l0.data = brec.clone() self.bout = nn.Parameter(bout.clone(), requires_grad=True) def forward(self, inputs): hids = self.rnn(inputs) # print(hids[0][:,-1].shape) # print(self.wout.shape) # print((hids[0][:,-1] @ self.wout).shape) return hids[0][:,-1] @ self.wout + self.bout # def profile(): if __name__ == '__main__': d = 10 N = 5 c = 2 b = 10 T = 6 lr = .005 win = th.randn(d, N) / math.sqrt(10) wrec = th.randn(N,N) / math.sqrt(5) wout = th.randn(N,c) brec = th.zeros(N) bout = th.zeros(c) num_batches = 2000 def train_model(model, optimizer): bhalf = int(round(b/2)) for i0 in range(num_batches): optimizer.zero_grad() model.zero_grad() inputs = th.zeros(b, T, d) inputs_0 = 0.1*th.randn(bhalf, T, d) - 0.2 inputs_0[:, 1:] = 0 inputs_1 = 0.1*th.randn(bhalf, T, d) + 0.2 inputs_1[:, 1:] = 0 inputs[:bhalf] = inputs_0 inputs[bhalf:] = inputs_1 targets = th.zeros(b, 2) targets[:bhalf] = th.Tensor([1, 0]) targets[bhalf:] = th.Tensor([0, 1]) out = model(inputs) loss = th.mean(th.norm(out - targets)**2) # print(loss.item()) loss.backward() optimizer.step() # rnn1 = th.jit.script(RNN_builtin(win, wrec, wout, brec, bout)) # optimizer1 = th.optim.SGD(filter(lambda p: p.requires_grad, rnn1.parameters()), lr=lr) # rnn2 = th.jit.script(models.RNN(win, wrec, wout, brec, bout, nonlinearity='tanh', train_input=True)) # rnn2 = th.jit.trace(models.RNN(win, wrec, wout, brec, bout, nonlinearity='tanh', train_input=True), # th.zeros(b, T, d)) rnn2 = models.RNN(win, wrec, wout, brec, bout, nonlinearity='tanh', train_input=True) optimizer2 = th.optim.SGD(filter(lambda p: p.requires_grad, rnn2.parameters()), lr=lr) # tic = time.time() # train_model(rnn1, optimizer1) # toc = time.time() # print(toc-tic) tic = time.time() train_model(rnn2, optimizer2) toc = time.time() print(toc-tic) # print # if __name__ == '__main__': # print(timeit.timeit("profile()", setup="from __main__ import profile"))
<reponame>liuxk99/sjPomotodo # encoding=utf-8 # ------------------------------------------------------------------------------- # Name: pomo # Purpose: python client for pomotodo # # Author: thomas # # Created: 07/07/2021 # Copyright: (c) thomas 2021 # Licence: <your licence> # coding=utf-8 # ------------------------------------------------------------------------------- """ [ { "uuid": "ac753187-2f22-4b5c-b716-f1fcecfb4410", "created_at": "2016-08-06T06:48:52.000Z", "updated_at": "2016-08-06T06:51:12.000Z", "description": "Catch some little Monsters", "notice": null, "pin": false, "completed": false, "completed_at": null, "repeat_type": "none", "remind_time": null, "estimated_pomo_count": null, "costed_pomo_count": 0, "sub_todos": [ "81921b2e-8b54-46cf-bb47-0d3c3c7e8302", "ff59811e-4c53-404f-a842-9590b632616f" ] } ] """ import re import datetime_utils class Pomo: def __init__(self, uuid, created_at, updated_at, description, pin, completed, completed_at, repeat_type, estimated_pomo_count, costed_pomo_count, started_at, ended_at, local_started_at, local_ended_at, length, abandoned=False, manual=False): self._uuid = uuid self._created_at = created_at self._updated_at = updated_at self._description = description self._pin = pin self._started_at = started_at self._ended_at = ended_at self._local_started_at = local_started_at self._local_ended_at = local_ended_at self._length = length self._abandoned = abandoned self._manual = manual def __str__(self): uuid = str(self._uuid) created_at = self._created_at.isoformat() updated_at = self._updated_at.isoformat() description = self._description started_at = self._started_at.isoformat() ended_at = self._ended_at.isoformat() local_started_at = self._local_started_at.isoformat() local_ended_at = self._local_ended_at.isoformat() length = str(self._length) abandoned = str(self._abandoned) manual = str(self._manual) return (u'uuid: %s\n started_at: %s, ended_at: %s\n' u' local_started_at: %s, local_ended_at: %s\n' u' description: %s\n' u' create_at: %s, update_at: %s\n' u' length: %s, abandoned: %s, manual: %s\n' % (uuid, started_at, ended_at, local_started_at, local_ended_at, description, created_at, updated_at, length, abandoned, manual)).encode("utf-8") @staticmethod def from_json(e): uuid = e[u'uuid'] created_at = e[u'created_at'] updated_at = e[u'updated_at'] description = e[u'description'] started_at = e[u'started_at'] ended_at = e[u'ended_at'] local_started_at = e[u'local_started_at'] local_ended_at = e[u'local_ended_at'] length = e[u'length'] abandoned = e[u'abandoned'] manual = e[u'manual'] return Pomo(uuid, datetime_utils.from_iso8601(created_at), datetime_utils.from_iso8601(updated_at), description, datetime_utils.from_iso8601(started_at), datetime_utils.from_iso8601(ended_at), datetime_utils.from_iso8601(local_started_at), datetime_utils.from_iso8601(local_ended_at), length, abandoned, manual) pass
<reponame>fahlmant/openshift-tools #!/usr/bin/env python # vim: expandtab:tabstop=4:shiftwidth=4 #This is not a module, but pylint thinks it is. This is a command. #pylint: disable=invalid-name """ ops-runner: Script that runs commands and sends result data to zabbix. """ import argparse import sys from subprocess import Popen, PIPE, STDOUT import random import time import re import fcntl import tempfile import os import atexit import datetime import socket # Reason: disable pylint import-error because our libs aren't loaded on jenkins. # Status: temporary until we start testing in a container where our stuff is installed. # pylint: disable=import-error from openshift_tools.monitoring.metric_sender import MetricSender from openshift_tools.timeout import timeout, TimeoutException NAME = "ops-runner" OPS_RUNNER_LOG_FILE = "/var/log/%s.log" % NAME OPS_RUNNER_LOCK_FILE_PREFIX = "/var/tmp/%s-" % NAME OPS_RUNNER_DISC_KEY = 'disc.ops.runner' OPS_RUNNER_DISC_MACRO = '#OSO_COMMAND' OPS_RUNNER_EXITCODE_KEY = 'disc.ops.runner.command.exitcode' OPS_RUNNER_TIMEOUT_KEY = 'disc.ops.runner.command.timeout' class OpsRunner(object): """ class to run a command and report results to zabbix """ def __init__(self): """ constructor """ self.args = None self.parse_args() self.tmp_file_handle = None self.lock_file_handle = None def create_tmp_file(self): """ Create the temporary file where command output is stored """ prefix = NAME + '-' + self.args.name + "-" self.tmp_file_handle = tempfile.NamedTemporaryFile(prefix=prefix, mode='w', delete=False) # Ensure that we clean up the tmp file on exit atexit.register(self.cleanup) def cleanup(self): """ Cleans up resources when we're done (like the temp file). This runs on exit. """ self.verbose_print("Removing temp file [%s]" % self.tmp_file_handle.name) self.tmp_file_handle.close() os.remove(self.tmp_file_handle.name) def verbose_print(self, msg): """ Prints a message if we're in verbose mode """ if self.args.verbose: print msg @staticmethod def fail(msg): """ prints a message and then exits the script """ print "ERROR: %s" % msg sys.exit(10) def check_flock(self): """ wrap details on file locking behavior """ if self.args.flock or self.args.flock_no_fail: lock_aquired = self.attempt_to_lock_file() if not lock_aquired: if self.args.flock_no_fail: self.verbose_print('Process already running. Exit quietly.') sys.exit(0) else: self.fail('this process is already running.') def check_sleep(self): """ pause for a random number (bounded) of seconds if needed""" if self.args.random_sleep: rand = random.Random() # seed the rng using the hostname and check name. That means that for each hostname/check, # it will sleep the same amount every time for a given self.args.random_sleep rand.seed(hash(socket.gethostname()+self.args.name)) seconds = rand.randrange(int(self.args.random_sleep)) self.verbose_print("Sleeping %s seconds..." % seconds) time.sleep(seconds) def run_cmd(self): """ run specified command (with a max wait if specified) """ timedout = False if self.args.timeout: try: with timeout(self.args.timeout): exit_code = self.run_cmd_with_output(self.args.rest) except TimeoutException: exit_code = 1 timedout = True else: exit_code = self.run_cmd_with_output(self.args.rest) return (exit_code, timedout) def run(self): """ main function to run the script """ # Creating a file where all output will be written self.create_tmp_file() # Attempt flock if specified # We want to flock before we potentially sleep, just to # keep multiple process from running at the same time. self.check_flock() # Random Sleep if specified self.check_sleep() # Run the specified command exit_code, timedout = self.run_cmd() if self.args.flock: self.unlock_file() if timedout: self.report_to_zabbix(OPS_RUNNER_DISC_KEY, OPS_RUNNER_DISC_MACRO, OPS_RUNNER_EXITCODE_KEY, exit_code) self.report_to_zabbix(OPS_RUNNER_DISC_KEY, OPS_RUNNER_DISC_MACRO, OPS_RUNNER_TIMEOUT_KEY, self.args.timeout) else: self.report_to_zabbix(OPS_RUNNER_DISC_KEY, OPS_RUNNER_DISC_MACRO, OPS_RUNNER_EXITCODE_KEY, exit_code) self.report_to_zabbix(OPS_RUNNER_DISC_KEY, OPS_RUNNER_DISC_MACRO, OPS_RUNNER_TIMEOUT_KEY, 0) self.verbose_print("CMD Exit code: %s" % exit_code) if exit_code != 0: # We need to close it so we can re-open it to read from self.tmp_file_handle.close() if os.access(OPS_RUNNER_LOG_FILE, os.W_OK): self.verbose_print("Non-zero exit code, writing output to %s" % OPS_RUNNER_LOG_FILE) self.log_output(exit_code) else: self.verbose_print("Non-zero exit code, writing output to logger.") self.run_cmd_with_output(['/usr/bin/logger', '-t', NAME + ' ' + self.args.name, '-f', self.tmp_file_handle.name], log=False) sys.exit(exit_code) def log_output(self, exit_code): """ Copies the contents of the tmp file to the logfile """ ts = time.time() date_str = datetime.datetime.fromtimestamp(ts).strftime("%b %d %H:%M:%S") hostname = socket.gethostname() with open(OPS_RUNNER_LOG_FILE, 'a') as log_output: log_output.write("%s %s %s %s: Exit code [%s]:~" % (date_str, hostname, NAME, self.args.name, exit_code)) with open(self.tmp_file_handle.name, 'r') as tmp_input: for line in tmp_input: # We don't want any newlines in the log file line = re.sub('\n', "~", line) log_output.write(line) log_output.write('\n') def report_to_zabbix(self, disc_key, disc_macro, item_proto_key, value): """ Sends the commands exit code to zabbix. """ mts = MetricSender() # Add the dynamic item self.verbose_print("Adding the dynamic item to Zabbix - %s, %s, [%s]" % \ (disc_key, disc_macro, self.args.name)) mts.add_dynamic_metric(disc_key, disc_macro, [self.args.name]) # Send the value for the dynamic item self.verbose_print("Sending metric to Zabbix - %s[%s]: %s" % \ (item_proto_key, self.args.name, value)) mts.add_metric({'%s[%s]' % (item_proto_key, self.args.name): value}) # Actually send them mts.send_metrics() def parse_args(self): """ parse the args from the cli """ parser = argparse.ArgumentParser(description='ops-runner - Runs commands and reports results to zabbix.') parser.add_argument('-n', '--name', required=True, help='Name identifier for this command.') parser.add_argument('-s', '--random-sleep', help='Sleep time, random. Insert a random ' + \ 'sleep between 1 and X number of seconds.') parser.add_argument('-v', '--verbose', default=False, action="store_true", help='Makes ops-runner print more invormation.') parser.add_argument('-t', '--timeout', default=0, type=int, help='Value in seconds to wait for command to complete') parser.add_argument('rest', nargs=argparse.REMAINDER) group = parser.add_mutually_exclusive_group() group.add_argument('-f', '--flock', default=False, action="store_true", help='Flock the command so that only one can run at ' + \ 'a time (good for cron jobs).') group.add_argument('--flock-no-fail', default=False, action="store_true", help='Flock the command so that only one can run at ' + \ 'a time (good for cron jobs). But do not ' + \ 'return an error.') self.args = parser.parse_args() # Ensure name is safe to use regex = r"[^A-Za-z0-9_.]" self.args.name = re.sub(regex, "_", self.args.name) def attempt_to_lock_file(self): """ Attempts to lock the lock file, returns False if it couldn't """ try: lock_file = OPS_RUNNER_LOCK_FILE_PREFIX + self.args.name + ".lock" self.lock_file_handle = open(lock_file, 'w') fcntl.lockf(self.lock_file_handle, fcntl.LOCK_EX | fcntl.LOCK_NB) return True except IOError: return False def unlock_file(self): """ Unlocks the lock file """ fcntl.lockf(self.lock_file_handle, fcntl.LOCK_UN) def run_cmd_with_output(self, cmd, log=True): """ Runs a command and optionally logs it's output """ try: process = Popen(cmd, stdout=PIPE, stderr=STDOUT, universal_newlines=True) except OSError as e: self.verbose_print("Error while trying to run: {}".format(cmd)) self.verbose_print(e) # return non-zero exit return 1 while True: out = process.stdout.read(1) if out == '' and process.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush() if log: self.tmp_file_handle.write(out) self.tmp_file_handle.flush() return process.returncode if __name__ == "__main__": orunner = OpsRunner() orunner.run()
<reponame>mdda/libgpuarray import operator import numpy from pygpu import gpuarray, ndgpuarray as elemary from pygpu.elemwise import ElemwiseKernel from pygpu.tools import check_args, ArrayArg, ScalarArg from .support import (guard_devsup, rand, check_flags, check_meta, check_all, context, gen_gpuarray, dtypes_no_complex, check_meta_content) operators1 = [operator.neg, operator.pos, operator.abs] operators2 = [operator.add, operator.sub, operator.div, operator.floordiv, operator.mod, operator.mul, operator.truediv, operator.eq, operator.ne, operator.lt, operator.le, operator.gt, operator.ge] ioperators2 = [operator.iadd, operator.isub, operator.idiv, operator.ifloordiv, operator.imod, operator.imul, operator.itruediv] elems = [2, 0.3, numpy.asarray(3, dtype='int8'), numpy.asarray(7, dtype='uint32'), numpy.asarray(2.45, dtype='float32')] def test_elemwise1_ops_array(): for op in operators1: for dtype in dtypes_no_complex: yield elemwise1_ops_array, op, dtype @guard_devsup def elemwise1_ops_array(op, dtype): c, g = gen_gpuarray((50,), dtype, ctx=context, cls=elemary) out_c = op(c) out_g = op(g) assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) def test_elemwise2_ops_array(): for op in operators2: for dtype1 in dtypes_no_complex: for dtype2 in dtypes_no_complex: yield elemwise2_ops_array, op, dtype1, dtype2, (50,) def test_ielemwise2_ops_array(): for op in ioperators2: for dtype1 in dtypes_no_complex: for dtype2 in dtypes_no_complex: yield ielemwise2_ops_array, op, dtype1, dtype2, (50,) @guard_devsup def elemwise2_ops_array(op, dtype1, dtype2, shape): ac, ag = gen_gpuarray(shape, dtype1, ctx=context, cls=elemary) bc, bg = gen_gpuarray(shape, dtype2, nozeros=True, ctx=context, cls=elemary) out_c = op(ac, bc) out_g = op(ag, bg) assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) @guard_devsup def ielemwise2_ops_array(op, dtype1, dtype2, shape): incr = 0 if op == operator.isub and dtype1[0] == 'u': # array elements are smaller than 10 by default, so we avoid underflow incr = 10 ac, ag = gen_gpuarray(shape, dtype1, incr=incr, ctx=context, cls=elemary) bc, bg = gen_gpuarray(shape, dtype2, nozeros=True, ctx=context, cls=elemary) out_c = op(ac, bc) out_g = op(ag, bg) assert out_g is ag assert numpy.allclose(out_c, numpy.asarray(out_g)) def test_elemwise_layouts(): for shape in [(), (20, 30), (50, 8, 9)]: for offseted_outer in [True, False]: for offseted_inner in [True, False]: for sliced in [1, 2]: for order in ['c', 'f']: yield elemwise_layouts, shape, offseted_outer, \ offseted_inner, sliced, order yield elemwise_layouts_mixed, shape, offseted_outer, \ offseted_inner, sliced, order def test_elemwise_0(): elemwise_layouts((0,), False, False, 1, 'c') @guard_devsup def elemwise_layouts(shape, offseted_outer, offseted_inner, sliced, order): ac, ag = gen_gpuarray(shape, dtype='float32', sliced=sliced, order=order, offseted_outer=offseted_outer, offseted_inner=offseted_inner, ctx=context) bc, bg = gen_gpuarray(shape, dtype='float32', ctx=context) outg = gpuarray.empty(shape, dtype='float32', context=context) k = ElemwiseKernel(context, "float *a, float *b, float *c", "c[i] = a[i] + b[i]") # will use contig or basic k(ag, bg, outg) outc = ac + bc assert numpy.allclose(numpy.asarray(outg), outc) # test basic outg = gpuarray.empty(shape, dtype='float32', context=context) k.call_basic(ag, bg, outg) assert numpy.allclose(numpy.asarray(outg), outc) # test dimspec outg = gpuarray.empty(shape, dtype='float32', context=context) k.call_dimspec(ag, bg, outg) assert numpy.allclose(numpy.asarray(outg), outc) # test specialized outg = gpuarray.empty(shape, dtype='float32', context=context) k.call_specialized(ag, bg, outg) assert numpy.allclose(numpy.asarray(outg), outc) @guard_devsup def elemwise_layouts_mixed(shape, offseted_outer, offseted_inner, sliced, order): ac, ag = gen_gpuarray(shape, dtype='float32', sliced=sliced, order=order, offseted_outer=offseted_outer, offseted_inner=offseted_inner, ctx=context) b = numpy.asarray(2.0, dtype='float32') outg = gpuarray.empty(shape, dtype='float32', context=context) k = ElemwiseKernel(context, "float *a, float b, float *c", "c[i] = a[i] + b") # will use contig or basic k(ag, b, outg) outc = ac + b assert numpy.allclose(numpy.asarray(outg), outc) # test basic outg = gpuarray.empty(shape, dtype='float32', context=context) k.call_basic(ag, b, outg) assert numpy.allclose(numpy.asarray(outg), outc) # test dimspec outg = gpuarray.empty(shape, dtype='float32', context=context) k.call_dimspec(ag, b, outg) assert numpy.allclose(numpy.asarray(outg), outc) # test specialized outg = gpuarray.empty(shape, dtype='float32', context=context) k.call_specialized(ag, b, outg) assert numpy.allclose(numpy.asarray(outg), outc) def test_elemwise2_ops_mixed(): for op in operators2: for dtype in dtypes_no_complex: for elem in elems: yield elemwise2_ops_mixed, op, dtype, (50,), elem def test_ielemwise2_ops_mixed(): for op in ioperators2: for dtype in dtypes_no_complex: for elem in elems: yield ielemwise2_ops_mixed, op, dtype, (50,), elem @guard_devsup def elemwise2_ops_mixed(op, dtype, shape, elem): c, g = gen_gpuarray(shape, dtype, ctx=context, cls=elemary) out_c = op(c, elem) out_g = op(g, elem) assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) c, g = gen_gpuarray(shape, dtype, nozeros=True, ctx=context, cls=elemary) out_c = op(elem, c) out_g = op(elem, g) assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) @guard_devsup def ielemwise2_ops_mixed(op, dtype, shape, elem): incr = 0 if op == operator.isub and dtype[0] == 'u': # array elements are smaller than 10 by default, so we avoid underflow incr = 10 c, g = gen_gpuarray(shape, dtype, incr=incr, ctx=context, cls=elemary) out_c = op(c, elem) out_g = op(g, elem) assert out_g is g assert out_c.shape == out_g.shape assert out_c.dtype == out_g.dtype assert numpy.allclose(out_c, numpy.asarray(out_g)) def test_divmod(): for dtype1 in dtypes_no_complex: for dtype2 in dtypes_no_complex: yield divmod_array, dtype1, dtype2, (50,) for dtype in dtypes_no_complex: for elem in elems: yield divmod_mixed, dtype, (50,), elem @guard_devsup def divmod_array(dtype1, dtype2, shape): ac, ag = gen_gpuarray(shape, dtype1, ctx=context, cls=elemary) bc, bg = gen_gpuarray(shape, dtype2, nozeros=True, ctx=context, cls=elemary) out_c = divmod(ac, bc) out_g = divmod(ag, bg) assert out_c[0].shape == out_g[0].shape assert out_c[1].shape == out_g[1].shape assert out_c[0].dtype == out_g[0].dtype assert out_c[1].dtype == out_g[1].dtype assert numpy.allclose(out_c[0], numpy.asarray(out_g[0])) assert numpy.allclose(out_c[1], numpy.asarray(out_g[1])) @guard_devsup def divmod_mixed(dtype, shape, elem): c, g = gen_gpuarray(shape, dtype, nozeros=True, ctx=context, cls=elemary) out_c = divmod(c, elem) out_g = divmod(g, elem) assert out_c[0].shape == out_g[0].shape assert out_c[1].shape == out_g[1].shape assert out_c[0].dtype == out_g[0].dtype assert out_c[1].dtype == out_g[1].dtype assert numpy.allclose(out_c[0], numpy.asarray(out_g[0])) assert numpy.allclose(out_c[1], numpy.asarray(out_g[1])) out_c = divmod(elem, c) out_g = divmod(elem, g) assert out_c[0].shape == out_g[0].shape assert out_c[1].shape == out_g[1].shape assert out_c[0].dtype == out_g[0].dtype assert out_c[1].dtype == out_g[1].dtype assert numpy.allclose(out_c[0], numpy.asarray(out_g[0])) assert numpy.allclose(out_c[1], numpy.asarray(out_g[1])) def test_elemwise_bool(): a = gpuarray.empty((2,), context=context) exc = None try: bool(a) except ValueError, e: exc = e assert e is not None a = gpuarray.zeros((1,), context=context) assert bool(a) == False a = gpuarray.zeros((), context=context) assert bool(a) == False def test_broadcast(): for shapea, shapeb in [((3, 5), (3, 5)), ((1, 5), (3, 5)), ((3, 5), (3, 1)), ((1, 5), (3, 1)), ((3, 1), (3, 5)), ((3, 5), (3, 1)), ((1, 1), (1, 1)), ((3, 4, 5), (4, 5)), ((4, 5), (3, 4, 5)), ((), ())]: yield broadcast, shapea, shapeb def broadcast(shapea, shapeb): ac, ag = gen_gpuarray(shapea, 'float32', ctx=context, cls=elemary) bc, bg = gen_gpuarray(shapeb, 'float32', ctx=context, cls=elemary) rc = ac + bc rg = ag + bg check_meta_content(rg, rc) def test_elemwise_collapse(): for dtype1 in dtypes_no_complex: for dtype2 in dtypes_no_complex: for shape1, shape2, expected in [ # 1d to test this special case ((40,), (40,), 1), ((40,), (1,), 1), # No broadcastable dimensions ((4, 5, 6, 9), (4, 5, 6, 9), 1), # All inputs have one(and the same) broadcastable dimension ((1, 4, 5, 9), (1, 4, 5, 9), 1), ((4, 1, 5, 9), (4, 1, 5, 9), 1), ((4, 5, 1, 9), (4, 5, 1, 9), 1), ((4, 5, 9, 1), (4, 5, 9, 1), 1), # One inputs have one broadcastable dimension ((1, 5, 6, 9), (4, 5, 6, 9), 2), ((4, 1, 6, 9), (4, 5, 6, 9), 3), ((4, 5, 1, 9), (4, 5, 6, 9), 3), ((4, 5, 6, 1), (4, 5, 6, 9), 2), # One inputs have two broadcastable dimension ((1, 1, 6, 9), (4, 5, 6, 9), 2), ((1, 5, 1, 9), (4, 5, 6, 9), 4), ((1, 5, 6, 1), (4, 5, 6, 9), 3), ((4, 1, 1, 9), (4, 5, 6, 9), 3), ((4, 1, 6, 1), (4, 5, 6, 9), 4), ((4, 5, 1, 1), (4, 5, 6, 9), 2), # One inputs have tree broadcastable dimension ((1, 1, 1, 9), (4, 5, 6, 9), 2), ((1, 1, 6, 1), (4, 5, 6, 9), 3), ((1, 5, 1, 1), (4, 5, 6, 9), 3), ((4, 1, 1, 1), (4, 5, 6, 9), 2), # One scalar ((1, 1, 1, 1), (4, 5, 6, 9), 1), # One scalar, the other 1 broadcast dims ((1, 1, 1, 1), (4, 5, 6, 1), 1), ]: yield elemwise_collapse, dtype1, dtype2, shape1, shape2, \ expected def elemwise_collapse(dtype1, dtype2, shape1, shape2, expected): assert len(shape1) == len(shape2) # int8 does not cause problematic upcasts scalar = numpy.asarray(1, dtype='int8') a_cpu, a_gpu = gen_gpuarray(shape1, dtype1, ctx=context) b_cpu, b_gpu = gen_gpuarray(shape2, dtype2, ctx=context) o_shape = [] for i in range(len(shape1)): o_shape.append(max(shape1[i], shape2[i])) o = gpuarray.empty(o_shape, dtype=(a_cpu + b_cpu).dtype, context=context) n, nd, dims, strs, offsets, contig = check_args((a_gpu, b_gpu), collapse=True, broadcast=True) assert nd == expected, (shape1, shape2, dims, nd, expected) k = ElemwiseKernel(context, [ArrayArg(numpy.dtype(dtype1), 'a'), ArrayArg(numpy.dtype(dtype2), 'b'), ArrayArg(o.dtype, 'o')], "o[i] = a[i] + b[i]") out_cpu = a_cpu + b_cpu k(a_gpu, b_gpu, o, collapse=True, broadcast=True) assert numpy.allclose(numpy.asarray(o), out_cpu) k(a_gpu, b_gpu, o, collapse=False, broadcast=True) assert numpy.allclose(numpy.asarray(o), out_cpu) broadcast = any([True for i in shape1 + shape2 if i == 1]) n, nd, dims, strs, offsets, contig = check_args((a_gpu, b_gpu, scalar), collapse=True, broadcast=True) assert nd == expected k = ElemwiseKernel(context, [ArrayArg(numpy.dtype(dtype1), 'a'), ArrayArg(numpy.dtype(dtype2), 'b'), ScalarArg(scalar.dtype, 's'), ArrayArg(o.dtype, 'o')], "o[i] = a[i] + b[i] + s") out_cpu = a_cpu + b_cpu + scalar k(a_gpu, b_gpu, scalar, o, collapse=True, broadcast=True) assert numpy.allclose(numpy.asarray(o), out_cpu) k(a_gpu, b_gpu, scalar, o, collapse=False, broadcast=True) assert numpy.allclose(numpy.asarray(o), out_cpu) if expected == 1: expected2 = 2 else: expected2 = expected if len(shape1) != 4: return if shape1[0] != 1: c_cpu, c_gpu = gen_gpuarray(shape1, dtype=dtype1, sliced=2, ctx=context) n, nd, dims, strs, offsets,contig = check_args((c_gpu, b_gpu), collapse=True, broadcast=True) if broadcast: assert nd >= expected else: assert nd == expected2
#!/usr/bin/python from h264 import * import unittest def binData( s ): "convert 0/1/<space> string into byte buffer string" ret = "" mask = 1<<7 val = 0 for c in s: if c == ' ': continue if c == '1': val += mask mask /= 2 if mask == 0: ret += chr(val) val = 0 mask = 1<<7 if mask != 1<<7: ret += chr(val) return ret return "\xca" class H264Test( unittest.TestCase ): def testBit( self ): self.assertEqual( BitStream('\xFF').bit(), 1 ) def testGolomb( self ): self.assertEqual( BitStream('\xFF').golomb(), 0 ) self.assertEqual( BitStream('\x5F' ).golomb(), 1 ) self.assertEqual( BitStream('\x0F\x00' ).golomb(), 29 ) def testSignedGolomb( self ): self.assertEqual( BitStream('\xFF').signedGolomb(), 0 ) self.assertEqual( BitStream(binData('010')).signedGolomb(), 1 ) self.assertEqual( BitStream(binData('011')).signedGolomb(), -1 ) self.assertEqual( BitStream(binData('0001000')).signedGolomb(), 4 ) def testBitStream( self ): bs = BitStream( buf='\xBF' ) self.assertEqual( bs.bits( 2 ), 2 ) self.assertEqual( bs.bits( 3 ), 7 ) self.assertEqual( bs.golomb(), 0 ) self.assertEqual( bs.bit(), 1 ) def testAlignedByte( self ): bs = BitStream( buf="AHOJ" ) self.assertEqual( bs.alignedByte(), ord('A') ) bs.bit() self.assertEqual( bs.alignedByte(), ord('O') ) def testTab( self ): bs = BitStream( buf='\x50' ) table = { '01':"test01" } self.assertEqual( bs.tab( table ), "test01" ) self.assertEqual( bs.tab( table ), "test01" ) #self.assertEqual( bs.tab( table, maxBits=4 ), None ) # disabled, tired of removing sys.exit() def testBinStr( self ): tmp = VerboseWrapper( None ) self.assertEqual( len(tmp.binStr(2, 14)), 14 ) def testMix( self ): self.assertEqual( mix(None, None), 0 ) self.assertEqual( mix(13, None), 13 ) self.assertEqual( mix(None, 5), 5 ) self.assertEqual( mix(13, 5), 9 ) self.assertEqual( mix(1, 4), 3 ) # round-up def testBinData( self ): self.assertEqual( binData("11 0 0 101 0"), "\xCA" ) self.assertEqual( binData("111"), "\xE0" ) def testResidual( self ): bs = BitStream( buf=binData("01 " ) ) self.assertEqual( residual( bs, nC=-1 ), 0 ) self.assertEqual( bs.index, 2 ) bs = BitStream( buf=binData("11 " ) ) self.assertEqual( residual( bs, nC=3 ), 0 ) self.assertEqual( bs.index, 2 ) # failing "sector 51" bs = BitStream( buf=binData("00110 000 1 11 0010 011 11 11 11" ) ) self.assertEqual( residual( bs, nC=3 ), 5 ) self.assertEqual( bs.index, 1077959-1077935 ) # uncompleted table MB=115 (was bug in runBeforeMapping[6]) bs = BitStream( buf=binData("011 10 0100 101 1" ) ) self.assertEqual( residual( bs, nC=3 ), 2 ) self.assertEqual( bs.index, 1082430-1082418 ) # extra shift MB=2085 bs = BitStream( buf=binData("000000111 01 11 0010 111 1 0 " ) ) self.assertEqual( residual( bs, nC=1 ), 3 ) self.assertEqual( bs.index, 1191109-1191087 ) def testLevelTabs( self ): """ @1877578 Luma # c & tr.1s vlc=1 #c=7 #t1=3 000100 ( 4) @1877584 Luma trailing ones sign (2,0) 001 ( 1) @1877587 Luma lev (2,0) k=3 vlc=0 01 ( 1) @1877589 Luma lev (2,0) k=2 vlc=1 0010 ( 2) @1877593 Luma lev (2,0) k=1 vlc=1 00010 ( 2) @1877598 Luma lev (2,0) k=0 vlc=2 0110 ( 6) @1877602 Luma totalrun (2,0) vlc=6 011 ( 3) @1877605 Luma run (6,0) k=6 vlc=3 11 ( 3) @1877607 Luma run (5,0) k=5 vlc=3 10 ( 2) @1877609 Luma run (4,0) k=4 vlc=2 01 ( 1) @1877611 Luma run (3,0) k=3 vlc=0 1 ( 1) @1877612 Luma run (2,0) k=2 vlc=0 1 ( 1) @1877613 Luma run (1,0) k=1 vlc=0 0 ( 0) """ bs = VerboseWrapper( BitStream( buf=binData("000100 001 01 0010 00010 0110 011 11 10 01 1 1 0" ) ), 1877578 ) self.assertEqual( residual( bs, nC=2 ), 7 ) self.assertEqual( bs.worker.index, 1877614-1877578 ) def testLevelTabs2( self ): """ frame0091.bin MB: 3582 @1557490 Luma # c & tr.1s vlc=0 #c=6 #t1=3 00000100 ( 4) @1557498 Luma trailing ones sign (2,3) 100 ( 4) @1557501 Luma lev (2,3) k=2 vlc=0 000001 ( 1) @1557507 Luma lev (2,3) k=1 vlc=1 11 ( 3) @1557509 Luma lev (2,3) k=0 vlc=1 010 ( 2) @1557512 Luma totalrun (2,3) vlc=5 101 ( 5) @1557515 Luma run (5,3) k=5 vlc=3 000 ( 0) """ bs = VerboseWrapper( BitStream( buf=binData("00000100 100 000001 11 010 101 000" ) ), 1557490 ) self.assertEqual( residual( bs, nC=1 ), 6 ) self.assertEqual( bs.worker.index, 1557518-1557490 ) """ @1557518 Luma # c & tr.1s vlc=1 #c=3 #t1=0 0000111 ( 7) @1557525 Luma lev (3,3) k=2 vlc=0 000001 ( 1) @1557531 Luma lev (3,3) k=1 vlc=2 100 ( 4) @1557534 Luma lev (3,3) k=0 vlc=2 0100 ( 4) @1557538 Luma totalrun (3,3) vlc=2 0101 ( 5) """ bs = VerboseWrapper( BitStream( buf=binData("0000111 000001 100 0100 0101" ) ), 1557518 ) self.assertEqual( residual( bs, nC=3 ), 3 ) self.assertEqual( bs.worker.index, 1557542-1557518 ) def testLevelTabs3( self ): """ frame0183.bin MB: 40 @972253 Luma # c & tr.1s vlc=2 #c=6 #t1=1 001110 ( 14) @972259 Luma trailing ones sign (3,0) 1 ( 1) @972260 Luma lev (3,0) k=4 vlc=0 01 ( 1) @972262 Luma lev (3,0) k=3 vlc=1 010 ( 2) @972265 Luma lev (3,0) k=2 vlc=1 00010 ( 2) @972270 Luma lev (3,0) k=1 vlc=2 0100 ( 4) @972274 Luma lev (3,0) k=0 vlc=2 000110 ( 6) @972280 Luma totalrun (3,0) vlc=5 111 ( 7) @972283 Luma run (5,0) k=5 vlc=1 01 ( 1) @972285 Luma run (4,0) k=4 vlc=0 1 ( 1) @972286 Luma run (3,0) k=3 vlc=0 0 ( 0) """ bs = BitStream( buf=binData("001110 1 01 010 00010 0100 000110 111 01 1 0" ) ) self.assertEqual( residual( bs, nC=4 ), 6 ) self.assertEqual( bs.index, 972287-972253 ) def testLevelTabs4( self ): """ frame0187.bin MB: 24 @1365333 Luma # c & tr.1s vlc=1 #c=1 #t1=0 001011 ( 11) @1365339 Luma lev (0,0) k=0 vlc=0 0000000000000010001 ( 17) @1365358 Luma totalrun (0,0) vlc=0 1 ( 1) """ bs = BitStream( buf=binData("001011 0000000000000010001 1" ) ) self.assertEqual( residual( bs, nC=2 ), 1 ) self.assertEqual( bs.index, 1365359-1365333 ) def testLevelTabs5( self ): """ frame0228.bin MB: 30 @2742801 Luma # c & tr.1s vlc=2 #c=6 #t1=3 1001 ( 9) @2742805 Luma trailing ones sign (3,0) 111 ( 7) @2742808 Luma lev (3,0) k=2 vlc=0 0000000000000010010 ( 18) @2742827 Luma lev (3,0) k=1 vlc=2 110 ( 6) @2742830 Luma lev (3,0) k=0 vlc=2 0000100 ( 4) @2742837 Luma totalrun (3,0) vlc=5 110 ( 6) @2742840 Luma run (5,0) k=5 vlc=2 11 ( 3) @2742842 Luma run (4,0) k=4 vlc=2 10 ( 2) @2742844 Luma run (3,0) k=3 vlc=1 00 ( 0) """ bs = BitStream( buf=binData("1001 111 0000000000000010010 110 0000100 110 11 10 00" ) ) self.assertEqual( residual( bs, nC=7 ), 6 ) self.assertEqual( bs.index, 2742846-2742801 ) def testLevelTabs15( self ): """ frame0305.bin MB: 71 @2007284 Luma # c & tr.1s vlc=2 #c=5 #t1=3 1010 ( 10) @2007288 Luma trailing ones sign (3,0) 011 ( 3) @2007291 Luma lev (3,0) k=1 vlc=0 1 ( 1) @2007292 Luma lev (3,0) k=0 vlc=1 0000000000000001000000000001 (4097) @2007320 Luma totalrun (3,0) vlc=4 0100 ( 4) @2007324 Luma run (4,0) k=4 vlc=0 1 ( 1) @2007325 Luma run (3,0) k=3 vlc=0 0 ( 0)""" bs = BitStream( buf=binData("1010 011 1 0000000000000001000000000001 0100 1 0" ) ) self.assertEqual( residual( bs, nC=4 ), 5 ) self.assertEqual( bs.index, 2007326-2007284 ) def testMedian( self ): self.assertEqual( median( None, None, None), 0 ) self.assertEqual( median( 3, None, None), 3 ) self.assertEqual( median( 3, 13, 5), 5 ) self.assertEqual( median( -3, 11, None), 0 ) self.assertEqual( median( None, 4, None), 4 ) # frame=113, x=0, y=16 self.assertEqual( median( None, None, 13), 13 ) # not detected yet self.assertEqual( median( None, 0, 0), 0 ) # bug self.assertEqual( median( None, 14, 16), 14 ) def testLum16DC( self ): """ *********** POC: 2 (I/P) MB: 48 Slice: 0 Type 0 ********** @1184157 mb_skip_run 1 ( 0) @1184158 mb_type 0001000 ( 7) @1184165 intra_chroma_pred_mode 010 ( 1) @1184168 mb_qp_delta 1 ( 0) @1184169 Lum16DC # c & tr.1s vlc=0 #c=4 #t1=3 000011 ( 3) @1184175 Lum16DC trailing ones sign (0,0) 111 ( 7) @1184178 Lum16DC lev (0,0) k=0 vlc=0 01 ( 1) @1184180 Lum16DC totalrun (0,0) vlc=3 100 ( 4) @1184183 Lum16DC run (3,0) k=3 vlc=5 11 ( 3) @1184185 Lum16DC run (2,0) k=2 vlc=5 000 ( 0) @1184188 Lum16DC run (1,0) k=1 vlc=4 011 ( 3) """ bs = VerboseWrapper( BitStream( buf=binData("0001000 010 1 000011 111 01 100 11 000 011" ) ), startOffset=1184158 ) # without skip left = [[None]*4, [None]*2, [None]*2] up = [[None]*4, [None]*2, [None]*2] print "testLum16DC START" macroblockLayer( bs, left, up ) print "testLum16DC END" self.assertEqual( bs.worker.index, 1184191-1184158 ) """ *********** POC: 2 (I/P) MB: 206 Slice: 0 Type 0 ********** @1198123 mb_skip_run 1 ( 0) @1198124 mb_type 00111 ( 6) @1198129 intra_chroma_pred_mode 011 ( 2) @1198132 mb_qp_delta 00101 ( -2) @1198137 Lum16DC # c & tr.1s vlc=0 #c=5 #t1=3 0000100 ( 4) @1198144 Lum16DC trailing ones sign (0,0) 011 ( 3) @1198147 Lum16DC lev (0,0) k=1 vlc=0 1 ( 1) @1198148 Lum16DC lev (0,0) k=0 vlc=1 11 ( 3) @1198150 Lum16DC totalrun (0,0) vlc=4 0100 ( 4) @1198154 Lum16DC run (4,0) k=4 vlc=0 1 ( 1) @1198155 Lum16DC run (3,0) k=3 vlc=0 1 ( 1) @1198156 Lum16DC run (2,0) k=2 vlc=0 1 ( 1) @1198157 Lum16DC run (1,0) k=1 vlc=0 0 ( 0) """ bs = VerboseWrapper( BitStream( buf=binData("00111 011 00101 0000100 011 1 11 0100 1 1 1 0" ) ), startOffset=1198124 ) # without skip left = [[None]*4, [None]*2, [None]*2] up = [[None]*4, [None]*2, [None]*2] print "testLum16DC START" macroblockLayer( bs, left, up ) print "testLum16DC END" self.assertEqual( bs.worker.index, 1198158-1198124 ) """ *********** POC: 2 (I/P) MB: 368 Slice: 0 Type 0 ********** @1211250 mb_skip_run 1 ( 0) @1211251 mb_type 000010101 ( 20) @1211260 intra_chroma_pred_mode 011 ( 2) @1211263 mb_qp_delta 00101 ( -2) @1211268 Lum16DC # c & tr.1s vlc=0 #c=4 #t1=3 000011 ( 3) @1211274 Lum16DC trailing ones sign (0,0) 100 ( 4) @1211277 Lum16DC lev (0,0) k=0 vlc=0 01 ( 1) @1211279 Lum16DC totalrun (0,0) vlc=3 110 ( 6) @1211282 Lum16DC run (3,0) k=3 vlc=3 10 ( 2) @1211284 Lum16DC run (2,0) k=2 vlc=2 11 ( 3) @1211286 Lum16DC run (1,0) k=1 vlc=2 10 ( 2) @1211288 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211289 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211290 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211291 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211292 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211293 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211294 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211295 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211296 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211297 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211298 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211299 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211300 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211301 Lum16AC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @1211303 Lum16AC trailing ones sign (3,2) 1 ( 1) @1211304 Lum16AC totalrun (3,2) vlc=0 1 ( 1) @1211305 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1211306 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1)""" print "Lum16AC START" bs = VerboseWrapper( BitStream( buf=binData("000010101 011 00101 000011 100 01 110 10 11 10 1 1 1 1 1 1 1 1 1 1 1 1 1 01 1 1 1 1" ) ), startOffset=1211251 ) # without skip left = [[None]*4, [None]*2, [None]*2] up = [[None]*4, [None]*2, [None]*2] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 1211307-1211251 ) print "Lum16AC END" """ *********** POC: 2 (I/P) MB: 1250 Slice: 0 Type 0 ********** @1283940 mb_skip_run 1 ( 0) @1283941 mb_type 000011010 ( 25) @1283950 intra_chroma_pred_mode 1 ( 0) @1283951 mb_qp_delta 1 ( 0) @1283952 Lum16DC # c & tr.1s vlc=0 #c=5 #t1=3 0000100 ( 4) @1283959 Lum16DC trailing ones sign (0,0) 101 ( 5) @1283962 Lum16DC lev (0,0) k=1 vlc=0 1 ( 1) @1283963 Lum16DC lev (0,0) k=0 vlc=1 11 ( 3) @1283965 Lum16DC totalrun (0,0) vlc=4 110 ( 6) @1283968 Lum16DC run (4,0) k=4 vlc=3 01 ( 1) @1283970 Lum16DC run (3,0) k=3 vlc=1 1 ( 1) @1283971 Lum16DC run (2,0) k=2 vlc=1 00 ( 0) @1283973 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283974 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283975 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283976 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283977 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283978 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283979 Lum16AC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @1283981 Lum16AC trailing ones sign (2,1) 0 ( 0) @1283982 Lum16AC totalrun (2,1) vlc=0 011 ( 3) @1283985 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283986 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283987 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283988 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283989 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283990 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283991 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283992 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283993 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1283994 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) @1283996 ChrDC # c & tr.1s #c=1 #t1=1 1 ( 1) @1283997 ChrDC trailing ones sign (0,0) 0 ( 0) @1283998 ChrDC totalrun (0,0) vlc=0 001 ( 1) """ print "Lum16ACDC START" bs = VerboseWrapper( BitStream( buf=binData("000011010 1 1 0000100 101 1 11 110 01 1 00 1 1 1 1 1 1 01 0 011 1 1 1 1 1 1 1 1 1 01 1 0 001" ) ), startOffset=1283941 ) # without skip left = [[None]*4, [None]*2, [None]*2] up = [[None]*4, [None]*2, [None]*2] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 1284001-1283941 ) print "Lum16ACDC END" def testLum16DCWithLeftUp( self ): """ *********** POC: 2 (I/P) MB: 1292 Slice: 0 Type 0 ********** @1285939 mb_skip_run 1 ( 0) @1285940 mb_type 000010011 ( 18) @1285949 intra_chroma_pred_mode 011 ( 2) @1285952 mb_qp_delta 00100 ( 2) @1285957 Lum16DC # c & tr.1s vlc=0 #c=8 #t1=1 0000000001010 ( 10) @1285970 Lum16DC trailing ones sign (0,0) 0 ( 0) @1285971 Lum16DC lev (0,0) k=6 vlc=0 01 ( 1) @1285973 Lum16DC lev (0,0) k=5 vlc=1 11 ( 3) @1285975 Lum16DC lev (0,0) k=4 vlc=1 10 ( 2) @1285977 Lum16DC lev (0,0) k=3 vlc=1 11 ( 3) @1285979 Lum16DC lev (0,0) k=2 vlc=1 10 ( 2) @1285981 Lum16DC lev (0,0) k=1 vlc=1 11 ( 3) @1285983 Lum16DC lev (0,0) k=0 vlc=1 011 ( 3) @1285986 Lum16DC totalrun (0,0) vlc=7 10 ( 2) @1285988 Lum16DC run (7,0) k=7 vlc=4 000 ( 0) @1285991 Lum16AC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @1285993 Lum16AC trailing ones sign (0,0) 1 ( 1) @1285994 Lum16AC totalrun (0,0) vlc=0 1 ( 1) @1285995 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1285996 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1285997 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1285998 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1285999 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1286000 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1286001 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1286002 Lum16AC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @1286004 Lum16AC trailing ones sign (0,2) 0 ( 0) @1286005 Lum16AC totalrun (0,2) vlc=0 011 ( 3) @1286008 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1286009 Lum16AC # c & tr.1s vlc=1 #c=2 #t1=2 011 ( 3) @1286012 Lum16AC trailing ones sign (0,3) 10 ( 2) @1286014 Lum16AC totalrun (0,3) vlc=1 100 ( 4) @1286017 Lum16AC run (1,3) k=1 vlc=2 11 ( 3) @1286019 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1286020 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1286021 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1286022 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @1286023 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) """ # NOTE - When parsing for Intra16x16DCLevel, the values nA and nB are based on the number of non-zero # transform coefficient levels in adjacent 4x4 blocks and not on the number of non-zero DC transform coefficient # levels in adjacent 16x16 blocks. # ... that's probably it (???). Sum? print "Lum16AC-2 START" bs = VerboseWrapper( BitStream( buf=binData("000010011 011 00100 0000000001010 1 01 11 10 11 10 11 011 10 000 01 1 1 1 1 1 1 1 1 1\ 01 0 011 1 011 10 100 11 1 1 1 1 1" ) ), startOffset=1285940 ) # without skip left = [[0, 0, 0, 3], [0, 0], [0, 0]] up = [[0, 0, 0, 0], [0, 0], [0, 0]] # maybe it is not correct?? # mb_type 18 = I_16x16_1_1_1 Intra_16x16 1 1 15 macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 1286024-1285940 ) print "Lum16AC-2 END" def testBlockType22( self ): # no idea why it required ChrDC at the end """ *********** POC: 56 (I/P) MB: 1201 Slice: 0 Type 0 ********** @4601750 mb_skip_run 1 ( 0) @4601751 mb_type 000010111 ( 22) @4601760 intra_chroma_pred_mode 011 ( 2) @4601763 mb_qp_delta 000010110 ( 11) @4601772 Lum16DC # c & tr.1s vlc=1 #c=4 #t1=3 0100 ( 4) @4601776 Lum16DC trailing ones sign (0,0) 001 ( 1) @4601779 Lum16DC lev (0,0) k=0 vlc=0 1 ( 1) @4601780 Lum16DC totalrun (0,0) vlc=3 0010 ( 2) @4601784 Lum16DC run (3,0) k=3 vlc=6 011 ( 3) @4601787 Lum16DC run (2,0) k=2 vlc=4 10 ( 2) @4601789 Lum16DC run (1,0) k=1 vlc=3 11 ( 3) @4601791 Lum16AC # c & tr.1s vlc=1 #c=1 #t1=1 10 ( 2) @4601793 Lum16AC trailing ones sign (0,0) 1 ( 1) @4601794 Lum16AC totalrun (0,0) vlc=0 00011 ( 3) @4601799 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601800 Lum16AC # c & tr.1s vlc=0 #c=2 #t1=2 001 ( 1) @4601803 Lum16AC trailing ones sign (0,1) 10 ( 2) @4601805 Lum16AC totalrun (0,1) vlc=1 0101 ( 5) @4601809 Lum16AC run (1,1) k=1 vlc=4 001 ( 1) @4601812 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601813 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601814 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601815 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601816 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601817 Lum16AC # c & tr.1s vlc=0 #c=3 #t1=3 00011 ( 3) @4601822 Lum16AC trailing ones sign (0,2) 100 ( 4) @4601825 Lum16AC totalrun (0,2) vlc=2 101 ( 5) @4601828 Lum16AC run (2,2) k=2 vlc=2 11 ( 3) @4601830 Lum16AC run (1,2) k=1 vlc=2 00 ( 0) @4601832 Lum16AC # c & tr.1s vlc=1 #c=0 #t1=0 11 ( 3) @4601834 Lum16AC # c & tr.1s vlc=1 #c=0 #t1=0 11 ( 3) @4601836 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601837 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601838 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601839 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601840 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @4601841 ChrDC # c & tr.1s #c=1 #t1=1 1 ( 1) @4601842 ChrDC trailing ones sign (0,0) 1 ( 1) @4601843 ChrDC totalrun (0,0) vlc=0 1 ( 1) @4601844 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) """ bs = VerboseWrapper( BitStream( buf=binData("000010111 011 000010110 0100 001 1 0010 011 10 11 10 1 00011 1 001 10 0101 001\ 1 1 1 1 1 00011 100 101 11 00 11 11 1 1 1 1 1 1 1 1 01" ) ), startOffset=4601751 ) # without skip left = [[0, 0, 0, 0], [0, 0], [0, 0]] up = [[3, 0, 0, 0], [0, 0], [0, 0]] # maybe it is not correct?? # mb_type 18 = I_16x16_1_1_1 Intra_16x16 1 1 15 macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 4601846-4601751 ) def testMbType26( self ): # frame0137.bin """ *********** POC: 44 (I/P) MB: 959 Slice: 0 Type 0 ********** @2429880 mb_skip_run 1 ( 0) @2429881 mb_type 000011011 ( 26) @2429890 intra_chroma_pred_mode 1 ( 0) @2429891 mb_qp_delta 00110 ( 3) @2429896 Lum16DC # c & tr.1s vlc=0 #c=9 #t1=2 0000000001001 ( 9) @2429909 Lum16DC trailing ones sign (0,0) 01 ( 1) @2429911 Lum16DC lev (0,0) k=6 vlc=0 1 ( 1) @2429912 Lum16DC lev (0,0) k=5 vlc=1 011 ( 3) @2429915 Lum16DC lev (0,0) k=4 vlc=1 11 ( 3) @2429917 Lum16DC lev (0,0) k=3 vlc=1 10 ( 2) @2429919 Lum16DC lev (0,0) k=2 vlc=1 010 ( 2) @2429922 Lum16DC lev (0,0) k=1 vlc=1 011 ( 3) @2429925 Lum16DC lev (0,0) k=0 vlc=1 11 ( 3) @2429927 Lum16DC totalrun (0,0) vlc=8 00001 ( 1) @2429932 Lum16DC run (8,0) k=8 vlc=6 111 ( 7) @2429935 Lum16DC run (7,0) k=7 vlc=6 110 ( 6) @2429938 Lum16DC run (6,0) k=6 vlc=5 010 ( 2) @2429941 Lum16DC run (5,0) k=5 vlc=1 1 ( 1) @2429942 Lum16DC run (4,0) k=4 vlc=1 1 ( 1) @2429943 Lum16DC run (3,0) k=3 vlc=1 1 ( 1) @2429944 Lum16DC run (2,0) k=2 vlc=1 01 ( 1) @2429946 Lum16DC run (1,0) k=1 vlc=0 0 ( 0) @2429947 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429948 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429949 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429950 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429951 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429952 Lum16AC # c & tr.1s vlc=0 #c=3 #t1=3 00011 ( 3) @2429957 Lum16AC trailing ones sign (3,0) 001 ( 1) @2429960 Lum16AC totalrun (3,0) vlc=2 101 ( 5) @2429963 Lum16AC run (2,0) k=2 vlc=2 11 ( 3) @2429965 Lum16AC run (1,0) k=1 vlc=2 00 ( 0) @2429967 Lum16AC # c & tr.1s vlc=0 #c=1 #t1=0 000101 ( 5) @2429973 Lum16AC lev (2,1) k=0 vlc=0 1 ( 1) @2429974 Lum16AC totalrun (2,1) vlc=0 1 ( 1) @2429975 Lum16AC # c & tr.1s vlc=1 #c=2 #t1=2 011 ( 3) @2429978 Lum16AC trailing ones sign (3,1) 11 ( 3) @2429980 Lum16AC totalrun (3,1) vlc=1 111 ( 7) @2429983 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429984 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429985 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429986 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429987 Lum16AC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2429988 Lum16AC # c & tr.1s vlc=0 #c=2 #t1=2 001 ( 1) @2429991 Lum16AC trailing ones sign (3,2) 11 ( 3) @2429993 Lum16AC totalrun (3,2) vlc=1 111 ( 7) @2429996 Lum16AC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @2429998 Lum16AC trailing ones sign (2,3) 0 ( 0) @2429999 Lum16AC totalrun (2,3) vlc=0 1 ( 1) @2430000 Lum16AC # c & tr.1s vlc=1 #c=3 #t1=2 001001 ( 9) @2430006 Lum16AC trailing ones sign (3,3) 00 ( 0) @2430008 Lum16AC lev (3,3) k=0 vlc=0 01 ( 1) @2430010 Lum16AC totalrun (3,3) vlc=2 111 ( 7) @2430013 Lum16AC run (2,3) k=2 vlc=0 1 ( 1) @2430014 Lum16AC run (1,3) k=1 vlc=0 0 ( 0) @2430015 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) @2430017 ChrDC # c & tr.1s #c=2 #t1=2 001 ( 1) @2430020 ChrDC trailing ones sign (0,0) 10 ( 2) @2430022 ChrDC totalrun (0,0) vlc=1 1 ( 1) @2430023 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2430024 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2430025 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2430026 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2430027 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2430028 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2430029 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @2430030 ChrAC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @2430032 ChrAC trailing ones sign (3,5) 1 ( 1) @2430033 ChrAC totalrun (3,5) vlc=0 1 ( 1) *********** POC: 44 (I/P) MB: 960 Slice: 0 Type 0 ********** @2430034 mb_skip_run """ bs = VerboseWrapper( BitStream( buf=binData("000011011 1 00110 0000000001001 01 1 011 11 10 010 011 11 00001 111 110 010 1 1 1 01 0 1 1 1 1 1\ 00011 001 101 11 00 000101 1 1 011 11 111 1 1 1 1 1 001 11 111 01 0 1 001001 00 01 111 1 0 01 001 10 1 1 1 1 1 1 1 1 01 1 1" ) ), startOffset=2429881 ) # without skip left = [[0, 0, 0, 0], [0, 0], [0, 0]] up = [[0, 0, 0, 0], [0, 0], [0, 0]] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 2430034-2429881 ) def testMbType12( self ): # frame0141.bin """ *********** POC: 52 (I/P) MB: 2950 Slice: 0 Type 0 ********** @2871689 mb_skip_run 1 ( 0) @2871690 mb_type 0001101 ( 12) @2871697 intra_chroma_pred_mode 1 ( 0) @2871698 mb_qp_delta 00111 ( -3) @2871703 Lum16DC # c & tr.1s vlc=0 #c=7 #t1=3 000000100 ( 4) @2871712 Lum16DC trailing ones sign (0,0) 101 ( 5) @2871715 Lum16DC lev (0,0) k=3 vlc=0 1 ( 1) @2871716 Lum16DC lev (0,0) k=2 vlc=1 11 ( 3) @2871718 Lum16DC lev (0,0) k=1 vlc=1 10 ( 2) @2871720 Lum16DC lev (0,0) k=0 vlc=1 010 ( 2) @2871723 Lum16DC totalrun (0,0) vlc=6 100 ( 4) @2871726 Lum16DC run (6,0) k=6 vlc=2 11 ( 3) @2871728 Lum16DC run (5,0) k=5 vlc=2 11 ( 3) @2871730 Lum16DC run (4,0) k=4 vlc=2 01 ( 1) @2871732 Lum16DC run (3,0) k=3 vlc=0 0 ( 0) @2871733 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) @2871735 ChrDC # c & tr.1s #c=1 #t1=1 1 ( 1) @2871736 ChrDC trailing ones sign (0,0) 1 ( 1) @2871737 ChrDC totalrun (0,0) vlc=0 1 ( 1) """ bs = VerboseWrapper( BitStream( buf=binData("0001101 1 00111 000000100 101 1 11 10 010 100 11 11 01 0 01 1 1 1 " ) ), startOffset=2871689 ) # without skip left = [[0, 0, 0, 0], [0, 0], [0, 0]] up = [[0, 0, 0, 0], [0, 0], [0, 0]] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 2871738- 2871690 ) def testMbType10( self ): # frame0147.bin """ *********** POC: 4 (I/P) MB: 3426 Slice: 0 Type 0 ********** @606828 mb_skip_run 1 ( 0) @606829 mb_type 0001011 ( 10) @606836 intra_chroma_pred_mode 011 ( 2) @606839 mb_qp_delta 1 ( 0) @606840 Lum16DC # c & tr.1s vlc=0 #c=5 #t1=3 0000100 ( 4) @606847 Lum16DC trailing ones sign (0,0) 001 ( 1) @606850 Lum16DC lev (0,0) k=1 vlc=0 01 ( 1) @606852 Lum16DC lev (0,0) k=0 vlc=1 11 ( 3) @606854 Lum16DC totalrun (0,0) vlc=4 0010 ( 2) @606858 Lum16DC run (4,0) k=4 vlc=6 0001 ( 1) @606862 Lum16DC run (3,0) k=3 vlc=0 1 ( 1) @606863 Lum16DC run (2,0) k=2 vlc=0 1 ( 1) @606864 Lum16DC run (1,0) k=1 vlc=0 1 ( 1) @606865 ChrDC # c & tr.1s #c=1 #t1=1 1 ( 1) @606866 ChrDC trailing ones sign (0,0) 1 ( 1) @606867 ChrDC totalrun (0,0) vlc=0 1 ( 1) @606868 ChrDC # c & tr.1s #c=1 #t1=1 1 ( 1) @606869 ChrDC trailing ones sign (0,0) 0 ( 0) @606870 ChrDC totalrun (0,0) vlc=0 1 ( 1) """ bs = VerboseWrapper( BitStream( buf=binData("0001011 011 1 0000100 001 01 11 0010 0001 1 1 1 1 1 1 1 0 1 " ) ), startOffset=2871689 ) # without skip left = [[0, 0, 0, 0], [0, 0], [0, 0]] up = [[0, 0, 0, 0], [0, 0], [0, 0]] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 606871-606829 ) def testMbType14( self ): # frame0148.bin """ *********** POC: 6 (I/P) MB: 2613 Slice: 0 Type 0 ********** @707572 mb_skip_run 1 ( 0) @707573 mb_type 0001111 ( 14) @707580 intra_chroma_pred_mode 010 ( 1) @707583 mb_qp_delta 00100 ( 2) @707588 Lum16DC # c & tr.1s vlc=0 #c=8 #t1=3 0000000100 ( 4) @707598 Lum16DC trailing ones sign (0,0) 001 ( 1) @707601 Lum16DC lev (0,0) k=4 vlc=0 1 ( 1) @707602 Lum16DC lev (0,0) k=3 vlc=1 10 ( 2) @707604 Lum16DC lev (0,0) k=2 vlc=1 10 ( 2) @707606 Lum16DC lev (0,0) k=1 vlc=1 10 ( 2) @707608 Lum16DC lev (0,0) k=0 vlc=1 011 ( 3) @707611 Lum16DC totalrun (0,0) vlc=7 10 ( 2) @707613 Lum16DC run (7,0) k=7 vlc=4 011 ( 3) @707616 Lum16DC run (6,0) k=6 vlc=2 10 ( 2) @707618 Lum16DC run (5,0) k=5 vlc=1 01 ( 1) @707620 Lum16DC run (4,0) k=4 vlc=0 1 ( 1) @707621 Lum16DC run (3,0) k=3 vlc=0 0 ( 0) @707622 ChrDC # c & tr.1s #c=1 #t1=1 1 ( 1) @707623 ChrDC trailing ones sign (0,0) 0 ( 0) @707624 ChrDC totalrun (0,0) vlc=0 01 ( 1) @707626 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) @707628 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @707629 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @707630 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @707631 ChrAC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @707633 ChrAC trailing ones sign (1,5) 0 ( 0) @707634 ChrAC totalrun (1,5) vlc=0 1 ( 1) @707635 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @707636 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @707637 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @707638 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) """ bs = VerboseWrapper( BitStream( buf=binData("0001111 010 00100 0000000100 001 1 10 10 10 011 10 011 10 01 1 0 1 0 01 01 1 1 1 01 0 1 1 1 1 1 " ) ), startOffset=2871689 ) # without skip left = [[0, 0, 0, 0], [0, 0], [0, 0]] up = [[0, 0, 0, 0], [0, 0], [0, 0]] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 707639-707573 ) def testMbType16( self ): # frame0149.bin """ *********** POC: 8 (I/P) MB: 2896 Slice: 0 Type 0 ********** @873939 mb_skip_run 1 ( 0) @873940 mb_type 000010001 ( 16) @873949 intra_chroma_pred_mode 00100 ( 3) @873954 mb_qp_delta 011 ( -1) @873957 Lum16DC # c & tr.1s vlc=0 #c=3 #t1=3 00011 ( 3) @873962 Lum16DC trailing ones sign (0,0) 110 ( 6) @873965 Lum16DC totalrun (0,0) vlc=2 101 ( 5) @873968 Lum16DC run (2,0) k=2 vlc=2 00 ( 0) @873970 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) @873972 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) @873974 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @873975 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @873976 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @873977 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @873978 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @873979 ChrAC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @873981 ChrAC trailing ones sign (3,4) 0 ( 0) @873982 ChrAC totalrun (3,4) vlc=0 011 ( 3) @873985 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @873986 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) """ bs = VerboseWrapper( BitStream( buf=binData("000010001 00100 011 00011 110 101 00 01 01 1 1 1 1 1 01 0 011 1 1 " ) ), startOffset=2871689 ) # without skip left = [[0, 0, 0, 0], [0, 0], [0, 0]] up = [[0, 0, 0, 0], [0, 0], [0, 0]] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 873987-873940 ) def testMbType17( self ): # frame0150.bin """ *********** POC: 10 (I/P) MB: 2704 Slice: 0 Type 0 ********** @980878 mb_skip_run 1 ( 0) @980879 mb_type 000010010 ( 17) @980888 intra_chroma_pred_mode 1 ( 0) @980889 mb_qp_delta 00110 ( 3) @980894 Lum16DC # c & tr.1s vlc=0 #c=5 #t1=3 0000100 ( 4) @980901 Lum16DC trailing ones sign (0,0) 001 ( 1) @980904 Lum16DC lev (0,0) k=1 vlc=0 1 ( 1) @980905 Lum16DC lev (0,0) k=0 vlc=1 11 ( 3) @980907 Lum16DC totalrun (0,0) vlc=4 111 ( 7) @980910 Lum16DC run (4,0) k=4 vlc=2 10 ( 2) @980912 Lum16DC run (3,0) k=3 vlc=1 01 ( 1) @980914 Lum16DC run (2,0) k=2 vlc=0 0 ( 0) @980915 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) @980917 ChrDC # c & tr.1s #c=1 #t1=1 1 ( 1) @980918 ChrDC trailing ones sign (0,0) 0 ( 0) @980919 ChrDC totalrun (0,0) vlc=0 1 ( 1) @980920 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @980921 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @980922 ChrAC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @980924 ChrAC trailing ones sign (0,5) 1 ( 1) @980925 ChrAC totalrun (0,5) vlc=0 1 ( 1) @980926 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @980927 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @980928 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @980929 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @980930 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) """ bs = VerboseWrapper( BitStream( buf=binData("000010010 1 00110 0000100 001 1 11 111 10 01 0 01 1 0 1 1 1 01 1 1 1 1 1 1 1 " ) ), startOffset=2871689 ) # without skip left = [[0, 0, 0, 0], [0, 0], [0, 0]] up = [[0, 0, 0, 0], [0, 0], [0, 0]] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 980931-980879 ) def testMbType15( self ): # frame0150.bin """ *********** POC: 10 (I/P) MB: 2871 Slice: 0 Type 0 ********** @989455 mb_skip_run 1 ( 0) @989456 mb_type 000010000 ( 15) @989465 intra_chroma_pred_mode 010 ( 1) @989468 mb_qp_delta 1 ( 0) @989469 Lum16DC # c & tr.1s vlc=0 #c=4 #t1=3 000011 ( 3) @989475 Lum16DC trailing ones sign (0,0) 111 ( 7) @989478 Lum16DC lev (0,0) k=0 vlc=0 001 ( 1) @989481 Lum16DC totalrun (0,0) vlc=3 0010 ( 2) @989485 Lum16DC run (3,0) k=3 vlc=6 001 ( 1) @989488 Lum16DC run (2,0) k=2 vlc=2 11 ( 3) @989490 Lum16DC run (1,0) k=1 vlc=2 00 ( 0) @989492 ChrDC # c & tr.1s #c=2 #t1=2 001 ( 1) @989495 ChrDC trailing ones sign (0,0) 01 ( 1) @989497 ChrDC totalrun (0,0) vlc=1 01 ( 1) @989499 ChrDC run (1,0) k=1 vlc=0 0 ( 0) @989500 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) @989502 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @989503 ChrAC # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @989505 ChrAC trailing ones sign (1,4) 0 ( 0) @989506 ChrAC totalrun (1,4) vlc=0 011 ( 3) @989509 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @989510 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @989511 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @989512 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @989513 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @989514 ChrAC # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) """ bs = VerboseWrapper( BitStream( buf=binData("000010000 010 1 000011 111 001 0010 001 11 00 001 01 01 0 01 1 01 0 011 1 1 1 1 1 1 " ) ), startOffset=2871689 ) # without skip left = [[0, 0, 0, 0], [0, 0], [0, 0]] up = [[0, 0, 0, 0], [0, 0], [0, 0]] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 989515-989456 ) def testDCError( self ): # frame0380.bin - this was in reality problem due to unhandled ESCAPE sequence """ *********** POC: 50 (I/P) MB: 244 Slice: 0 Type 0 ********** @3584943 mb_skip_run 1 ( 0) @3584944 mb_type 1 ( 0) @3584945 mvd0_l0 00000100000 ( 16) @3584956 mvd1_l0 1 ( 0) @3584957 coded_block_pattern 00000100011 ( 20) @3584968 mb_qp_delta 00101 ( -2) @3584973 Luma # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @3584975 Luma trailing ones sign (0,2) 1 ( 1) @3584976 Luma totalrun (0,2) vlc=0 1 ( 1) @3584977 Luma # c & tr.1s vlc=0 #c=0 #t1=0 1 ( 1) @3584978 Luma # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @3584980 Luma trailing ones sign (0,3) 1 ( 1) @3584981 Luma totalrun (0,3) vlc=0 011 ( 3) @3584984 Luma # c & tr.1s vlc=0 #c=1 #t1=1 01 ( 1) @3584986 Luma trailing ones sign (1,3) 0 ( 0) @3584987 Luma totalrun (1,3) vlc=0 1 ( 1) @3584988 ChrDC # c & tr.1s #c=4 #t1=3 0000000 ( 0) @3584995 ChrDC trailing ones sign (0,0) 000 ( 0) @3584998 ChrDC lev (0,0) k=0 vlc=0 00000000000001 ( 1) @3585012 ChrDC # c & tr.1s #c=0 #t1=0 01 ( 1) """ bs = VerboseWrapper( BitStream( buf=binData("1 00000100000 1 00000100011 00101 01 1 1 1 01 1 011 01 0 1 0000000 000 00000000000001 01 " ) ), startOffset=3584944 ) # without skip left = [[0, 0, 0, 0], [0, 1], [0, 0]] up = [[0, 0, 0, 1], [0, 0], [0, 0]] macroblockLayer( bs, left, up ) self.assertEqual( bs.worker.index, 3585014-3584944 ) def testRemoveEscape( self ): buf = "".join( [chr(x) for x in [0x04, 0x65, 0x7B, 0x6A, 0x00, 0x00, 0x03, 0x02, 0xE0, 0xD0, 0x0A]] ) self.assertEqual( removeEscape( buf ), "".join( [chr(x) for x in [0x04, 0x65, 0x7B, 0x6A, 0x00, 0x00, 0x02, 0xE0, 0xD0, 0x0A]] ) ) def testDroneSPS( self ): bs = BitStream( buf = "".join( [chr(x) for x in [0x42, 0x80, 0x1f, 0x8b, 0x68, 0x5, 0x0, 0x5b, 0x10]] ) ) self.assertEqual( bs.bits(8), 66 ) # profileIdc ... 66 = Baseline profile bs.bits(8) # flag set 012 self.assertEqual( bs.bits(8), 31 ) # level def testBitG( self ): bs = BitStream( buf = "\xAF" ) self.assertEqual( bs.bitG().next(), 1 ) self.assertEqual( bs.bitG().next(), 1 ) gen = bs.bitG() self.assertEqual( gen.next(), 1 ) self.assertEqual( gen.next(), 0 ) self.assertEqual( bs.gen.next(), 1 ) self.assertEqual( bs.gen.next(), 0 ) def testBitAutomat( self ): bs = BitStream( buf = "\x5F" ) tab = { '01':0, '00':1, '1':2 } automat = makeAutomat( tab ) self.assertEqual( bs.bitAutomat( automat ), 0 ) self.assertEqual( bs.bitAutomat( automat ), 0 ) self.assertEqual( bs.bitAutomat( automat ), 2 ) if __name__ == "__main__": setVerbose( False ) unittest.main()
<gh_stars>1-10 # Generated by the protocol buffer compiler. DO NOT EDIT! # sources: onos/ransim/model/model.proto # plugin: python-betterproto from dataclasses import dataclass from typing import AsyncIterator, Dict, List, Optional import betterproto from betterproto.grpc.grpclib_server import ServiceBase import grpclib class EventType(betterproto.Enum): """Change event type""" # NONE indicates this response represents a pre-existing entity NONE = 0 # CREATED indicates a new entity was created CREATED = 1 # UPDATED indicates an existing entity was updated UPDATED = 2 # DELETED indicates an entity was deleted DELETED = 3 @dataclass(eq=False, repr=False) class DataSet(betterproto.Message): type: str = betterproto.string_field(1) data: bytes = betterproto.bytes_field(2) @dataclass(eq=False, repr=False) class LoadRequest(betterproto.Message): data_set: List["DataSet"] = betterproto.message_field(1) resume: bool = betterproto.bool_field(2) @dataclass(eq=False, repr=False) class LoadResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class ClearRequest(betterproto.Message): resume: bool = betterproto.bool_field(1) @dataclass(eq=False, repr=False) class ClearResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class PlmnIdRequest(betterproto.Message): pass @dataclass(eq=False, repr=False) class PlmnIdResponse(betterproto.Message): plmnid: int = betterproto.uint32_field(1) @dataclass(eq=False, repr=False) class CreateNodeRequest(betterproto.Message): """CreateNodeRequest create a node request""" node: "_types__.Node" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class CreateNodeResponse(betterproto.Message): """CreateNodeResponse create a node response""" pass @dataclass(eq=False, repr=False) class GetNodeRequest(betterproto.Message): """GetNodeRequest get a node request""" enbid: int = betterproto.uint64_field(1) @dataclass(eq=False, repr=False) class GetNodeResponse(betterproto.Message): """GetNodeResponse get a node response""" node: "_types__.Node" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class UpdateNodeRequest(betterproto.Message): """UpdateNodeRequest update a node request""" node: "_types__.Node" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class UpdateNodeResponse(betterproto.Message): """UpdateNodeResponse update a node response""" pass @dataclass(eq=False, repr=False) class DeleteNodeRequest(betterproto.Message): """DeleteNodeRequest delete a node request""" enbid: int = betterproto.uint64_field(1) @dataclass(eq=False, repr=False) class DeleteNodeResponse(betterproto.Message): """DeleteNodeResponse delete a node response""" pass @dataclass(eq=False, repr=False) class ListNodesRequest(betterproto.Message): pass @dataclass(eq=False, repr=False) class ListNodesResponse(betterproto.Message): node: "_types__.Node" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class WatchNodesRequest(betterproto.Message): no_replay: bool = betterproto.bool_field(1) no_subscribe: bool = betterproto.bool_field(2) @dataclass(eq=False, repr=False) class WatchNodesResponse(betterproto.Message): node: "_types__.Node" = betterproto.message_field(1) type: "EventType" = betterproto.enum_field(2) @dataclass(eq=False, repr=False) class AgentControlRequest(betterproto.Message): enbid: int = betterproto.uint64_field(1) command: str = betterproto.string_field(2) args: List[str] = betterproto.string_field(3) @dataclass(eq=False, repr=False) class AgentControlResponse(betterproto.Message): node: "_types__.Node" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class CreateCellRequest(betterproto.Message): cell: "_types__.Cell" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class CreateCellResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class GetCellRequest(betterproto.Message): ecgi: int = betterproto.uint64_field(1) @dataclass(eq=False, repr=False) class GetCellResponse(betterproto.Message): cell: "_types__.Cell" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class UpdateCellRequest(betterproto.Message): cell: "_types__.Cell" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class UpdateCellResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class DeleteCellRequest(betterproto.Message): enbid: int = betterproto.uint64_field(1) @dataclass(eq=False, repr=False) class DeleteCellResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class WatchCellsRequest(betterproto.Message): no_replay: bool = betterproto.bool_field(1) no_subscribe: bool = betterproto.bool_field(2) @dataclass(eq=False, repr=False) class WatchCellsResponse(betterproto.Message): cell: "_types__.Cell" = betterproto.message_field(1) type: "EventType" = betterproto.enum_field(2) @dataclass(eq=False, repr=False) class ListCellsRequest(betterproto.Message): pass @dataclass(eq=False, repr=False) class ListCellsResponse(betterproto.Message): cell: "_types__.Cell" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class CreateRouteRequest(betterproto.Message): route: "_types__.Route" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class CreateRouteResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class GetRouteRequest(betterproto.Message): imsi: int = betterproto.uint32_field(1) @dataclass(eq=False, repr=False) class GetRouteResponse(betterproto.Message): route: "_types__.Route" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class DeleteRouteRequest(betterproto.Message): enbid: int = betterproto.uint64_field(1) @dataclass(eq=False, repr=False) class DeleteRouteResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class WatchRoutesRequest(betterproto.Message): no_replay: bool = betterproto.bool_field(1) no_subscribe: bool = betterproto.bool_field(2) @dataclass(eq=False, repr=False) class WatchRoutesResponse(betterproto.Message): route: "_types__.Route" = betterproto.message_field(1) type: "EventType" = betterproto.enum_field(2) @dataclass(eq=False, repr=False) class ListRoutesRequest(betterproto.Message): pass @dataclass(eq=False, repr=False) class ListRoutesResponse(betterproto.Message): route: "_types__.Route" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class GetUeRequest(betterproto.Message): imsi: int = betterproto.uint32_field(1) @dataclass(eq=False, repr=False) class GetUeResponse(betterproto.Message): ue: "_types__.Ue" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class MoveToCellRequest(betterproto.Message): imsi: int = betterproto.uint32_field(1) ecgi: int = betterproto.uint32_field(2) @dataclass(eq=False, repr=False) class MoveToCellResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class MoveToLocationRequest(betterproto.Message): imsi: int = betterproto.uint32_field(1) location: "_types__.Point" = betterproto.message_field(2) heading: int = betterproto.uint32_field(3) @dataclass(eq=False, repr=False) class MoveToLocationResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class DeleteUeRequest(betterproto.Message): imsi: int = betterproto.uint32_field(1) @dataclass(eq=False, repr=False) class DeleteUeResponse(betterproto.Message): pass @dataclass(eq=False, repr=False) class WatchUEsRequest(betterproto.Message): no_replay: bool = betterproto.bool_field(1) no_subscribe: bool = betterproto.bool_field(2) @dataclass(eq=False, repr=False) class WatchUEsResponse(betterproto.Message): ue: "_types__.Ue" = betterproto.message_field(1) type: "EventType" = betterproto.enum_field(2) @dataclass(eq=False, repr=False) class ListUEsRequest(betterproto.Message): pass @dataclass(eq=False, repr=False) class ListUEsResponse(betterproto.Message): ue: "_types__.Ue" = betterproto.message_field(1) @dataclass(eq=False, repr=False) class GetUeCountRequest(betterproto.Message): pass @dataclass(eq=False, repr=False) class GetUeCountResponse(betterproto.Message): count: int = betterproto.uint32_field(1) @dataclass(eq=False, repr=False) class SetUeCountRequest(betterproto.Message): count: int = betterproto.uint32_field(1) @dataclass(eq=False, repr=False) class SetUeCountResponse(betterproto.Message): pass class ModelServiceStub(betterproto.ServiceStub): async def load( self, *, data_set: Optional[List["DataSet"]] = None, resume: bool = False ) -> "LoadResponse": data_set = data_set or [] request = LoadRequest() if data_set is not None: request.data_set = data_set request.resume = resume return await self._unary_unary( "/onos.ransim.model.ModelService/Load", request, LoadResponse ) async def clear(self, *, resume: bool = False) -> "ClearResponse": request = ClearRequest() request.resume = resume return await self._unary_unary( "/onos.ransim.model.ModelService/Clear", request, ClearResponse ) class NodeModelStub(betterproto.ServiceStub): async def get_plmn_id(self) -> "PlmnIdResponse": request = PlmnIdRequest() return await self._unary_unary( "/onos.ransim.model.NodeModel/GetPlmnID", request, PlmnIdResponse ) async def create_node( self, *, node: "_types__.Node" = None ) -> "CreateNodeResponse": request = CreateNodeRequest() if node is not None: request.node = node return await self._unary_unary( "/onos.ransim.model.NodeModel/CreateNode", request, CreateNodeResponse ) async def get_node(self, *, enbid: int = 0) -> "GetNodeResponse": request = GetNodeRequest() request.enbid = enbid return await self._unary_unary( "/onos.ransim.model.NodeModel/GetNode", request, GetNodeResponse ) async def update_node( self, *, node: "_types__.Node" = None ) -> "UpdateNodeResponse": request = UpdateNodeRequest() if node is not None: request.node = node return await self._unary_unary( "/onos.ransim.model.NodeModel/UpdateNode", request, UpdateNodeResponse ) async def delete_node(self, *, enbid: int = 0) -> "DeleteNodeResponse": request = DeleteNodeRequest() request.enbid = enbid return await self._unary_unary( "/onos.ransim.model.NodeModel/DeleteNode", request, DeleteNodeResponse ) async def watch_nodes( self, *, no_replay: bool = False, no_subscribe: bool = False ) -> AsyncIterator["WatchNodesResponse"]: request = WatchNodesRequest() request.no_replay = no_replay request.no_subscribe = no_subscribe async for response in self._unary_stream( "/onos.ransim.model.NodeModel/WatchNodes", request, WatchNodesResponse, ): yield response async def list_nodes(self) -> AsyncIterator["ListNodesResponse"]: request = ListNodesRequest() async for response in self._unary_stream( "/onos.ransim.model.NodeModel/ListNodes", request, ListNodesResponse, ): yield response async def agent_control( self, *, enbid: int = 0, command: str = "", args: Optional[List[str]] = None ) -> "AgentControlResponse": args = args or [] request = AgentControlRequest() request.enbid = enbid request.command = command request.args = args return await self._unary_unary( "/onos.ransim.model.NodeModel/AgentControl", request, AgentControlResponse ) class CellModelStub(betterproto.ServiceStub): async def create_cell( self, *, cell: "_types__.Cell" = None ) -> "CreateCellResponse": request = CreateCellRequest() if cell is not None: request.cell = cell return await self._unary_unary( "/onos.ransim.model.CellModel/CreateCell", request, CreateCellResponse ) async def delete_cell(self, *, enbid: int = 0) -> "DeleteCellResponse": request = DeleteCellRequest() request.enbid = enbid return await self._unary_unary( "/onos.ransim.model.CellModel/DeleteCell", request, DeleteCellResponse ) async def update_cell( self, *, cell: "_types__.Cell" = None ) -> "UpdateCellResponse": request = UpdateCellRequest() if cell is not None: request.cell = cell return await self._unary_unary( "/onos.ransim.model.CellModel/UpdateCell", request, UpdateCellResponse ) async def get_cell(self, *, ecgi: int = 0) -> "GetCellResponse": request = GetCellRequest() request.ecgi = ecgi return await self._unary_unary( "/onos.ransim.model.CellModel/GetCell", request, GetCellResponse ) async def watch_cells( self, *, no_replay: bool = False, no_subscribe: bool = False ) -> AsyncIterator["WatchCellsResponse"]: request = WatchCellsRequest() request.no_replay = no_replay request.no_subscribe = no_subscribe async for response in self._unary_stream( "/onos.ransim.model.CellModel/WatchCells", request, WatchCellsResponse, ): yield response async def list_cells(self) -> AsyncIterator["ListCellsResponse"]: request = ListCellsRequest() async for response in self._unary_stream( "/onos.ransim.model.CellModel/ListCells", request, ListCellsResponse, ): yield response class RouteModelStub(betterproto.ServiceStub): async def create_route( self, *, route: "_types__.Route" = None ) -> "CreateRouteResponse": request = CreateRouteRequest() if route is not None: request.route = route return await self._unary_unary( "/onos.ransim.model.RouteModel/CreateRoute", request, CreateRouteResponse ) async def delete_route(self, *, enbid: int = 0) -> "DeleteRouteResponse": request = DeleteRouteRequest() request.enbid = enbid return await self._unary_unary( "/onos.ransim.model.RouteModel/DeleteRoute", request, DeleteRouteResponse ) async def get_route(self, *, imsi: int = 0) -> "GetRouteResponse": request = GetRouteRequest() request.imsi = imsi return await self._unary_unary( "/onos.ransim.model.RouteModel/GetRoute", request, GetRouteResponse ) async def watch_routes( self, *, no_replay: bool = False, no_subscribe: bool = False ) -> AsyncIterator["WatchRoutesResponse"]: request = WatchRoutesRequest() request.no_replay = no_replay request.no_subscribe = no_subscribe async for response in self._unary_stream( "/onos.ransim.model.RouteModel/WatchRoutes", request, WatchRoutesResponse, ): yield response async def list_routes(self) -> AsyncIterator["ListRoutesResponse"]: request = ListRoutesRequest() async for response in self._unary_stream( "/onos.ransim.model.RouteModel/ListRoutes", request, ListRoutesResponse, ): yield response class UeModelStub(betterproto.ServiceStub): async def get_ue(self) -> "GetUeResponse": request = GetUeRequest() return await self._unary_unary( "/onos.ransim.model.UEModel/GetUE", request, GetUeResponse ) async def move_to_cell( self, *, imsi: int = 0, ecgi: int = 0 ) -> "MoveToCellResponse": request = MoveToCellRequest() request.imsi = imsi request.ecgi = ecgi return await self._unary_unary( "/onos.ransim.model.UEModel/MoveToCell", request, MoveToCellResponse ) async def move_to_location( self, *, imsi: int = 0, location: "_types__.Point" = None, heading: int = 0 ) -> "MoveToLocationResponse": request = MoveToLocationRequest() request.imsi = imsi if location is not None: request.location = location request.heading = heading return await self._unary_unary( "/onos.ransim.model.UEModel/MoveToLocation", request, MoveToLocationResponse ) async def delete_ue(self) -> "DeleteUeResponse": request = DeleteUeRequest() return await self._unary_unary( "/onos.ransim.model.UEModel/DeleteUE", request, DeleteUeResponse ) async def watch_u_es( self, *, no_replay: bool = False, no_subscribe: bool = False ) -> AsyncIterator["WatchUEsResponse"]: request = WatchUEsRequest() request.no_replay = no_replay request.no_subscribe = no_subscribe async for response in self._unary_stream( "/onos.ransim.model.UEModel/WatchUEs", request, WatchUEsResponse, ): yield response async def list_u_es(self) -> AsyncIterator["ListUEsResponse"]: request = ListUEsRequest() async for response in self._unary_stream( "/onos.ransim.model.UEModel/ListUEs", request, ListUEsResponse, ): yield response async def get_ue_count(self) -> "GetUeCountResponse": request = GetUeCountRequest() return await self._unary_unary( "/onos.ransim.model.UEModel/GetUECount", request, GetUeCountResponse ) async def set_ue_count(self) -> "SetUeCountResponse": request = SetUeCountRequest() return await self._unary_unary( "/onos.ransim.model.UEModel/SetUECount", request, SetUeCountResponse ) class ModelServiceBase(ServiceBase): async def load( self, data_set: Optional[List["DataSet"]], resume: bool ) -> "LoadResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def clear(self, resume: bool) -> "ClearResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def __rpc_load(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "data_set": request.data_set, "resume": request.resume, } response = await self.load(**request_kwargs) await stream.send_message(response) async def __rpc_clear(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "resume": request.resume, } response = await self.clear(**request_kwargs) await stream.send_message(response) def __mapping__(self) -> Dict[str, grpclib.const.Handler]: return { "/onos.ransim.model.ModelService/Load": grpclib.const.Handler( self.__rpc_load, grpclib.const.Cardinality.UNARY_UNARY, LoadRequest, LoadResponse, ), "/onos.ransim.model.ModelService/Clear": grpclib.const.Handler( self.__rpc_clear, grpclib.const.Cardinality.UNARY_UNARY, ClearRequest, ClearResponse, ), } class NodeModelBase(ServiceBase): async def get_plmn_id(self) -> "PlmnIdResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def create_node(self, node: "_types__.Node") -> "CreateNodeResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def get_node(self, enbid: int) -> "GetNodeResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def update_node(self, node: "_types__.Node") -> "UpdateNodeResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def delete_node(self, enbid: int) -> "DeleteNodeResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def watch_nodes( self, no_replay: bool, no_subscribe: bool ) -> AsyncIterator["WatchNodesResponse"]: raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def list_nodes(self) -> AsyncIterator["ListNodesResponse"]: raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def agent_control( self, enbid: int, command: str, args: Optional[List[str]] ) -> "AgentControlResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def __rpc_get_plmn_id(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} response = await self.get_plmn_id(**request_kwargs) await stream.send_message(response) async def __rpc_create_node(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "node": request.node, } response = await self.create_node(**request_kwargs) await stream.send_message(response) async def __rpc_get_node(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "enbid": request.enbid, } response = await self.get_node(**request_kwargs) await stream.send_message(response) async def __rpc_update_node(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "node": request.node, } response = await self.update_node(**request_kwargs) await stream.send_message(response) async def __rpc_delete_node(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "enbid": request.enbid, } response = await self.delete_node(**request_kwargs) await stream.send_message(response) async def __rpc_watch_nodes(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "no_replay": request.no_replay, "no_subscribe": request.no_subscribe, } await self._call_rpc_handler_server_stream( self.watch_nodes, stream, request_kwargs, ) async def __rpc_list_nodes(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} await self._call_rpc_handler_server_stream( self.list_nodes, stream, request_kwargs, ) async def __rpc_agent_control(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "enbid": request.enbid, "command": request.command, "args": request.args, } response = await self.agent_control(**request_kwargs) await stream.send_message(response) def __mapping__(self) -> Dict[str, grpclib.const.Handler]: return { "/onos.ransim.model.NodeModel/GetPlmnID": grpclib.const.Handler( self.__rpc_get_plmn_id, grpclib.const.Cardinality.UNARY_UNARY, PlmnIdRequest, PlmnIdResponse, ), "/onos.ransim.model.NodeModel/CreateNode": grpclib.const.Handler( self.__rpc_create_node, grpclib.const.Cardinality.UNARY_UNARY, CreateNodeRequest, CreateNodeResponse, ), "/onos.ransim.model.NodeModel/GetNode": grpclib.const.Handler( self.__rpc_get_node, grpclib.const.Cardinality.UNARY_UNARY, GetNodeRequest, GetNodeResponse, ), "/onos.ransim.model.NodeModel/UpdateNode": grpclib.const.Handler( self.__rpc_update_node, grpclib.const.Cardinality.UNARY_UNARY, UpdateNodeRequest, UpdateNodeResponse, ), "/onos.ransim.model.NodeModel/DeleteNode": grpclib.const.Handler( self.__rpc_delete_node, grpclib.const.Cardinality.UNARY_UNARY, DeleteNodeRequest, DeleteNodeResponse, ), "/onos.ransim.model.NodeModel/WatchNodes": grpclib.const.Handler( self.__rpc_watch_nodes, grpclib.const.Cardinality.UNARY_STREAM, WatchNodesRequest, WatchNodesResponse, ), "/onos.ransim.model.NodeModel/ListNodes": grpclib.const.Handler( self.__rpc_list_nodes, grpclib.const.Cardinality.UNARY_STREAM, ListNodesRequest, ListNodesResponse, ), "/onos.ransim.model.NodeModel/AgentControl": grpclib.const.Handler( self.__rpc_agent_control, grpclib.const.Cardinality.UNARY_UNARY, AgentControlRequest, AgentControlResponse, ), } class CellModelBase(ServiceBase): async def create_cell(self, cell: "_types__.Cell") -> "CreateCellResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def delete_cell(self, enbid: int) -> "DeleteCellResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def update_cell(self, cell: "_types__.Cell") -> "UpdateCellResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def get_cell(self, ecgi: int) -> "GetCellResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def watch_cells( self, no_replay: bool, no_subscribe: bool ) -> AsyncIterator["WatchCellsResponse"]: raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def list_cells(self) -> AsyncIterator["ListCellsResponse"]: raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def __rpc_create_cell(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "cell": request.cell, } response = await self.create_cell(**request_kwargs) await stream.send_message(response) async def __rpc_delete_cell(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "enbid": request.enbid, } response = await self.delete_cell(**request_kwargs) await stream.send_message(response) async def __rpc_update_cell(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "cell": request.cell, } response = await self.update_cell(**request_kwargs) await stream.send_message(response) async def __rpc_get_cell(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "ecgi": request.ecgi, } response = await self.get_cell(**request_kwargs) await stream.send_message(response) async def __rpc_watch_cells(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "no_replay": request.no_replay, "no_subscribe": request.no_subscribe, } await self._call_rpc_handler_server_stream( self.watch_cells, stream, request_kwargs, ) async def __rpc_list_cells(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} await self._call_rpc_handler_server_stream( self.list_cells, stream, request_kwargs, ) def __mapping__(self) -> Dict[str, grpclib.const.Handler]: return { "/onos.ransim.model.CellModel/CreateCell": grpclib.const.Handler( self.__rpc_create_cell, grpclib.const.Cardinality.UNARY_UNARY, CreateCellRequest, CreateCellResponse, ), "/onos.ransim.model.CellModel/DeleteCell": grpclib.const.Handler( self.__rpc_delete_cell, grpclib.const.Cardinality.UNARY_UNARY, DeleteCellRequest, DeleteCellResponse, ), "/onos.ransim.model.CellModel/UpdateCell": grpclib.const.Handler( self.__rpc_update_cell, grpclib.const.Cardinality.UNARY_UNARY, UpdateCellRequest, UpdateCellResponse, ), "/onos.ransim.model.CellModel/GetCell": grpclib.const.Handler( self.__rpc_get_cell, grpclib.const.Cardinality.UNARY_UNARY, GetCellRequest, GetCellResponse, ), "/onos.ransim.model.CellModel/WatchCells": grpclib.const.Handler( self.__rpc_watch_cells, grpclib.const.Cardinality.UNARY_STREAM, WatchCellsRequest, WatchCellsResponse, ), "/onos.ransim.model.CellModel/ListCells": grpclib.const.Handler( self.__rpc_list_cells, grpclib.const.Cardinality.UNARY_STREAM, ListCellsRequest, ListCellsResponse, ), } class RouteModelBase(ServiceBase): async def create_route(self, route: "_types__.Route") -> "CreateRouteResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def delete_route(self, enbid: int) -> "DeleteRouteResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def get_route(self, imsi: int) -> "GetRouteResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def watch_routes( self, no_replay: bool, no_subscribe: bool ) -> AsyncIterator["WatchRoutesResponse"]: raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def list_routes(self) -> AsyncIterator["ListRoutesResponse"]: raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def __rpc_create_route(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "route": request.route, } response = await self.create_route(**request_kwargs) await stream.send_message(response) async def __rpc_delete_route(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "enbid": request.enbid, } response = await self.delete_route(**request_kwargs) await stream.send_message(response) async def __rpc_get_route(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "imsi": request.imsi, } response = await self.get_route(**request_kwargs) await stream.send_message(response) async def __rpc_watch_routes(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "no_replay": request.no_replay, "no_subscribe": request.no_subscribe, } await self._call_rpc_handler_server_stream( self.watch_routes, stream, request_kwargs, ) async def __rpc_list_routes(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} await self._call_rpc_handler_server_stream( self.list_routes, stream, request_kwargs, ) def __mapping__(self) -> Dict[str, grpclib.const.Handler]: return { "/onos.ransim.model.RouteModel/CreateRoute": grpclib.const.Handler( self.__rpc_create_route, grpclib.const.Cardinality.UNARY_UNARY, CreateRouteRequest, CreateRouteResponse, ), "/onos.ransim.model.RouteModel/DeleteRoute": grpclib.const.Handler( self.__rpc_delete_route, grpclib.const.Cardinality.UNARY_UNARY, DeleteRouteRequest, DeleteRouteResponse, ), "/onos.ransim.model.RouteModel/GetRoute": grpclib.const.Handler( self.__rpc_get_route, grpclib.const.Cardinality.UNARY_UNARY, GetRouteRequest, GetRouteResponse, ), "/onos.ransim.model.RouteModel/WatchRoutes": grpclib.const.Handler( self.__rpc_watch_routes, grpclib.const.Cardinality.UNARY_STREAM, WatchRoutesRequest, WatchRoutesResponse, ), "/onos.ransim.model.RouteModel/ListRoutes": grpclib.const.Handler( self.__rpc_list_routes, grpclib.const.Cardinality.UNARY_STREAM, ListRoutesRequest, ListRoutesResponse, ), } class UeModelBase(ServiceBase): async def get_ue(self) -> "GetUeResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def move_to_cell(self, imsi: int, ecgi: int) -> "MoveToCellResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def move_to_location( self, imsi: int, location: "_types__.Point", heading: int ) -> "MoveToLocationResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def delete_ue(self) -> "DeleteUeResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def watch_u_es( self, no_replay: bool, no_subscribe: bool ) -> AsyncIterator["WatchUEsResponse"]: raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def list_u_es(self) -> AsyncIterator["ListUEsResponse"]: raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def get_ue_count(self) -> "GetUeCountResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def set_ue_count(self) -> "SetUeCountResponse": raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED) async def __rpc_get_ue(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} response = await self.get_ue(**request_kwargs) await stream.send_message(response) async def __rpc_move_to_cell(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "imsi": request.imsi, "ecgi": request.ecgi, } response = await self.move_to_cell(**request_kwargs) await stream.send_message(response) async def __rpc_move_to_location(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "imsi": request.imsi, "location": request.location, "heading": request.heading, } response = await self.move_to_location(**request_kwargs) await stream.send_message(response) async def __rpc_delete_ue(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} response = await self.delete_ue(**request_kwargs) await stream.send_message(response) async def __rpc_watch_u_es(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = { "no_replay": request.no_replay, "no_subscribe": request.no_subscribe, } await self._call_rpc_handler_server_stream( self.watch_u_es, stream, request_kwargs, ) async def __rpc_list_u_es(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} await self._call_rpc_handler_server_stream( self.list_u_es, stream, request_kwargs, ) async def __rpc_get_ue_count(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} response = await self.get_ue_count(**request_kwargs) await stream.send_message(response) async def __rpc_set_ue_count(self, stream: grpclib.server.Stream) -> None: request = await stream.recv_message() request_kwargs = {} response = await self.set_ue_count(**request_kwargs) await stream.send_message(response) def __mapping__(self) -> Dict[str, grpclib.const.Handler]: return { "/onos.ransim.model.UEModel/GetUE": grpclib.const.Handler( self.__rpc_get_ue, grpclib.const.Cardinality.UNARY_UNARY, GetUeRequest, GetUeResponse, ), "/onos.ransim.model.UEModel/MoveToCell": grpclib.const.Handler( self.__rpc_move_to_cell, grpclib.const.Cardinality.UNARY_UNARY, MoveToCellRequest, MoveToCellResponse, ), "/onos.ransim.model.UEModel/MoveToLocation": grpclib.const.Handler( self.__rpc_move_to_location, grpclib.const.Cardinality.UNARY_UNARY, MoveToLocationRequest, MoveToLocationResponse, ), "/onos.ransim.model.UEModel/DeleteUE": grpclib.const.Handler( self.__rpc_delete_ue, grpclib.const.Cardinality.UNARY_UNARY, DeleteUeRequest, DeleteUeResponse, ), "/onos.ransim.model.UEModel/WatchUEs": grpclib.const.Handler( self.__rpc_watch_u_es, grpclib.const.Cardinality.UNARY_STREAM, WatchUEsRequest, WatchUEsResponse, ), "/onos.ransim.model.UEModel/ListUEs": grpclib.const.Handler( self.__rpc_list_u_es, grpclib.const.Cardinality.UNARY_STREAM, ListUEsRequest, ListUEsResponse, ), "/onos.ransim.model.UEModel/GetUECount": grpclib.const.Handler( self.__rpc_get_ue_count, grpclib.const.Cardinality.UNARY_UNARY, GetUeCountRequest, GetUeCountResponse, ), "/onos.ransim.model.UEModel/SetUECount": grpclib.const.Handler( self.__rpc_set_ue_count, grpclib.const.Cardinality.UNARY_UNARY, SetUeCountRequest, SetUeCountResponse, ), } from .. import types as _types__
""" This module provides GLTF 2.0 exports """ import json import collections import numpy as np from .. import util # magic numbers which have meaning in GLTF # most are uint32's of UTF-8 text _magic = {'gltf': 1179937895, 'json': 1313821514, 'bin': 5130562} # GLTF data type codes: numpy dtypes _types = {5120: np.bool, 5122: np.int16, 5123: np.uint16, 5125: np.uint32, 5126: np.float32} # GLTF data formats: numpy shapes _shapes = {'SCALAR': -1, 'VEC2': (-1, 2), 'VEC3': (-1, 3), 'VEC4': (-1, 4), 'MAT2': (2, 2), 'MAT3': (3, 3), 'MAT4': (4, 4)} def export_gltf(scene): """ Export a scene object as a GLTF directory. This has the advantage of putting each mesh into a separate file (buffer) as opposed to one large file, but means multiple files need to be tracked. Parameters ----------- scene: trimesh.Scene object Returns ---------- export: dict, {file name : file data} """ tree, buffer_items = _create_gltf_structure(scene) buffers = [] views = [] files = {} for i, name in zip(range(0, len(buffer_items), 2), scene.geometry.keys()): # create the buffer views current_pos = 0 for j in range(2): current_item = buffer_items[i + j] views.append({"buffer": len(buffers), "byteOffset": current_pos, "byteLength": len(current_item)}) current_pos += len(current_item) # the data is just appended buffer_data = bytes().join(buffer_items[i:i + 2]) buffer_name = 'mesh_' + name + '.bin' buffers.append({'uri': buffer_name, 'byteLength': len(buffer_data)}) files[buffer_name] = buffer_data tree['buffers'] = buffers tree['bufferViews'] = views files['model.gltf'] = json.dumps(tree).encode('utf-8') return files def export_glb(scene): """ Export a scene as a binary GLTF (GLB) file. Parameters ------------ scene: trimesh.Scene object Returns ---------- exported: bytes, exported result """ tree, buffer_items = _create_gltf_structure(scene) # A bufferView is a slice of a file views = [] # create the buffer views current_pos = 0 for current_item in buffer_items: views.append({"buffer": 0, "byteOffset": current_pos, "byteLength": len(current_item)}) current_pos += len(current_item) # the data is just appended buffer_data = bytes().join(buffer_items) tree['buffers'] = [{'byteLength': len(buffer_data)}] tree['bufferViews'] = views # export the tree to JSON for the content of the file content = json.dumps(tree) # add spaces to content, so the start of the data # is 4 byte aligned as per spec content += ((len(content) + 20) % 4) * ' ' content = content.encode('utf-8') # the initial header of the file header = np.array([_magic['gltf'], # magic, turns into glTF 2, # GLTF version # length is the total length of the Binary glTF # including Header and all Chunks, in bytes. len(content) + len(buffer_data) + 28, # contentLength is the length, in bytes, # of the glTF content (JSON) len(content), # magic number which is 'JSON' 1313821514], dtype=np.uint32) # the header of the binary data section bin_header = np.array([len(buffer_data), 0x004E4942], dtype=np.uint32) exported = (header.tostring() + content + bin_header.tostring() + buffer_data) return exported def load_glb(file_obj, **passed): """ Load a GLTF file in the binary GLB format into a trimesh.Scene. Implemented from specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0 Parameters ------------ file_obj: file- like object containing GLB file Returns ------------ kwargs: dict, kwargs to instantiate a trimesh.Scene """ # save the start position of the file for referencing # against lengths start = file_obj.tell() # read the first 20 bytes which contain section lengths head_data = file_obj.read(20) head = np.frombuffer(head_data, dtype=np.uint32) # check to make sure first index is gltf # and second is 2, for GLTF 2.0 if head[0] != _magic['gltf'] or head[1] != 2: raise ValueError('file is not GLTF 2.0') # overall file length # first chunk length # first chunk type length, chunk_length, chunk_type = head[2:] # first chunk should be JSON header if chunk_type != _magic['json']: raise ValueError('no initial JSON header!') # np.uint32 causes an error in read, so we convert to native int # for the length passed to read, for the JSON header json_data = file_obj.read(int(chunk_length)) # convert to text if hasattr(json_data, 'decode'): json_data = json_data.decode('utf-8') # load the json header to native dict header = json.loads(json_data) # read the binary data referred to by GLTF as 'buffers' buffers = [] while (file_obj.tell() - start) < length: # the last read put us past the JSON chunk # we now read the chunk header, which is 8 bytes chunk_head = file_obj.read(8) if len(chunk_head) != 8: # double check to make sure we didn't # read the whole file break chunk_length, chunk_type = np.frombuffer(chunk_head, dtype=np.uint32) # make sure we have the right data type if chunk_type != _magic['bin']: raise ValueError('not binary GLTF!') # read the chunk chunk_data = file_obj.read(int(chunk_length)) if len(chunk_data) != chunk_length: raise ValueError('chunk was not expected length!') buffers.append(chunk_data) # turn the layout header and data into kwargs # that can be used to instantiate a trimesh.Scene object kwargs = _read_buffers(header=header, buffers=buffers) return kwargs def _mesh_to_material(mesh, metallic=.02, rough=.1): """ Create a simple GLTF material for a mesh using the most commonly occurring color in that mesh. Parameters ------------ mesh: Trimesh object Returns ------------ material: dict, in GLTF material format """ # just get the most commonly occurring color color = mesh.visual.main_color # convert uint color to 0-1.0 float color color = color.astype(float) / (2 ** (8 * color.dtype.itemsize)) material = {'pbrMetallicRoughness': {'baseColorFactor': color.tolist(), 'metallicFactor': metallic, 'roughnessFactor': rough}} return material def _create_gltf_structure(scene): """ Generate a GLTF header """ # we are defining a single scene, and will be setting the # world node to the 0th index tree = {'scene': 0, 'scenes': [{'nodes': [0]}], "asset": {"version": "2.0", "generator": "github.com/mikedh/trimesh"}, 'accessors': [], 'meshes': [], 'materials': []} # GLTF references meshes by index, so store them here mesh_index = {name: i for i, name in enumerate(scene.geometry.keys())} # grab the flattened scene graph in GLTF's format nodes = scene.graph.to_gltf(mesh_index=mesh_index) tree.update(nodes) buffer_items = [] for name, mesh in scene.geometry.items(): # meshes reference accessor indexes tree['meshes'].append({"name": name, "primitives": [ {"attributes": {"POSITION": len(tree['accessors']) + 1}, "indices": len(tree['accessors']), "mode": 4, # mode 4 is GL_TRIANGLES 'material': len(tree['materials'])}]}) tree['materials'].append(_mesh_to_material(mesh)) # accessors refer to data locations # mesh faces are stored as flat list of integers tree['accessors'].append({"bufferView": len(buffer_items), "componentType": 5125, "count": len(mesh.faces) * 3, "max": [int(mesh.faces.max())], "min": [0], "type": "SCALAR"}) # the vertex accessor tree['accessors'].append({"bufferView": len(buffer_items) + 1, "componentType": 5126, "count": len(mesh.vertices), "type": "VEC3", "byteOffset": 0, "max": mesh.vertices.max(axis=0).tolist(), "min": mesh.vertices.min(axis=0).tolist()}) # convert to the correct dtypes # 5126 is a float32 # 5125 is an unsigned 32 bit integer # add faces, then vertices buffer_items.append(mesh.faces.astype(np.uint32).tostring()) buffer_items.append(mesh.vertices.astype(np.float32).tostring()) return tree, buffer_items def _read_buffers(header, buffers): """ Given a list of binary data and a layout, return the kwargs to create a scene object. Parameters ----------- header: dict, with GLTF keys buffers: list, of bytes Returns ----------- kwargs: can be passed to load_kwargs for a trimesh.Scene """ # split buffer data into buffer views views = [] for view in header['bufferViews']: start = view['byteOffset'] end = start + view['byteLength'] views.append(buffers[view['buffer']][start:end]) assert len(views[-1]) == view['byteLength'] # load data from buffers and bufferviews into numpy arrays # using the layout described by accessors access = [] for a in header['accessors']: data = views[a['bufferView']] dtype = _types[a['componentType']] shape = _shapes[a['type']] # is the accessor offset in a buffer if 'byteOffset' in a: start = a['byteOffset'] else: start = 0 # basically the number of columns per_count = np.abs(np.product(shape)) # length is the number of bytes per item times total length = np.dtype(dtype).itemsize * a['count'] * per_count end = start + length array = np.frombuffer(data[start:end], dtype=dtype).reshape(shape) assert len(array) == a['count'] access.append(array) # turn materials into a simple list of colors if populated colors = [] if 'materials' in header: for mat in header['materials']: # get the base color of the material try: color = np.array(mat['pbrMetallicRoughness']['baseColorFactor'], dtype=np.float) except BaseException: color = np.array([.5, .5, .5, 1]) # convert float 0-1 colors to uint8 colors and append colors.append((color * 255).astype(np.uint8)) # load data from accessors into Trimesh objects meshes = collections.OrderedDict() for index, m in enumerate(header['meshes']): color = None kwargs = collections.defaultdict(list) for p in m['primitives']: if p['mode'] != 4: continue faces = access[p['indices']].reshape((-1, 3)) verts = access[p['attributes']['POSITION']] kwargs['faces'].append(faces) kwargs['vertices'].append(verts) if 'material' in p: color = colors[p['material']] else: color = [128, 128, 128, 255] # stack colors to line up with faces kwargs['face_colors'].append(np.tile(color, (len(faces), 1))) # re- index faces (kwargs['vertices'], kwargs['faces']) = util.append_faces(kwargs['vertices'], kwargs['faces']) # stack colors kwargs['face_colors'] = np.vstack(kwargs['face_colors']) if 'name' in m: meshes[m['name']] = kwargs else: meshes[index] = kwargs # make it easier to reference nodes nodes = header['nodes'] # nodes are referenced by index # save their string names if they have one # node index (int) : name (str) names = {} for i, n in enumerate(nodes): if 'name' in n: names[i] = n['name'] else: names[i] = str(i) # make sure we have a unique base frame name base_frame = 'world' if base_frame in names: base_frame = str(int(np.random.random() * 1e10)) names[base_frame] = base_frame # visited, kwargs for scene.graph.update graph = collections.deque() # unvisited, pairs of node indexes queue = collections.deque() # the index of the node which is the root of the tree for root in header['scenes'][header['scene']]['nodes']: # add transform from base frame to these root nodes queue.append([base_frame, root]) # add any children to the queue if 'children' in nodes[root]: queue.extend([root, c] for c in nodes[root]['children']) # meshes are listed by index rather than name # replace the index with a nicer name mesh_names = list(meshes.keys()) # go through the nodes tree to populate # kwargs for scene graph loader while len(queue) > 0: # (int, int) pair of node indexes a, b = queue.pop() # dict of child node child = nodes[b] # add edges of children to be processed if 'children' in child: queue.extend([[b, i] for i in child['children']]) # kwargs to be passed to scene.graph.update kwargs = {'frame_from': names[a], 'frame_to': names[b]} # grab matrix from child # parent -> child relationships have matrix stored in child # for the transform from parent to child if 'matrix' in child: kwargs['matrix'] = np.array(child['matrix']).reshape((4, 4)).T else: kwargs['matrix'] = np.eye(4) if 'mesh' in child: kwargs['geometry'] = mesh_names[child['mesh']] graph.append(kwargs) # kwargs to be loaded result = {'class': 'Scene', 'geometry': meshes, 'graph': graph, 'base_frame': base_frame} return result _gltf_loaders = {'glb': load_glb}
<gh_stars>100-1000 from dynaconf.utils.boxing import DynaBox from datetime import datetime from threatbus_misp import plugin as misp_plugin from threatbus_inmem import plugin as inmem_backbone from queue import Queue import time import unittest import zmq class TestRoundtrips(unittest.TestCase): def test_misp_plugin_indicator_roundtrip(self): """ Backend agnostic message passing screnario. Sends a single MISP Attribute via ZeroMQ to the Threat Bus MISP plugin and checks if the sent message is parsed and forwarded correctly as new STIX-2 Indicator. """ timestamp = 1614599635 misp_attribute_id = "5e1f2787-fcfc-4718-a58a-00b4c0a82f06" misp_attribute_indicator = "example.com" misp_attribute_type = "domain" misp_json_attribute = f"""{{ "Attribute": {{ "id": "15", "event_id": "1", "object_id": "0", "object_relation": null, "category": "Network activity", "type": "{misp_attribute_type}", "value1": "{misp_attribute_indicator}", "value2": "", "to_ids": true, "uuid": "{misp_attribute_id}", "timestamp": "{timestamp}", "distribution": "5", "sharing_group_id": "0", "comment": "", "deleted": false, "disable_correlation": false, "value": "{misp_attribute_indicator}", "Sighting": [] }}, "Event": {{ "id": "1", "date": "{timestamp}", "info": "adsf", "uuid": "5e1ee79d-25c8-42bd-a386-0291c0a82f06", "published": false, "analysis": "0", "threat_level_id": "1", "org_id": "1", "orgc_id": "1", "distribution": "3", "sharing_group_id": "0", "Orgc": {{ "id": "1", "uuid": "5e1edc98-3984-4321-9003-018bfb195b64", "name": "ORGNAME" }} }}, "action": "add" }}""" # emulate a Threat Bus execution environment inq = Queue() outq = Queue() misp_zmq_pub_port = 50001 socket = zmq.Context().socket(zmq.PUB) socket.bind(f"tcp://127.0.0.1:{misp_zmq_pub_port}") config = DynaBox( { "misp": { "zmq": { "host": "127.0.0.1", "port": misp_zmq_pub_port, } }, "inmem": {}, "console": False, "file": False, } ) # start MISP plugin and in-memory backbone empty_callback = lambda x, y: None misp_plugin.run(config, config, inq, empty_callback, empty_callback) inmem_backbone.run(config, config, inq) inmem_backbone.subscribe("stix2/indicator", outq) time.sleep(0.5) # send MISP attribute via ZMQ socket.send_string(f"misp_json_attribute {misp_json_attribute}") # wait for MISP plugin to parse the IoC and forward to backbone where # this test's queue is subscribed at ioc = outq.get(block=True) outq.task_done() outq.join() self.assertEqual(ioc.created, datetime.fromtimestamp(timestamp)) self.assertEqual(ioc.id, f"indicator--{misp_attribute_id}") self.assertEqual(ioc.pattern_type, "stix") self.assertEqual( ioc.pattern, f"[domain-name:value = '{misp_attribute_indicator}']" ) # terminate worker threads from plugins inmem_backbone.stop() misp_plugin.stop()
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Unit tests for graph partitioning.""" import os import sys import json import math import numpy as np import tvm from tvm import te import tvm.relay.testing import tvm.relay.transform from tvm import relay from tvm.relay import transform from tvm import runtime from tvm.contrib import utils import vta import vta.testing def check_result(mod, map_inputs, out_shape, result, tol=1e-5, target="llvm", ctx=tvm.cpu(), use_graph_rt=True): if sys.platform == "win32": print("Skip test on Windows for now") return def update_lib(lib): vta_hw_path = os.environ['VTA_HW_PATH'] tvm_home = os.environ['TVM_HOME'] test_dir = os.path.dirname(os.path.realpath(os.path.expanduser(__file__))) source_dir = os.path.join(test_dir, "..", "..", "..") vta_config = json.load(open('/' + os.path.join(*(vta_hw_path.split(os.path.sep) + ['config', 'vta_config.json'])))) vta_config['LOG_BLOCK_IN'] = vta_config['LOG_BLOCK'] vta_config['LOG_BLOCK_OUT'] = vta_config['LOG_BLOCK'] vta_config['LOG_OUT_WIDTH'] = vta_config['LOG_INP_WIDTH'] vta_config['LOG_OUT_BUFF_SIZE'] = vta_config['LOG_ACC_BUFF_SIZE'] + vta_config['LOG_OUT_WIDTH'] - vta_config['LOG_ACC_WIDTH'] kwargs = {} kwargs["options"] = ["-O2", "-std=c++14", f"-L{tvm_home}/build", "-lvta_fsim", f'-I{tvm_home}/src/runtime/contrib', f"-I{tvm_home}/3rdparty/vta-hw/include"] \ + [f'-D{"VTA_" + x}={y}' for (x, y) in filter(lambda pi: 'LOG' in pi[0], vta_config.items())] kwargs["options"].append(f'-DVTA_LOG_BLOCK_IN={vta_config["LOG_BLOCK"]}') kwargs["options"].append(f'-DVTA_LOG_BLOCK_OUT={vta_config["LOG_BLOCK"]}') tmp_path = utils.tempdir() lib_name = "lib.so" lib_path = tmp_path.relpath(lib_name) lib.export_library(lib_path, fcompile=False, **kwargs) lib = tvm.runtime.load_module(lib_path) return lib def check_vm_result(): with tvm.transform.PassContext(opt_level=3, disabled_pass=["AlterOpLayout"]): exe = relay.vm.compile(mod, target=target) code, lib = exe.save() lib = update_lib(lib) exe = runtime.vm.Executable.load_exec(code, lib) vm = runtime.vm.VirtualMachine(exe, ctx) out = vm.run(**map_inputs) tvm.testing.assert_allclose(out.asnumpy(), result, rtol=tol, atol=tol) def check_graph_runtime_result(): with tvm.transform.PassContext(opt_level=3, disabled_pass=["AlterOpLayout"]): json, lib, _ = relay.build(mod, target=target) lib = update_lib(lib) rt_mod = tvm.contrib.graph_runtime.create(json, lib, ctx) for name, data in map_inputs.items(): rt_mod.set_input(name, data) rt_mod.run() out = tvm.nd.empty(out_shape, ctx=ctx) out = rt_mod.get_output(0, out) tvm.testing.assert_allclose(out.asnumpy(), result, rtol=tol, atol=tol) check_vm_result() if use_graph_rt: check_graph_runtime_result() def set_external_func_attr(func, compiler, ext_symbol): func = func.with_attr("Primitive", tvm.tir.IntImm("int32", 1)) func = func.with_attr("Compiler", compiler) func = func.with_attr("global_symbol", ext_symbol) return func def test_multi_node_subgraph(): x = relay.var("x", shape=(10, 10)) w0 = relay.var("w0", shape=(10, 10)) w1 = relay.var("w1", shape=(10, 10)) w2 = relay.var("w2", shape=(10, 10)) w3 = relay.var("w3", shape=(10, 10)) w4 = relay.var("w4", shape=(10, 10)) w5 = relay.var("w5", shape=(10, 10)) w6 = relay.var("w6", shape=(10, 10)) w7 = relay.var("w7", shape=(10, 10)) # subgraph0 x0 = relay.var("x0", shape=(10, 10)) w00 = relay.var("w00", shape=(10, 10)) w01 = relay.var("w01", shape=(10, 10)) w02 = relay.var("w02", shape=(10, 10)) z00 = relay.add(x0, w00) p00 = relay.subtract(z00, w01) q00 = relay.multiply(p00, w02) subgraph0 = relay.Function([x0, w00, w01, w02], q00) subgraph0 = set_external_func_attr(subgraph0, "ccompiler", "ccompiler_0") call0 = relay.Call(subgraph0, [x, w0, w1, w2]) # subgraph1 x1 = relay.var("x1", shape=(10, 10)) w10 = relay.var("w10", shape=(10, 10)) w11 = relay.var("w11", shape=(10, 10)) w12 = relay.var("w12", shape=(10, 10)) z10 = relay.add(x1, w10) p10 = relay.subtract(z10, w11) q10 = relay.multiply(p10, w12) subgraph1 = relay.Function([x1, w10, w11, w12], q10) subgraph1 = set_external_func_attr(subgraph1, "ccompiler", "ccompiler_1") call1 = relay.Call(subgraph1, [x, w3, w4, w5]) # Other parts on TVM z2 = relay.add(x, w6) q2 = relay.subtract(z2, w7) r = relay.concatenate((call0, call1, q2), axis=0) f = relay.Function([x, w0, w1, w2, w3, w4, w5, w6, w7], r) mod = tvm.IRModule() mod["main"] = f mod = relay.transform.InferType()(mod) x_data = np.random.rand(10, 10).astype("float32") w_data = [] for _ in range(8): w_data.append(np.random.rand(10, 10).astype("float32")) map_inputs = {"w{}".format(i): w_data[i] for i in range(8)} map_inputs["x"] = x_data check_result( mod, map_inputs, (30, 10), np.concatenate( ( ((x_data + w_data[0]) - w_data[1]) * w_data[2], ((x_data + w_data[3]) - w_data[4]) * w_data[5], x_data + w_data[6] - w_data[7], ), axis=0, ), ) def test_extern_gcc_single_op(): x = relay.var("x", shape=(8, 8)) y = relay.var("y", shape=(8, 8)) x0 = relay.var("x0", shape=(8, 8)) y0 = relay.var("y0", shape=(8, 8)) z = x0 + y0 f = relay.Function([x0, y0], z) f = set_external_func_attr(f, "ccompiler", "ccompiler_0") call = relay.Call(f, [x, y]) mod = tvm.IRModule.from_expr(call) x_data = np.random.rand(8, 8).astype("float32") y_data = np.random.rand(8, 8).astype("float32") check_result(mod, {"x": x_data, "y": y_data}, (8, 8), x_data + y_data) def test_extern_gcc_single_op_int(): x = relay.var("x", shape=(8, 8), dtype="int32") y = relay.var("y", shape=(8, 8), dtype="int32") x0 = relay.var("x0", shape=(8, 8), dtype="int32") y0 = relay.var("y0", shape=(8, 8), dtype="int32") z = x0 + y0 f = relay.Function([x0, y0], z) f = set_external_func_attr(f, "ccompiler", "ccompiler_0") call = relay.Call(f, [x, y]) mod = tvm.IRModule.from_expr(call) x_data = np.random.rand(8, 8).astype("int32") y_data = np.random.rand(8, 8).astype("int32") check_result(mod, {"x": x_data, "y": y_data}, (8, 8), x_data + y_data) def test_extern_gcc(): x = relay.var("x", shape=(2, 2)) y = relay.var("y", shape=(2, 2)) # subgraph for mul x0 = relay.var("x0", shape=(2, 2)) y0 = relay.var("y0", shape=(2, 2)) mul = x0 * y0 mul = relay.Function([x0, y0], mul) mul = set_external_func_attr(mul, "ccompiler", "ccompiler_2") call_mul = relay.Call(mul, [y, y]) # subgraph for add x1 = relay.var("x1", shape=(2, 2)) y1 = relay.var("y1", shape=(2, 2)) add = x1 + y1 add = relay.Function([x1, y1], add) add = set_external_func_attr(add, "ccompiler", "ccompiler_1") call_add = relay.Call(add, [x, x]) # subgraph for sub x2 = relay.var("x2", shape=(2, 2)) y2 = relay.var("y2", shape=(2, 2)) sub = x2 - y2 sub = relay.Function([x2, y2], sub) sub = set_external_func_attr(sub, "ccompiler", "ccompiler_0") call_sub = relay.Call(sub, [call_mul, call_add]) mod = tvm.IRModule.from_expr(call_sub) x_data = np.random.rand(2, 2).astype("float32") y_data = np.random.rand(2, 2).astype("float32") check_result(mod, {"x": x_data, "y": y_data}, (2, 2), (y_data * y_data) - (x_data + x_data)) def test_extern_gcc_consts(): @tvm._ffi.register_func("relay.ext.ccompiler.constant_updater") def constant_updater(expr, symbol): """A dummy constant updater just to test that a custom one works.""" return {"ccompiler_0_p0": tvm.nd.array(y0_data)} x = relay.var("x", shape=(8, 8)) y0_data = np.random.uniform(0, 1, (8, 8)).astype("float32") x0 = relay.var("x0", shape=(8, 8)) y0_const = relay.const(y0_data, "float32") z = x0 + y0_const f = relay.Function([x0], z) f = set_external_func_attr(f, "ccompiler", "ccompiler_0") call = relay.Call(f, [x]) mod = tvm.IRModule.from_expr(call) with tvm.transform.PassContext(opt_level=3, disabled_pass=["AlterOpLayout"]): compiler = relay.backend.vm.VMCompiler() compiler.lower(mod, "llvm") compiler.codegen() params = compiler.get_params() assert len(params) == 1 assert "ccompiler_0_p0" in params.keys() with tvm.transform.PassContext(opt_level=3, disabled_pass=["AlterOpLayout"]): _, _, params = relay.build(mod, target="llvm") assert len(params) == 1 assert "ccompiler_0_p0" in params.keys() tvm._ffi.registry.remove_global_func("relay.ext.ccompiler.constant_updater") def test_extern_dnnl(): if not tvm.get_global_func("relay.ext.dnnl", True): print("skip because DNNL codegen is not available") return dtype = "float32" ishape = (1, 32, 14, 14) w1shape = (32, 1, 3, 3) data0 = relay.var("data0", shape=(ishape), dtype=dtype) weight0 = relay.var("weight0", shape=(w1shape), dtype=dtype) data1 = relay.var("data0", shape=(ishape), dtype=dtype) weight1 = relay.var("weight0", shape=(w1shape), dtype=dtype) weight2 = relay.var("weight1", shape=(w1shape), dtype=dtype) depthwise_conv2d_1 = relay.nn.conv2d( data1, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32 ) depthwise_conv2d_2 = relay.nn.conv2d( depthwise_conv2d_1, weight2, kernel_size=(3, 3), padding=(1, 1), groups=32 ) out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2) f = relay.Function([data1, weight1, weight2], out) ref_mod = tvm.IRModule() ref_mod["main"] = f f = set_external_func_attr(f, "dnnl", "dnnl_0") call = relay.Call(f, [data0, weight0, weight0]) mod = tvm.IRModule.from_expr(call) i_data = np.random.uniform(0, 1, ishape).astype(dtype) w_data = np.random.uniform(0, 1, w1shape).astype(dtype) ref_ex = relay.create_executor("graph", mod=ref_mod, ctx=tvm.cpu()) ref_res = ref_ex.evaluate()(i_data, w_data, w_data) check_result( mod, {"data0": i_data, "weight0": w_data}, (1, 32, 14, 14), ref_res.asnumpy(), tol=1e-5 ) def test_extern_dnnl_const(): if not tvm.get_global_func("relay.ext.dnnl", True): print("skip because DNNL codegen is not available") return dtype = "float32" ishape = (1, 32, 14, 14) w1shape = (32, 1, 3, 3) data0 = relay.var("data0", shape=(ishape), dtype=dtype) w_data = np.random.uniform(0, 1, w1shape).astype(dtype) data1 = relay.var("data0", shape=(ishape), dtype=dtype) weight1 = relay.const(w_data, dtype=dtype) weight2 = relay.const(w_data, dtype=dtype) depthwise_conv2d_1 = relay.nn.conv2d( data1, weight1, kernel_size=(3, 3), padding=(1, 1), groups=32 ) depthwise_conv2d_2 = relay.nn.conv2d( depthwise_conv2d_1, weight2, kernel_size=(3, 3), padding=(1, 1), groups=32 ) out = relay.add(depthwise_conv2d_1, depthwise_conv2d_2) f = relay.Function([data1], out) ref_mod = tvm.IRModule() ref_mod["main"] = f f = set_external_func_attr(f, "dnnl", "dnnl_0") call = relay.Call(f, [data0]) mod = tvm.IRModule.from_expr(call) i_data = np.random.uniform(0, 1, ishape).astype(dtype) ref_ex = relay.create_executor("graph", mod=ref_mod, ctx=tvm.cpu()) ref_res = ref_ex.evaluate()(i_data) check_result(mod, {"data0": i_data}, (1, 32, 14, 14), ref_res.asnumpy(), tol=1e-5) def test_extern_vta(): if not tvm.get_global_func("relay.ext.vta_matmul", True): print('VTA ILA codegen not supported') vta.testing.simulator.dump_mode(True) dtype = 'float32' ishape = (16, 16) wshape = (16, 16) data = relay.var('data', shape=(ishape), dtype=dtype) weight = relay.var('weight', shape=(wshape), dtype=dtype) data_1 = relay.log(data) o1 = relay.multiply(data_1, relay.const(np.random.uniform(1, 1, ishape))) out = relay.nn.dense(o1, weight) # relay.Call(dense_func, [o1]) f = relay.Function([data, weight], out) inputs = relay.var('input', shape=ishape, dtype=dtype) weights = relay.var('w', shape=wshape, dtype=dtype) call = relay.Call(f, [inputs, weights]) mod = tvm.IRModule() mod['main'] = f mod = relay.transform.InferType()(mod) mod = tvm.IRModule.from_expr(call) seq = tvm.transform.Sequential([transform.AnnotateTarget('vta_matmul'), transform.PartitionGraph()]) mod = seq(mod) in_data = np.array([math.e] * ishape[0] * ishape[1]).reshape(ishape).astype(dtype) w_data = (np.arange(wshape[0] * wshape[1]) % 10).reshape(wshape).astype(dtype) check_result(mod, { 'input' : in_data, 'w': w_data }, (16, 16), np.matmul(np.array([1] * 16 * 16).reshape(ishape).astype(dtype), np.transpose(w_data)).astype(dtype), use_graph_rt=False) if __name__ == "__main__": test_multi_node_subgraph() test_extern_gcc_single_op() test_extern_gcc_single_op_int() test_extern_gcc() test_extern_gcc_consts() test_extern_dnnl() test_extern_dnnl_const() test_extern_vta()
<gh_stars>0 import re class WordIterator: """ A basic wrapper for sequential reading of words from file """ def __init__(self, filename): self.filename = filename self.word_queue = [] self.line_payload = 50 # how many lines will be loaded into the queue at one time self.__lines_count = sum(1 for line in open(filename)) self.__load_line = 1 # index of first line which haven't been already loaded into the queue self.__separators = [] def read(self): """ Returns first word from file that wasn't already read by this particular object. Return value format: (word, separator) When all words had been read, it returns None """ if len(self.word_queue) == 0: self.__load_payload() if len(self.word_queue) == 0: return None else: return self.word_queue.pop(0) def push_back(self, word): """ Pushes word from argument into the first position of the queue In case we already read a word but we want to re-read it again """ self.word_queue = [word] + self.word_queue def add_separator(self, sep): """ All words will be separated with sep separator """ if sep in self.__separators: return self.__separators.append(sep) new_queue = [] regex_arg = re.compile('(' + sep + ')') for word, sep in self.word_queue: new_word = re.sub(regex_arg, r' \1 ', word) new_words = new_word.split(' ') new_queue += self.__make_pairs(word + sep, new_words) self.word_queue = new_queue def __load_payload(self): """ Loads words from input file into the queue Format of words: (word, separator) """ index = 0 with open(self.filename, 'r') as file: for line in file: index += 1 if index < self.__load_line: continue elif index < self.__load_line + self.line_payload: self.word_queue += self.__parse_words(line) if index >= self.__lines_count: index += 1 else: break self.__load_line = index def __parse_words(self, line): """ Parses a line passed by argument using regular expressions. It separates each word on the line and stores it into list. returns list of tuples (word, separator between word and next word) """ orig_line = line if line == "\n" or line == "\r\n": return self.__make_pairs(orig_line, [line]) # All non escape occurrences of some characters are seperated to be a single 'word' line = re.sub(r'(?<!\\)(?:\\\\)*([{}\[\]()%])', r' \1 ', line) # $$ and $ are separated from the text to be a single 'word' line = re.sub(r'(?<!\\)(?:\\\\)*((\$\$)|(\$))', r' \1 ', line) # All escaped alphabetic characters are separated from the previous word line = re.sub(r'(?<!\\)(\\\\)*(\\)([A-Za-z])', r'\1 \2\3', line) # Non escaped character ~ is replaced with space line = re.sub(r'(?<!\\)(?:\\\\)*(~)', r' \1 ', line) # Iterate through every separator and put spaces around them for sep in self.__separators: line = re.sub('(' + sep + ')', r' \1 ', line) words_on_line = re.split(r'\s+', line) # At the end of every nonempty line newline character is placed words_on_line.append("\n") return self.__make_pairs(orig_line, words_on_line) @staticmethod def __make_pairs(orig_line, words): """ Generates list of tuples (word, separator between the word and the next word in list) """ pairs = [] read_index = 0 for i in range(len(words)): if i + 1 >= len(words): start = orig_line[read_index:].find(words[i]) + len(words[i]) + read_index pairs.append((words[i], orig_line[start:])) else: start = orig_line[read_index:].find(words[i]) + len(words[i]) + read_index end = orig_line[start:].find(words[i+1]) + start pairs.append((words[i], orig_line[start: end])) read_index = end return pairs
#!/usr/bin/python # ------------------------------------------------------------------------------ # # Automatic generation of a completion function for stoke for zsh. # Running this file will produce bin/_stoke, which can be used by zsh. If the # env variable ZSH_COMPLETION_DIR points to a directory, then _stoke is also # copied to that directory. # # The completion function code (not the generation script) is loosely based on # https://github.com/zsh-users/zsh-completions/blob/master/src/_git-flow # # Author: <NAME> <<EMAIL>> # # ------------------------------------------------------------------------------ import sys import re import subprocess import os import shutil # ------------------------------------------ # main entry point # ------------------------------------------ def main(): # build an AST with all the commands / arguments cmd = get_command() # show AST #print cmd handlers = [BashHandler(),ZshHandler()] # let each handler output it's file for handler in handlers: handler.handle(cmd) handler.finish() return # ------------------------------------------ # handler class # ------------------------------------------ # abstract handler that writes a completion script to a file # all actual handling of writing out the script is left abstract class Handler(object): def __init__(self, filename): self.filename = filename self.full_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", ".." , "bin", filename) self.file = open(self.full_filename, 'w') def handle(self, command): pass # to be implemented def writeln(self, line): print >>self.file, line def finish(self): self.file.close() # ------------------------------------------ # a handler for bash completion # ------------------------------------------ class BashHandler(Handler): def __init__(self): super(BashHandler, self).__init__("stoke.bash") def handle(self, command): self.writeln("# Bash completion script (auto-generated; do not modify!)") self.writeln("") self.writeln("_stoke()") self.writeln("{") self.writeln(" local prev=${COMP_WORDS[COMP_CWORD-1]}") self.writeln(" local cur=${COMP_WORDS[COMP_CWORD]}") self.writeln(" COMPREPLY=( $(compgen -A file -- $cur) )") def aux(command, depth): self.write_cmd(command, depth) for sub in command.subcommands: aux(sub, depth+1) aux(command, 1) self.writeln("}") self.writeln("") self.writeln("complete -F _stoke stoke") def write_cmd(self, command, depth): comps = [] if command.has_subcommands(): for sub in command.subcommands: comps.append(sub.name) self.writeln(" if [ \"$COMP_CWORD\" -eq " + str(depth) + " -a \"$prev\" == " + command.name + " ]; then") self.writeln(" COMPREPLY=( $(compgen -W \"" + " ".join(comps) + "\" -- $cur) )") self.writeln(" fi") else: for arg in command.arguments: for param in arg.params: comps.append(param) self.writeln(" if [ \"$COMP_CWORD\" -ge " + str(depth) + " -a \"${COMP_WORDS[" + str(depth-1) + "]}\" == " + command.name + " ]; then") self.writeln(" FILES=`ls ./*`") self.writeln(" COMPREPLY=( $(compgen -W \"$DIR " + " ".join(comps) + "\" -- $cur) )") self.writeln(" fi") def finish(self): super(BashHandler, self).finish() # ------------------------------------------ # a handler for zsh completion # ------------------------------------------ class ZshHandler(Handler): def __init__(self): super(ZshHandler, self).__init__("_stoke") def handle(self, command): def aux(command): if command.has_subcommands(): self.write_cmd(command) for sub in command.subcommands: aux(sub) else: self.write_arguments(command.full_name(), command.arguments) self.write_header() aux(command) def write_cmd(self, command): assert len(command.arguments) == 0 assert len(command.subcommands) > 0 subhelp = [] subrun = [] for sub in command.subcommands: subhelp.append("'" + sub.name + "':'" + sub.help + "'") r = "(" + sub.name + ")" r += "\n " + "_" + sub.full_name().replace(" ", "_") r += "\n ;;" subrun.append(r) self.writeln("_" + command.full_name().replace(" ", "_") + """ () { local curcontext="$curcontext" state line typeset -A opt_args _arguments -C \\ ':command:->command' \\ '*::options:->options' case $state in (command) local -a subcommands subcommands=( """ + "\n ".join(subhelp) + """ ) _describe -t commands '""" + command.full_name() + """' subcommands ;; (options) case $line[1] in """ + "\n\n ".join(subrun) + """ esac ;; esac }""") def write_arguments(self, name, args): def esc(s): s = s.replace("{", "\\{").replace("}", "\\}").replace("'", "") s = s.replace("[", "\\[").replace("]", "\\]") return s self.writeln("_" + name.replace(" ", "_") + "()\n{") res = [] for arg in args: if len(arg.get_parameters()) > 1: a = "{'" + "','".join(arg.get_parameters()) + "'}'" else: a = "'" + arg.get_parameters()[0] usage = arg.get_usage() # no argument, just a flag if usage == None: res.append(a + "[" + esc(arg.desc) + "]::'") continue # number argument m = re.search('<(int|double|percent|line|value|bytes)>$', usage) if m != None: res.append(a + "[" + esc(arg.desc + "; <"+m.group(1)+">") + "]:num:'") continue # file argument m = re.search('<(path/to/(file|bin)\.?(.*))>$', usage) if m != None: if len(m.group(3)) > 0: res.append(a + "[" + esc(arg.desc + "; <"+m.group(2)+">")+"]:file:_files -g \"*."+esc(m.group(3))+"\"'") else: res.append(a + "[" + esc(arg.desc + "; <"+m.group(2)+">")+"]:file:_files'") continue # dir argument m = re.search('<(path/to/dir|dir)>$', usage) if m != None: res.append(a + "[" + esc(arg.desc + "; <path/to/dir>")+"]:dir:_files -/'") continue # list of options m = re.search('\((.*)\)$', usage) if m != None: options = m.group(1).split("|") res.append(a + "[" + esc(arg.desc) + "]:argument:(" + " ".join(map(lambda x: esc(x), options)) + ")'") continue # arguments without completion m = re.search('({.*}|<move_type>|<move>|<arg1 arg2 ... argn>|<string>)$', usage) if m != None: options = m.group(1).split("|") res.append(a + "[" + esc(arg.desc + "; "+m.group(1))+"]:argument:'") continue # no match, just add default help print "ERROR: Argument with unknown usage found: " + usage sys.exit(1) #res.append(a + "[" + esc(arg.desc) + "]:argument:'") self.writeln(" _arguments \\") self.writeln(" " + " \\\n ".join(res)) self.writeln("}\n") def write_header(self): self.writeln("""#compdef stoke # ------------------------------------------------------------------------------ # # Completion script for stoke. # # NOTE: Automatically generated, do not modify! # # Author: <NAME> <<EMAIL>> # # ------------------------------------------------------------------------------ """) def finish(self): super(ZshHandler, self).finish() # if ZSH_COMPLETION_DIR is set, copy file there if os.environ.has_key('ZSH_COMPLETION_DIR'): d = os.environ.get('ZSH_COMPLETION_DIR') if os.path.isdir(d): shutil.copy2(self.full_filename, os.path.join(d, self.filename)) # ------------------------------------------ # AST classes # ------------------------------------------ # one argument to a given command class Arg(object): def __init__(self, arg, desc=""): self.name = arg self.desc = desc # finish initialization (no more calls to add_desc after this) def finish_init(self): match = re.match("(-[^ ]*)( (-[^ ]*))?( (.+?))?( \(default: (.*)\))?$", self.name) if match == None: print "Error parsing argument: " + self.name sys.exit(1) self.params = [match.group(1)] if match.group(3) != None: self.params.append(match.group(3)) self.usage = match.group(5) self.default = match.group(7) filters = [ "Required argument", "Default: use --debug_args to see this default" ] match = re.search("Default: (.+)$", self.desc) if match != None: filters.append(match.group(0)) self.default = match.group(1) for f in filters: if f in self.desc: self.desc = self.desc.replace(f, "").strip() # extend the description as necessary def add_desc(self, desc): self.desc += " " + desc.strip() self.desc = self.desc.strip() # get the list of parameter names (one or two) def get_parameters(self): return self.params # return the usage part of the parameter def get_usage(self): return self.usage def has_default(self): return self.default != None def get_default(self): return self.default # simple string representation def __repr__(self): return self.name # a stoke command (which has either a list of subcommands, or a list of arguments) class Command(object): def __init__(self, parent, name, help, subcommands, arguments): self.parent = parent self.name = name.strip() self.subcommands = subcommands self.help = help.strip() self.arguments = arguments def has_subcommands(self): return len(self.subcommands) > 0 def full_name(self): if self.parent == None: return self.name return self.parent.full_name() + " " + self.name def __repr__(self): def indent(s): return " " + s.replace("\n", "\n ") s = self.name + " - " + self.help + "\n" for sub in self.subcommands: s += indent(str(sub)) + "\n" for arg in self.arguments: s += indent(str(arg)) + "\n" return s # ------------------------------------------ # parsing --help output into an AST # ------------------------------------------ base_path = os.path.dirname(os.path.realpath(__file__)) def run(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = "" for line in p.stdout.readlines(): out += line return out def get_command(): output = run(base_path + "/../../bin/stoke --help | grep \"^ \"") subcommands = [] cmd = Command(None, "stoke", "", subcommands, []) subsubmap = {} for line in output.split("\n"): if len(line) > 0: match = re.search(r"^ (.*[^ ]) +([^ ].*)$", line) help = match.group(2) full = match.group(1) parts = full.split(" ") if (len(parts) == 1): args = get_arguments(full) sub = Command(cmd, full, help, [], args) subcommands.append(sub) else: assert len(parts) == 2 if not parts[0] in subsubmap: subsubmap[parts[0]] = [] subsubmap[parts[0]].append({ 'name': parts[1], 'help': help }) for sub, subsubs in subsubmap.iteritems(): subsubcommands = [] subcmd = Command(cmd, sub, sub + " commands", subsubcommands, []) subcommands.append(subcmd) for subsub in subsubs: args = get_arguments(sub + " " + subsub['name']) subsubcommands.append(Command(subcmd, subsub['name'], subsub['help'], [], args)) return cmd def get_arguments(subcommand): data = run(base_path + "/../../bin/stoke " + subcommand + " --help | grep \"^ \(-\| \)\"") args = [] for line in data.split("\n"): if line.startswith(" "): arg.add_desc(line[4:]) elif len(line) > 3: arg = Arg(line.strip()) args.append(arg) for a in args: a.finish_init() return args if __name__ == '__main__': main()
"""Implementation of the pycross_wheel_library rule.""" load(":providers.bzl", "PycrossWheelInfo") load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_python//python:defs.bzl", "PyInfo") def _pycross_wheel_library_impl(ctx): out = ctx.actions.declare_directory(ctx.attr.name) wheel_target = ctx.attr.wheel if PycrossWheelInfo in wheel_target: wheel_file = wheel_target[PycrossWheelInfo].wheel_file name_file = wheel_target[PycrossWheelInfo].name_file else: wheel_file = ctx.file.wheel name_file = None args = [ "--wheel", wheel_file.path, "--directory", out.path, ] inputs = [wheel_file] if name_file: inputs.append(name_file) args.extend([ "--wheel-name-file", name_file.path, ]) if ctx.attr.enable_implicit_namespace_pkgs: args.append("--enable-implicit-namespace-pkgs") ctx.actions.run( inputs = inputs, outputs = [out], executable = ctx.executable._tool, arguments = args, # Set environment variables to make generated .pyc files reproducible. env = { "SOURCE_DATE_EPOCH": "315532800", "PYTHONHASHSEED": "0", }, mnemonic = "WheelInstall", progress_message = "Installing %s" % ctx.file.wheel.basename, ) has_py2_only_sources = ctx.attr.python_version == "PY2" has_py3_only_sources = ctx.attr.python_version == "PY3" if not has_py2_only_sources: for d in ctx.attr.deps: if d[PyInfo].has_py2_only_sources: has_py2_only_sources = True break if not has_py3_only_sources: for d in ctx.attr.deps: if d[PyInfo].has_py3_only_sources: has_py3_only_sources = True break # TODO: Is there a more correct way to get this runfiles-relative import path? imp = paths.join( ctx.label.workspace_name or ctx.workspace_name, # Default to the local workspace. ctx.label.package, ctx.label.name, "lib", # we put lib files in this subdirectory. ) imports = depset( direct = [imp], transitive = [d[PyInfo].imports for d in ctx.attr.deps], ) transitive_sources = depset( direct = [out], transitive = [d[PyInfo].transitive_sources for d in ctx.attr.deps], ) runfiles = ctx.runfiles(files = [out]) for d in ctx.attr.deps: runfiles = runfiles.merge(d[DefaultInfo].default_runfiles) return [ DefaultInfo( files = depset(direct = [out]), runfiles = runfiles, ), PyInfo( has_py2_only_sources = has_py2_only_sources, has_py3_only_sources = has_py3_only_sources, imports = imports, transitive_sources = transitive_sources, ), ] pycross_wheel_library = rule( implementation = _pycross_wheel_library_impl, attrs = { "deps": attr.label_list( doc = "A list of this wheel's Python library dependencies.", providers = [DefaultInfo, PyInfo], ), "wheel": attr.label( doc = "The wheel file.", allow_single_file = [".whl"], mandatory = True, ), "enable_implicit_namespace_pkgs": attr.bool( default = True, doc = """ If true, disables conversion of native namespace packages into pkg-util style namespace packages. When set all py_binary and py_test targets must specify either `legacy_create_init=False` or the global Bazel option `--incompatible_default_to_explicit_init_py` to prevent `__init__.py` being automatically generated in every directory. This option is required to support some packages which cannot handle the conversion to pkg-util style. """, ), "python_version": attr.string( doc = "The python version required for this wheel ('PY2' or 'PY3')", values = ["PY2", "PY3", ""] ), "_tool": attr.label( default = Label("//pycross/private/tools:wheel_installer"), cfg = "host", executable = True, ), } )
<gh_stars>0 """ Tensorflow SMPL implementation as batch. Specify joint types: 'coco': Returns COCO+ 19 joints 'lsp': Returns H3.6M-LSP 14 joints Note: To get original smpl joints, use self.J_transformed """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pickle as pickle import tensorflow as tf from .batch_lbs import batch_rodrigues, batch_global_rigid_transformation # There are chumpy variables so convert them to numpy. def undo_chumpy(x): return x if isinstance(x, np.ndarray) else x.r class SMPL(object): def __init__(self, pkl_path, joint_type='cocoplus', dtype=tf.float32): """ pkl_path is the path to a SMPL model """ # -- Load SMPL params -- with open(pkl_path, 'rb') as f: dd = pickle.load(f) #dd = pickle.load(f, encoding="latin-1") # Mean template vertices self.v_template = tf.Variable( undo_chumpy(dd['v_template']), name='v_template', dtype=dtype, trainable=False) # Size of mesh [Number of vertices, 3] self.size = [self.v_template.shape[0].value, 3] self.num_betas = dd['shapedirs'].shape[-1] # Shape blend shape basis: 6980 x 3 x 10 # reshaped to 6980*30 x 10, transposed to 10x6980*3 shapedir = np.reshape( undo_chumpy(dd['shapedirs']), [-1, self.num_betas]).T self.shapedirs = tf.Variable( shapedir, name='shapedirs', dtype=dtype, trainable=False) # Regressor for joint locations given shape - 6890 x 24 self.J_regressor = tf.Variable( dd['J_regressor'].T.todense(), name="J_regressor", dtype=dtype, trainable=False) # Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*30 x 207 num_pose_basis = dd['posedirs'].shape[-1] # 207 x 20670 posedirs = np.reshape( undo_chumpy(dd['posedirs']), [-1, num_pose_basis]).T self.posedirs = tf.Variable( posedirs, name='posedirs', dtype=dtype, trainable=False) # indices of parents for each joints self.parents = dd['kintree_table'][0].astype(np.int32) # LBS weights self.weights = tf.Variable( undo_chumpy(dd['weights']), name='lbs_weights', dtype=dtype, trainable=False) # This returns 19 keypoints: 6890 x 19 self.joint_regressor = tf.Variable( dd['cocoplus_regressor'].T.todense(), name="cocoplus_regressor", dtype=dtype, trainable=False) if joint_type == 'lsp': # 14 LSP joints! self.joint_regressor = self.joint_regressor[:, :14] if joint_type not in ['cocoplus', 'lsp']: print('BAD!! Unknown joint type: %s, it must be either "cocoplus" or "lsp"' % joint_type) import ipdb ipdb.set_trace() def __call__(self, beta, theta, get_skin=False, name=None): """ Obtain SMPL with shape (beta) & pose (theta) inputs. Theta includes the global rotation. Args: beta: N x 10 theta: N x 72 (with 3-D axis-angle rep) Updates: self.J_transformed: N x 24 x 3 joint location after shaping & posing with beta and theta Returns: - joints: N x 19 or 14 x 3 joint locations depending on joint_type If get_skin is True, also returns - Verts: N x 6980 x 3 """ with tf.name_scope(name, "smpl_main", [beta, theta]): num_batch = beta.shape[0].value # 1. Add shape blend shapes # (N x 10) x (10 x 6890*3) = N x 6890 x 3 v_shaped = tf.reshape( tf.matmul(beta, self.shapedirs, name='shape_bs'), [-1, self.size[0], self.size[1]]) + self.v_template # 2. Infer shape-dependent joint locations. Jx = tf.matmul(v_shaped[:, :, 0], self.J_regressor) Jy = tf.matmul(v_shaped[:, :, 1], self.J_regressor) Jz = tf.matmul(v_shaped[:, :, 2], self.J_regressor) J = tf.stack([Jx, Jy, Jz], axis=2) # 3. Add pose blend shapes # N x 24 x 3 x 3 Rs = tf.reshape( batch_rodrigues(tf.reshape(theta, [-1, 3])), [-1, 24, 3, 3]) with tf.name_scope("lrotmin"): # Ignore global rotation. pose_feature = tf.reshape(Rs[:, 1:, :, :] - tf.eye(3), [-1, 207]) # (N x 207) x (207, 20670) -> N x 6890 x 3 v_posed = tf.reshape( tf.matmul(pose_feature, self.posedirs), [-1, self.size[0], self.size[1]]) + v_shaped #4. Get the global joint location self.J_transformed, A = batch_global_rigid_transformation(Rs, J, self.parents) # 5. Do skinning: # W is N x 6890 x 24 W = tf.reshape( tf.tile(self.weights, [num_batch, 1]), [num_batch, -1, 24]) # (N x 6890 x 24) x (N x 24 x 16) T = tf.reshape( tf.matmul(W, tf.reshape(A, [num_batch, 24, 16])), [num_batch, -1, 4, 4]) v_posed_homo = tf.concat( [v_posed, tf.ones([num_batch, v_posed.shape[1], 1])], 2) v_homo = tf.matmul(T, tf.expand_dims(v_posed_homo, -1)) verts = v_homo[:, :, :3, 0] # Get cocoplus or lsp joints: joint_x = tf.matmul(verts[:, :, 0], self.joint_regressor) joint_y = tf.matmul(verts[:, :, 1], self.joint_regressor) joint_z = tf.matmul(verts[:, :, 2], self.joint_regressor) joints = tf.stack([joint_x, joint_y, joint_z], axis=2) if get_skin: return verts, joints, Rs else: return joints
from __future__ import unicode_literals from click.testing import CliRunner import os.path from pytest import raises from textx import metamodel_from_str from textx.cli import textx from textx.exceptions import TextXError from textx.generators import gen_file, get_output_filename from textx import language, generator, register_language, register_generator grammar = r""" Model: 'MyModel' name=ID; """ text = r""" MyModel test1 """ def test_model_params(): mm = metamodel_from_str(grammar) mm.model_param_defs.add( "parameter1", "an example param (1)" ) mm.model_param_defs.add( "parameter2", "an example param (2)" ) m = mm.model_from_str(text, parameter1='P1', parameter2='P2') assert m.name == 'test1' assert hasattr(m, '_tx_model_params') assert len(m._tx_model_params) == 2 assert len(m._tx_model_params.used_keys) == 0 assert not m._tx_model_params.all_used assert m._tx_model_params['parameter1'] == 'P1' assert len(m._tx_model_params.used_keys) == 1 assert 'parameter1' in m._tx_model_params.used_keys assert 'parameter2' not in m._tx_model_params.used_keys assert not m._tx_model_params.all_used assert m._tx_model_params['parameter2'] == 'P2' assert len(m._tx_model_params.used_keys) == 2 assert 'parameter1' in m._tx_model_params.used_keys assert 'parameter2' in m._tx_model_params.used_keys assert m._tx_model_params.all_used assert m._tx_model_params.get( 'missing_params', default='default value') == 'default value' assert m._tx_model_params.get( 'parameter1', default='default value') == 'P1' with raises(TextXError, match=".*unknown parameter myerror2.*"): mm.model_from_str(text, parameter1='P1', myerror2='P2') assert len(mm.model_param_defs) >= 2 assert 'parameter1' in mm.model_param_defs assert 'parameter1' in mm.model_param_defs assert mm.model_param_defs[ 'parameter1'].description == "an example param (1)" def test_model_params_empty(): mm = metamodel_from_str(grammar) mm.model_param_defs.add( "parameter1", "an example param (1)" ) mm.model_param_defs.add( "parameter2", "an example param (2)" ) m = mm.model_from_str(text) assert m.name == 'test1' assert hasattr(m, '_tx_model_params') assert len(m._tx_model_params) == 0 assert m._tx_model_params.all_used def test_model_params_file_based(): mm = metamodel_from_str(grammar) mm.model_param_defs.add( "parameter1", "an example param (1)" ) mm.model_param_defs.add( "parameter2", "an example param (2)" ) current_dir = os.path.dirname(__file__) m = mm.model_from_file( os.path.join(current_dir, 'test_model_params', 'model.txt'), parameter1='P1', parameter2='P2') assert m.name == 'file_based' assert hasattr(m, '_tx_model_params') assert len(m._tx_model_params) == 2 def test_model_params_generate_cli(): """ Test that model parameters are passed through generate cli command. """ # register test language @language('testlang', '*.mpt') def model_param_test(): def processor(model, metamodel): # Just to be sure that processor sees the model parameters model.model_params = model._tx_model_params mm = metamodel_from_str(grammar) mm.model_param_defs.add('meaning_of_life', 'The Meaning of Life') mm.register_model_processor(processor) return mm register_language(model_param_test) # register language generator @generator('testlang', 'testtarget') def mytarget_generator(metamodel, model, output_path, overwrite, debug=False, **custom_args): # Dump custom args for testing txt = '\n'.join(["{}={}".format(arg_name, arg_value) for arg_name, arg_value in custom_args.items()]) # Dump model params processed by model processor for testing txt += '\nModel params:' txt += '\n'.join(["{}={}".format(param_name, param_value) for param_name, param_value in model.model_params.items()]) output_file = get_output_filename(model._tx_filename, None, 'testtarget') def gen_callback(): with open(output_file, 'w') as f: f.write(txt) gen_file(model._tx_filename, output_file, gen_callback, overwrite) register_generator(mytarget_generator) # Run generator from CLI this_folder = os.path.abspath(os.path.dirname(__file__)) runner = CliRunner() model_file = os.path.join(this_folder, 'model_param_generate_test.mpt') result = runner.invoke(textx, ['generate', '--language', 'testlang', '--target', 'testtarget', '--overwrite', model_file, '--meaning_of_life', '42', '--someparam', 'somevalue']) assert result.exit_code == 0 output_file = os.path.join(this_folder, 'model_param_generate_test.testtarget') with open(output_file, 'r') as f: content = f.read() assert 'someparam=somevalue' in content assert 'Model params:meaning_of_life=42' in content
<filename>pysal/esda/tests/test_gamma.py import unittest import numpy as np from ...weights import lat2W from ..gamma import Gamma from ...common import pandas PANDAS_EXTINCT = pandas is None class Gamma_Tester(unittest.TestCase): """Unit test for Gamma Index""" def setUp(self): self.w = lat2W(4, 4) self.y = np.ones(16) self.y[0:8] = 0 np.random.seed(12345) self.g = Gamma(self.y, self.w) def test_Gamma(self): """Test method""" g = self.g self.assertAlmostEquals(g.g, 20.0) self.assertAlmostEquals(g.g_z, 3.1879280354548638) self.assertAlmostEquals(g.p_sim_g, 0.0030000000000000001) self.assertAlmostEquals(g.min_g, 0.0) self.assertAlmostEquals(g.max_g, 20.0) self.assertAlmostEquals(g.mean_g, 11.093093093093094) np.random.seed(12345) g1 = Gamma(self.y, self.w, operation='s') self.assertAlmostEquals(g1.g, 8.0) self.assertAlmostEquals(g1.g_z, -3.7057554345954791) self.assertAlmostEquals(g1.p_sim_g, 0.001) self.assertAlmostEquals(g1.min_g, 14.0) self.assertAlmostEquals(g1.max_g, 48.0) self.assertAlmostEquals(g1.mean_g, 25.623623623623622) np.random.seed(12345) g2 = Gamma(self.y, self.w, operation='a') self.assertAlmostEquals(g2.g, 8.0) self.assertAlmostEquals(g2.g_z, -3.7057554345954791) self.assertAlmostEquals(g2.p_sim_g, 0.001) self.assertAlmostEquals(g2.min_g, 14.0) self.assertAlmostEquals(g2.max_g, 48.0) self.assertAlmostEquals(g2.mean_g, 25.623623623623622) np.random.seed(12345) g3 = Gamma(self.y, self.w, standardize='y') self.assertAlmostEquals(g3.g, 32.0) self.assertAlmostEquals(g3.g_z, 3.7057554345954791) self.assertAlmostEquals(g3.p_sim_g, 0.001) self.assertAlmostEquals(g3.min_g, -48.0) self.assertAlmostEquals(g3.max_g, 20.0) self.assertAlmostEquals(g3.mean_g, -3.2472472472472473) np.random.seed(12345) def func(z, i, j): q = z[i] * z[j] return q g4 = Gamma(self.y, self.w, operation=func) self.assertAlmostEquals(g4.g, 20.0) self.assertAlmostEquals(g4.g_z, 3.1879280354548638) self.assertAlmostEquals(g4.p_sim_g, 0.0030000000000000001) @unittest.skipIf(PANDAS_EXTINCT, 'missing pandas') def test_by_col(self): import pandas as pd df = pd.DataFrame(self.y, columns=['y']) r1 = Gamma.by_col(df, ['y'], w=self.w) self.assertIn('y_gamma', r1.columns) self.assertIn('y_p_sim', r1.columns) this_gamma = np.unique(r1.y_gamma.values) this_pval = np.unique(r1.y_p_sim.values) np.testing.assert_allclose(this_gamma, self.g.g) np.testing.assert_allclose(this_pval, self.g.p_sim) Gamma.by_col(df, ['y'], inplace=True, operation='s', w=self.w) this_gamma = np.unique(df.y_gamma.values) this_pval = np.unique(df.y_p_sim.values) np.testing.assert_allclose(this_gamma, 8.0) np.testing.assert_allclose(this_pval, .001) suite = unittest.TestSuite() test_classes = [Gamma_Tester] for i in test_classes: a = unittest.TestLoader().loadTestsFromTestCase(i) suite.addTest(a) if __name__ == '__main__': runner = unittest.TextTestRunner() runner.run(suite)
<gh_stars>1000+ #!/usr/bin/env python # # check_sizes.py is a tool run by the ESP-IDF build system # to check a particular binary fits in the available partitions of # a particular type/subtype. Can be used to check if the app binary fits in # all available app partitions, for example. # # (Can also check if the bootloader binary fits before the partition table.) # # Copyright 2020 Espressif Systems (Shanghai) PTE LTD # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import division, print_function, unicode_literals import argparse import io # noqa: F401 # pylint: disable=unused-import import os import sys try: from typing import IO # noqa: F401 # pylint: disable=unused-import except ImportError: pass # used for type hinting only import gen_esp32part from gen_esp32part import PartitionTable, get_ptype_as_int, get_subtype_as_int allow_failures = False def _file_size(f): # type: (IO) -> int before = f.tell() f.seek(0, 2) # seek to end result = f.tell() f.seek(before) return result def _fail(msg): # type: (str) -> None if allow_failures: print('Warning: {}'.format(msg)) else: raise SystemExit('Error: {}'.format(msg)) def check_bootloader(partition_table_offset, bootloader_offset, binary_file): # type: (int, int, IO) -> None max_size = partition_table_offset - bootloader_offset bootloader_size = _file_size(binary_file) if bootloader_size > max_size: msg = ('Bootloader binary size {:#x} bytes is too large for partition table offset {:#02x}. ' + 'Bootloader binary can be maximum {:#x} ({}) bytes unless the partition table offset ' + 'is increased in the Partition Table section of the project configuration menu.').format( bootloader_size, partition_table_offset, max_size, max_size) _fail(msg) free_size = max_size - bootloader_size print('Bootloader binary size {:#x} bytes. {:#x} bytes ({}%) free.'.format( bootloader_size, free_size, round(free_size * 100 / max_size))) def check_partition(ptype, subtype, partition_table_file, bin_file): # type: (str, str, io.IOBase, IO) -> None table, _ = PartitionTable.from_file(partition_table_file) ptype_str = str(ptype) ptype = get_ptype_as_int(ptype) partitions = [p for p in table if p.type == ptype] if subtype is not None: ptype_str += ' ({})'.format(subtype) subtype = get_subtype_as_int(ptype, subtype) partitions = [p for p in partitions if p.subtype == subtype] if len(partitions) == 0: print('WARNING: Partition table does not contain any partitions matching {}'.format(ptype_str)) return bin_name = os.path.basename(bin_file.name) bin_size = _file_size(bin_file) smallest_size = min(p.size for p in partitions) if smallest_size >= bin_size: free_size = smallest_size - bin_size print('{} binary size {:#x} bytes. Smallest {} partition is {:#x} bytes. {:#x} bytes ({}%) free.'.format( bin_name, bin_size, ptype_str, smallest_size, free_size, round(free_size * 100 / smallest_size))) return too_small_partitions = [p for p in partitions if p.size < bin_size] if len(partitions) == 1: msg = '{} partition is'.format(ptype_str) elif len(partitions) == len(too_small_partitions): msg = 'All {} partitions are'.format(ptype_str) else: msg = '{}/{} {} partitions are'.format(len(too_small_partitions), len(partitions), ptype_str) msg += ' too small for binary {} size {:#x}:'.format(bin_name, bin_size) for p in too_small_partitions: msg += '\n - {} (overflow {:#x})'.format(p, bin_size - p.size) if not allow_failures and len(partitions) == len(too_small_partitions): # if some partitions can fit the binary then just print a warning raise SystemExit('Error: ' + msg) else: print('Warning: ' + msg) def main(): # type: () -> None global allow_failures # pylint: disable=global-statement parser = argparse.ArgumentParser(description='Check binary sizes against partition table entries') parser.add_argument('--target', choices=['esp32', 'esp32s2']) parser.add_argument('--allow_failures', action='store_true', help='If true, failures will print warnings but not exit with an error') parser.add_argument('--offset', '-o', help='Set partition table offset', default='0x8000') subparsers = parser.add_subparsers(dest='check_target', help='Type of binary to check against partition table layout') sp_bootloader = subparsers.add_parser('bootloader') sp_bootloader.add_argument('bootloader_offset', help='Hex offset of bootloader in flash') sp_bootloader.add_argument('bootloader_binary', type=argparse.FileType('rb'), help='Bootloader binary (.bin) file from build output') sp_part = subparsers.add_parser('partition') sp_part.add_argument('--type', type=str, help='Check the file size against all partitions of this type.', required=True) sp_part.add_argument('--subtype', type=str, help='Optional, only check the file size against all partitions of this subtype.') sp_part.add_argument('partition_table', type=argparse.FileType('rb'), help='Partition table file') sp_part.add_argument('binary', type=argparse.FileType('rb'), help='Binary file which will have the size checked') args = parser.parse_args() gen_esp32part.quiet = True args.offset = int(args.offset, 0) gen_esp32part.offset_part_table = args.offset if args.check_target is None: # add_subparsers only has a 'required' argument since Python 3 parser.print_help() sys.exit(1) if args.check_target == 'bootloader': check_bootloader(args.offset, int(args.bootloader_offset, 0), args.bootloader_binary) else: check_partition(args.type, args.subtype, args.partition_table, args.binary) if __name__ == '__main__': main()
from AC3utils import PLUGIN_BASE, PLUGIN_VERSION from Components.ActionMap import NumberActionMap from Components.Button import Button from Components.ConfigList import ConfigListScreen from Components.Label import Label from Components.config import config, getConfigListEntry from Screens.Screen import Screen class AC3LipSyncSetup(ConfigListScreen, Screen): skin = """ <screen position="center,center" size="560,400" title="AC3 Lip Sync Setup"> <ePixmap pixmap="~/img/button-red.png" position="0,0" zPosition="0" size="140,40" transparent="1" alphatest="on" /> <ePixmap pixmap="~/img/button-green.png" position="140,0" zPosition="0" size="140,40" transparent="1" alphatest="on" /> <ePixmap pixmap="~/img/button-yellow.png" position="280,0" zPosition="0" size="140,40" transparent="1" alphatest="on" /> <ePixmap pixmap="~/img/button-blue.png" position="420,0" zPosition="0" size="140,40" transparent="1" alphatest="on" /> <widget name="key_red" position="0,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#9f1313" transparent="1" shadowColor="#000000" shadowOffset="-1,-1" /> <widget name="key_green" position="140,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#1f771f" transparent="1" shadowColor="#000000" shadowOffset="-1,-1" /> <widget name="key_yellow" position="280,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#a08500" transparent="1" shadowColor="#000000" shadowOffset="-1,-1" /> <widget name="key_blue" position="420,0" zPosition="1" size="140,40" font="Regular;20" valign="center" halign="center" backgroundColor="#18188b" transparent="1" shadowColor="#000000" shadowOffset="-1,-1" /> <widget name="config" position="10,40" size="540,320" scrollbarMode="showOnDemand" /> <widget name="PluginInfo" position="10,370" size="540,20" zPosition="4" font="Regular;18" foregroundColor="#cccccc" /> </screen>""" def __init__(self, session, plugin_path): Screen.__init__(self, session) # Lets get a list of elements for the config list self.list = [ getConfigListEntry(_("Outer Bound (+/-)"), config.plugins.AC3LipSync.outerBounds), getConfigListEntry(_("Step in ms for arrow keys"), config.plugins.AC3LipSync.arrowStepSize), getConfigListEntry(_("Wait time in ms before activation:"), config.plugins.AC3LipSync.activationDelay), getConfigListEntry(_("Step in ms for keys '%s'") % ("1/3"), config.plugins.AC3LipSync.stepSize13), getConfigListEntry(_("Step in ms for keys '%s'") % ("4/6"), config.plugins.AC3LipSync.stepSize46), getConfigListEntry(_("Step in ms for keys '%s'") % ("7/9"), config.plugins.AC3LipSync.stepSize79), getConfigListEntry(_("Step in ms for key %i") % (2), config.plugins.AC3LipSync.absoluteStep2), getConfigListEntry(_("Step in ms for key %i") % (5), config.plugins.AC3LipSync.absoluteStep5), getConfigListEntry(_("Step in ms for key %i") % (8), config.plugins.AC3LipSync.absoluteStep8) ] ConfigListScreen.__init__(self, self.list) self["config"].list = self.list self.skin_path = plugin_path # Plugin Information self["PluginInfo"] = Label(_("Plugin: %(plugin)s , Version: %(version)s") %dict(plugin=PLUGIN_BASE,version=PLUGIN_VERSION)) # BUTTONS self["key_red"] = Button(_("Cancel")) self["key_green"] = Button(_("Save")) self["key_yellow"] = Button(_(" ")) self["key_blue"] = Button(" ") self["setupActions"] = NumberActionMap(["SetupActions", "ColorActions"], { "save": self.save, "cancel": self.cancel, "green": self.save, "red": self.cancel, "ok": self.save, }, -2) def save(self): for x in self.list: x[1].save() self.close() def cancel(self): for x in self["config"].list: x[1].cancel() self.close()