repo_name
stringlengths
5
92
path
stringlengths
4
232
copies
stringclasses
19 values
size
stringlengths
4
7
content
stringlengths
721
1.04M
license
stringclasses
15 values
hash
int64
-9,223,277,421,539,062,000
9,223,102,107B
line_mean
float64
6.51
99.9
line_max
int64
15
997
alpha_frac
float64
0.25
0.97
autogenerated
bool
1 class
CodingCrush/WeeklyReport
deploy/config.py
1
1432
#coding:utf-8 import os base_dir = os.path.dirname(os.path.realpath(__file__)) DEBUG = True SECRET_KEY = os.environ.get('SECRET_KEY') or 'nobody knows the password' PER_PAGE = 10 SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_RECORD_QUERIES = True IMAGE_UPLOAD_DIR = 'static/upload/' UPLOAD_FOLDER = os.path.join(base_dir, 'app/static/upload/') #MAIL_SERVER = 'smtp.163.com' MAIL_SERVER = '' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USERNAME = '<EMAIL@ADDRESS>' MAIL_PASSWORD = '<EMAIL_PASSWORD>' WR_MAIL_SUBJECT_PREFIX = '[WeeklyReport]' WR_MAIL_SENDER = 'WeeklyReport <[email protected]>' DEPARTMENTS = ( '人事行政部', '软件测试部', '产品开发部', '新技术研发部' ) DEFAULT_CONTENT = "<p><strong>1、上周计划完成情况:</strong></p><ol><li></li></ol>" \ "<p>&nbsp;<strong>2、计划外工作(包含协助运维工作):</strong></p><ol><li></li></ol>" \ "<p>&nbsp;<strong>3、重要问题:</strong></p><ol><li></li></ol>" \ "<p>&nbsp;<strong>4、持续未处理解决的事情:</strong></p><ol><li></li></ol>" \ "<p>&nbsp;<strong id=\"next_week\">5、下周计划:</strong></p><ol><li></li></ol>" #SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:postgres@db/wr_prd' SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(base_dir, 'wr_prd.sqlite')
mit
7,987,779,683,887,999,000
27.622222
92
0.621118
false
msanatan/organise
organise/views/todos.py
1
1456
from flask import Blueprint, render_template, request, redirect, url_for, flash from organise.models import Todo from organise import db todos = Blueprint('todos', __name__, template_folder='/../templates') @todos.route('/') def index(): all_todos = Todo.query.order_by(Todo.id.desc()).all() return render_template('todos.html', all_todos=all_todos) @todos.route('/add', methods=['POST']) def add_todo(): todo = Todo(request.form['title'], request.form['description']) db.session.add(todo) db.session.commit() flash('New todo was added') return redirect(url_for('todos.index')) @todos.route('/todo/<int:t_id>') def show_todo(t_id): todo = Todo.query.filter_by(id=t_id).first_or_404() return render_template('todo.html', todo=todo) @todos.route('/todo/<int:t_id>/edit', methods=['POST']) def edit_todo(t_id): changed_title = request.form['title'] changed_description = request.form['description'] todo = Todo.query.filter_by(id=t_id).first_or_404() todo.title = changed_title todo.description = changed_description db.session.commit() flash('All changes were saved') return redirect(url_for('todos.index')) @todos.route('/todo/<int:t_id>/delete', methods=['POST']) def delete_todo(t_id): todo = Todo.query.filter_by(id=t_id).first_or_404() db.session.delete(todo) db.session.commit() flash('Todo successfully deleted') return redirect(url_for('todos.index'))
mit
-5,600,133,511,941,293,000
30.652174
79
0.674451
false
fujimotos/fastcomp
mbleven.py
1
1757
"""An implementation of mbleven algorithm""" # # Constants REPLACE = 'r' INSERT = 'i' DELETE = 'd' TRANSPOSE = 't' MATRIX = [ ['id', 'di', 'rr'], ['dr', 'rd'], ['dd'] ] MATRIX_T = [ ['id', 'di', 'rr', 'tt', 'tr', 'rt'], ['dr', 'rd', 'dt', 'td'], ['dd'] ] # # Library API def compare(str1, str2, transpose=False): len1, len2 = len(str1), len(str2) if len1 < len2: len1, len2 = len2, len1 str1, str2 = str2, str1 if len1 - len2 > 2: return -1 if transpose: models = MATRIX_T[len1-len2] else: models = MATRIX[len1-len2] res = 3 for model in models: cost = check_model(str1, str2, len1, len2, model) if cost < res: res = cost if res == 3: res = -1 return res def check_model(str1, str2, len1, len2, model): """Check if the model can transform str1 into str2""" idx1, idx2 = 0, 0 cost, pad = 0, 0 while (idx1 < len1) and (idx2 < len2): if str1[idx1] != str2[idx2 - pad]: cost += 1 if 2 < cost: return cost option = model[cost-1] if option == DELETE: idx1 += 1 elif option == INSERT: idx2 += 1 elif option == REPLACE: idx1 += 1 idx2 += 1 pad = 0 elif option == TRANSPOSE: if (idx2 + 1) < len2 and str1[idx1] == str2[idx2+1]: idx1 += 1 idx2 += 1 pad = 1 else: return 3 else: idx1 += 1 idx2 += 1 pad = 0 return cost + (len1 - idx1) + (len2 - idx2)
mit
-5,861,236,381,234,552,000
19.670588
68
0.430848
false
scrapinghub/dateparser
dateparser/data/date_translation_data/bem.py
1
2480
info = { "name": "bem", "date_order": "DMY", "january": [ "jan", "januari" ], "february": [ "feb", "februari" ], "march": [ "mac", "machi" ], "april": [ "epr", "epreo" ], "may": [ "mei" ], "june": [ "jun", "juni" ], "july": [ "jul", "julai" ], "august": [ "oga", "ogasti" ], "september": [ "sep", "septemba" ], "october": [ "okt", "oktoba" ], "november": [ "nov", "novemba" ], "december": [ "dis", "disemba" ], "monday": [ "palichimo" ], "tuesday": [ "palichibuli" ], "wednesday": [ "palichitatu" ], "thursday": [ "palichine" ], "friday": [ "palichisano" ], "saturday": [ "pachibelushi" ], "sunday": [ "pa mulungu" ], "am": [ "uluchelo" ], "pm": [ "akasuba" ], "year": [ "umwaka" ], "month": [ "umweshi" ], "week": [ "umulungu" ], "day": [ "ubushiku" ], "hour": [ "insa" ], "minute": [ "mineti" ], "second": [ "sekondi" ], "relative-type": { "0 day ago": [ "lelo" ], "0 hour ago": [ "this hour" ], "0 minute ago": [ "this minute" ], "0 month ago": [ "this month" ], "0 second ago": [ "now" ], "0 week ago": [ "this week" ], "0 year ago": [ "this year" ], "1 day ago": [ "yesterday" ], "1 month ago": [ "last month" ], "1 week ago": [ "last week" ], "1 year ago": [ "last year" ], "in 1 day": [ "tomorrow" ], "in 1 month": [ "next month" ], "in 1 week": [ "next week" ], "in 1 year": [ "next year" ] }, "locale_specific": {}, "skip": [ " ", "'", ",", "-", ".", "/", ";", "@", "[", "]", "|", "," ] }
bsd-3-clause
6,550,758,699,142,455,000
14.391304
26
0.27724
false
kubeflow/tf-operator
py/kubeflow/tf_operator/k8s_util.py
1
6344
"""K8s util class for E2E tests.""" import datetime import json import logging import re import time from kubeflow.testing import util from kubernetes import client as k8s_client from kubernetes.client import rest def get_container_start_time(client, namespace, pod_selector, index, phase): """ get start time of container in the pod with pod_name, we assume there is only one container. Args: client: K8s api client. namespace: Namespace. pod_selector: Selector for the pods. index: Index of the pods phase: expected of the phase when getting the start time Returns: container_start_time: container start time in datetime datatype """ pods = list_pods(client, namespace, pod_selector) logging.info("%s pods matched %s pods", len(pods.items), pod_selector) pod = pods.items[index] if phase == "Running": container_start_time = pod.status.container_statuses[ 0].state.running.started_at else: container_start_time = pod.status.container_statuses[ 0].state.terminated.started_at return container_start_time def log_pods(pods): """Log information about pods.""" for p in pods.items: logging.info("Pod name=%s Phase=%s", p.metadata.name, p.status.phase) def wait_for_pods_to_be_in_phases( client, namespace, pod_selector, phases, timeout=datetime.timedelta(minutes=15), polling_interval=datetime.timedelta(seconds=30)): """Wait for the pods matching the selector to be in the specified state Args: client: K8s api client. namespace: Namespace. pod_selector: Selector for the pods. phases: List of desired phases timeout: How long to wait for the job. polling_interval: How often to poll for the status of the job. status_callback: (Optional): Callable. If supplied this callable is invoked after we poll the job. Callable takes a single argument which is the job. """ time.sleep(polling_interval.seconds) end_time = datetime.datetime.now() + timeout while True: pods = list_pods(client, namespace, pod_selector) logging.info("%s pods matched %s pods", len(pods.items), pod_selector) is_match = True for p in pods.items: if p.status.phase not in phases: # for debug logging.info("pod in phase %s", p.status.phase) is_match = False if is_match and pods.items: logging.info("All pods in phase %s", phases) log_pods(pods) return pods if datetime.datetime.now() + polling_interval > end_time: logging.info("Latest pod phases") log_pods(pods) logging.error("Timeout waiting for pods to be in phase: %s", phases) raise util.TimeoutError( "Timeout waiting for pods to be in states %s" % phases) time.sleep(polling_interval.seconds) return None def wait_for_pods_to_be_deleted( client, namespace, pod_selector, timeout=datetime.timedelta(minutes=10), polling_interval=datetime.timedelta(seconds=30)): """Wait for the specified job to be deleted. Args: client: K8s api client. namespace: Namespace. pod_selector: Selector for the pods. timeout: How long to wait for the job. polling_interval: How often to poll for the status of the job. status_callback: (Optional): Callable. If supplied this callable is invoked after we poll the job. Callable takes a single argument which is the job. """ end_time = datetime.datetime.now() + timeout while True: pods = list_pods(client, namespace, pod_selector) logging.info("%s pods matched %s pods", len(pods.items), pod_selector) if not pods.items: return if datetime.datetime.now() + polling_interval > end_time: raise util.TimeoutError("Timeout waiting for pods to be deleted.") time.sleep(polling_interval.seconds) def list_pods(client, namespace, label_selector): core = k8s_client.CoreV1Api(client) try: pods = core.list_namespaced_pod(namespace, label_selector=label_selector) return pods except rest.ApiException as e: message = "" if e.message: message = e.message if e.body: try: body = json.loads(e.body) except ValueError: # There was a problem parsing the body of the response as json. logging.exception( ("Exception when calling DefaultApi->" "apis_fqdn_v1_namespaces_namespace_resource_post. body: %s"), e.body) raise message = body.get("message") logging.exception(("Exception when calling DefaultApi->" "apis_fqdn_v1_namespaces_namespace_resource_post: %s"), message) raise e def get_events(client, namespace, uid): """Get the events for the provided object.""" core = k8s_client.CoreV1Api(client) try: # We can't filter by labels because events don't appear to have anyone # and I didn't see an easy way to get them. events = core.list_namespaced_event(namespace, limit=500) except rest.ApiException as e: message = "" if e.message: message = e.message if e.body: try: body = json.loads(e.body) except ValueError: # There was a problem parsing the body of the response as json. logging.exception( ("Exception when calling DefaultApi->" "apis_fqdn_v1_namespaces_namespace_resource_post. body: %s"), e.body) raise message = body.get("message") logging.exception(("Exception when calling DefaultApi->" "apis_fqdn_v1_namespaces_namespace_resource_post: %s"), message) raise e matching = [] for e in events.items: if e.involved_object.uid != uid: continue matching.append(e) return matching def parse_events(events): """Parse events. Args: events: List of events. Returns pods_created: Set of unique pod names created. services_created: Set of unique services created. """ pattern = re.compile(".*Created.*(pod|Service).*: (.*)", re.IGNORECASE) pods = set() services = set() for e in events: m = re.match(pattern, e.message) if not m: continue kind = m.group(1) name = m.group(2) if kind.lower() == "pod": pods.add(name) elif kind.lower() == "service": services.add(name) return pods, services
apache-2.0
-723,238,186,295,833,700
27.44843
80
0.660309
false
raghavgupta0296/eminemWithin
trainLSTM.py
1
7863
from keras.layers import LSTM, Dropout, Dense from keras.models import Sequential from keras import backend as KB from keras.layers.core import K from keras.objectives import categorical_crossentropy import tensorflow as tf import numpy as np import word2vec2 tf.set_random_seed(1001) f = open("cleanedRapLyrics.txt") data = f.read().lower() d = [] try: data = data.split("\r\n") for i in data: for j in i.split(" "): d.append(j) d.append("\n") except: print("error : modify code for spliting of data into words") print("DATA TOKENIZED..............") data = d del d # data = tf.compat.as_str((data.split())) vocab_size = 5000 embedding_size = 128 data2, most_common, word2int, int2word = word2vec2.integerizeData(data, vocab_size) del data print("DATA INTEGERIZED............") batch_size = 128 num_skips = 2 skip_window = 1 validation_set = np.random.choice(50, 3, replace=False) neg_samples = 64 # embeddings = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0)) embeddings = word2vec2.trainWord2Vec(data2, batch_size, validation_set, vocab_size, embedding_size, neg_samples, num_skips, skip_window, int2word) print(embeddings) print("Embeddings Obtained.........") print(" Embeddings Shape : ", embeddings.shape) # saver = tf.train.Saver() # with tf.Session() as sess: # saver.restore(sess,"/tmp/word2vecModel.ckpt") # sess.run(tf.all_variables()) # e = tf.get_collection(tf.GraphKeys.VARIABLES, "e")[0] # print "embeddings : ",sess.run(e) words_to_read = 20 X = tf.placeholder(tf.float32, shape=(None, words_to_read, embedding_size)) Y = tf.placeholder(tf.float32, shape=(None,vocab_size)) def one_hot(num): a = np.zeros(vocab_size) a[num] = 1 return a i = 0 def newXY(i): # for i in range(0,len(data2)-words_to_read,1): # global i frame = data2[i] # X = tf.placeholder(tf.float32,shape=(words_to_read,embedding_size)) # X = tf.placeholder(tf.float32,shape=(embedding_size,)) # x = tf.nn.embedding_lookup(embeddings,frame) x = [] # x = embeddings[frame] # initialize X to 0? frame = data2[(i):(i + words_to_read)] output = data2[i + words_to_read] # Y = tf.nn.embedding_lookup(embeddings,output) y = one_hot(output) #y = embeddings[output] for f in frame: # t = tf.nn.embedding_lookup(embeddings,f) x = np.append(x, embeddings[f]) # print x.shape # print t,t.shape # x = tf.concat([x,t],0) # print "X shape : ",X.get_shape() # i+=1 x = np.reshape(x, (words_to_read, embedding_size)) # print x.shape return x, y # nX = len(X) # print "DATA VECTORIZED............." # X = np.reshape(X,(nX,words_to_read,1)) # print X.get_shape(),Y.get_shape() sess = tf.Session() K.set_session(sess) model = Sequential() model.add(LSTM(256, input_shape=(int(X.get_shape()[1]), int(X.get_shape()[2])), return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(256, return_sequences=False)) model.add(Dropout(0.2)) model.add(Dense(vocab_size)) #, activation="softmax")) # model.compile(loss="categorical_crossentropy",optimizer="adam") # model = LSTM(256,input_shape=(X.get_shape()[1],X.get_shape()[2]),init='uniform',return_sequences=True)(X) # model = Dropout(0.2)(model) # model = LSTM(256)(model) # model = Dropout(0.2)(model) # model = Dense(embedding_size,activation='softmax')(model) outModel = model(X) # loss = tf.reduce_mean(categorical_crossentropy(Y, outModel)) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(outModel,Y)) train_step = tf.train.AdamOptimizer(0.001).minimize(loss) print("MODEL CREATED..............") model_json = model.to_json() with open("rapModel.json", "w") as json_file: json_file.write(model_json) # f2 = "weights-improvement.hdf5" # checkpoint = ModelCheckpoint(f2,monitor='loss',verbose=1,save_best_only=True,mode='min') print("Training...................") # model.fit(X,Y,nb_epoch=20,batch_size=128,callbacks=[checkpoint]) ''' def closestEmbedding(predictedWord): ctrEm=[] for q in range(len(embeddings)): ctr = 0 for w in range(len(embeddings[q])): ctr += (predictedWord[0][w] - embeddings[q][w])**2 ctrEm.append(ctr) predictedWord = np.argmax(ctrEm) # to not get UNK as prediction if (predictedWord == 0): predictedWord = np.argsort(ctrEm)[-2] # return predictedWord ''' def generateTest(): words_to_generate = 30 testSeed = np.random.randint(low=1,high=(len(data2)-words_to_read),size=1) testSeed = int(testSeed) tx = [] for t in range(testSeed,testSeed+words_to_read,1): tx.append(int2word[data2[t]]) actualY = data2[testSeed+words_to_read] actualY = one_hot(int(actualY)) actualY = np.reshape(actualY,(1,vocab_size)) # tx = ["came", "back", "from", "those", "strange", "streets","\n","any","day","of","those","lame","dreams","\n","move","with","the","same","speed","\n"] print(tx) for i in range(len(tx)): try: tx[i] = word2int[tx[i]] except: tx[i] = word2int['UNK'] # tx = [word2int[tx_i] for tx_i in tx] tx = [embeddings[tx_i] for tx_i in tx] for j in range(words_to_generate): tx = np.reshape(tx, (1, words_to_read, embedding_size)) if (j == 0): print("loss : ", sess.run([loss], feed_dict={X: tx, Y: actualY, K.learning_phase(): 0})) predictedWord = model.predict(tx) ''' predictedWord = closestEmbedding(predictedWord) predictedWord2 = embeddings[predictedWord] predictedWord2 = np.reshape(predictedWord2,[1,embedding_size]) ''' predictedWord = np.asarray(predictedWord).astype('float64') predictedWord = np.reshape(predictedWord, (vocab_size)) # temperate # temperature = 0.6 # predictedWord = np.log(predictedWord) / temperature # pw = np.exp(predictedWord) # predictedWord = pw / np.sum(pw) # pm = np.random.multinomial(1, predictedWord, 1) # pm = np.reshape(pm,(vocab_size)) pm = predictedWord # either this or temp pw = np.exp(pm) pm = pw / np.sum(pw) predictedWord = np.argmax(pm) # # to not get UNK as prediction if (predictedWord==0): predictedWord = np.argsort(pm)[-2] # predictedWord2 = one_hot(predictedWord) predictedWord2 = np.reshape(predictedWord2,(1,vocab_size)) tx = np.reshape(tx, (words_to_read, embedding_size)) e = embeddings[predictedWord] e = np.reshape(e, (1, embedding_size)) tx = np.append(tx, e, axis=0) tx = tx[1:] print(int2word[predictedWord],' ', end='') # tx = np.reshape(tx,(1,words_to_read,embedding_size)) # print (len(data2)) # - 106989 ...106932 106983 batch_size = int(len(data2)/213) with sess.as_default(): sess.run(tf.global_variables_initializer()) for epoch in range(1, 51): print("\n\n Epoch ", epoch, "/500") for i in range(0,(len(data2) - words_to_read)-batch_size,batch_size): x = np.array([]) y = np.array([]) for j in range(i,i+batch_size,1): # print ('error at ?',i,j) x_, y_ = newXY(j) x = np.append(x,x_) y = np.append(y,y_) # X = tf.reshape(X,[1,words_to_read,embedding_size]) x = np.reshape(x, (batch_size, words_to_read, embedding_size)) y = np.reshape(y, (batch_size, vocab_size)) train_step.run(feed_dict={X: x, Y: y, K.learning_phase(): 1}) # model.fit(x, y, batch_size=batch_size) # if (i%1000==0): # test model generateTest() model.save_weights("rapWeights.h5") print("Training Finished..........")
mit
4,360,297,226,600,381,400
30.452
157
0.608801
false
zhangyage/Python-oldboy
day12/service_manager/manager/views.py
1
4028
# -*- coding:utf-8 -*- from django.shortcuts import render from django.shortcuts import render_to_response from django.shortcuts import redirect #导入跳转连接模块 from django.http.response import HttpResponse #导入模块该模块可以加载处理html网页 from manager import models from models import UserInfo from models import Asset from models import UserGroup from forms import RegisterForm from django.core.context_processors import request #导入数据库模块 # Create your views here. def register(request): register = RegisterForm() if request.method == 'POST': #判断是否是提交数据 form = RegisterForm(request.POST) if form.is_valid(): data = form.cleaned_data print data #UserInfo.objects.create( # username=request.POST.get('username'), # password=request.POST.get('password'), # email=request.POST.get('email'), # typeId_id=request.POST.get('typeid'),) UserInfo.objects.create( username=data['username'], password=data['password'], email=data['email'], user_type_id=data['user_type_id'],) else: temp = form.errors.as_data() print temp['email'][0].messages[0] return render_to_response('register.html',{'form':register}) def login(request): if request.method == 'POST': user = request.POST.get('username',None) #获取用户名 如果没有获取到赋值为None pwd = request.POST.get('password',None) #检查用户名和密码是否存在 result = UserInfo.objects.filter(username=user,password=pwd).count() if result == 1: return redirect ('/manager/index/') #登录成功跳转到首页 else: return render_to_response('login.html',{'status':'用户名密码错误!'}) else: return render_to_response('login.html') def index(request): return render_to_response('index.html',{'status':'欢迎进入主机管理系统!'}) def host(request): return render_to_response('host.html',{'status':'添加主机'}) def add(request): if request.method == 'POST': hostname = request.POST.get('hostname',None) ip = request.POST.get('ip',None) groupname = request.POST.get('groupname',None) if hostname and ip : Asset.objects.create( hostname=hostname, ip=ip, user_group_id=groupname,) return redirect('/manager/list/') else: return render_to_response('host.html',{'decide':'主机信息输入有误,请重新输入!'}) else: return render_to_response('host.html',{'status':'添加主机'}) def list(request): assert_list = Asset.objects.all() return render_to_response('assetlist.html',{'data':assert_list,'decide':'主机添加成功'}) #上面的两行是输出所有的主机 #assert_list = Asset.objects.filter(user_group__GroupName='陨石地带') #user_group__GroupName 选取是在models中定义的如下 #user_group = models.ForeignKey('UserGroup') #return render_to_response('assetlist.html',{'data':assert_list,'decide':'主机添加成功'}) #上面的两行使用的是跨表查询,user_group__GroupName跨表查询使用__ 跨表取值使用的是.可以参考教程day12-02 def many(request): #处理多对多的情况 添加数据 u1 = UserInfo.objects.get(id=2) #获取用户 g1 = UserGroup.objects.get(id=3) #获取组 g1.user.add(u1) #在多对多关系表中建立关系 user的选取是在models中定义的如下 #user = models.ManyToManyField('UserInfo') #或是使用如下方式添加 u1.usergroup_set.add(g1) 注意两种方式u1和g1的顺序 return HttpResponse('Ok')
apache-2.0
279,347,164,223,201,250
33.223301
87
0.608116
false
YourCyborg/Sun-RPI
src/server/caches.py
1
10627
""" Central caching module. """ from sys import getsizeof from collections import defaultdict from django.conf import settings _ENABLE_LOCAL_CACHES = settings.GAME_CACHE_TYPE _GA = object.__getattribute__ _SA = object.__setattr__ _DA = object.__delattr__ # OOB hooks (OOB not yet functional, don't use yet) _OOB_FIELD_UPDATE_HOOKS = defaultdict(dict) _OOB_PROP_UPDATE_HOOKS = defaultdict(dict) _OOB_ATTR_UPDATE_HOOKS = defaultdict(dict) _OOB_NDB_UPDATE_HOOKS = defaultdict(dict) _OOB_CUSTOM_UPDATE_HOOKS = defaultdict(dict) _OOB_HANDLER = None # set by oob handler when it initializes def hashid(obj): """ Returns a per-class unique that combines the object's class name with its idnum and creation time. This makes this id unique also between different typeclassed entities such as scripts and objects (which may still have the same id). """ if not obj: return obj try: hid = _GA(obj, "_hashid") except AttributeError: try: date, idnum = _GA(obj, "db_date_created"), _GA(obj, "id") if not idnum or not date: # this will happen if setting properties on an object # which is not yet saved return None except AttributeError: # this happens if hashing something like ndb. We have to # rely on memory adressing in this case. date, idnum = "Nondb", id(obj) # build the hashid hid = "%s-%s-#%s" % (_GA(obj, "__class__"), date, idnum) _SA(obj, "_hashid", hid) return hid # oob helper functions def register_oob_update_hook(obj,name, entity="field"): """ Register hook function to be called when field/property/db/ndb is updated. Given function will be called with function(obj, entityname, newvalue, *args, **kwargs) entity - one of "field", "property", "db", "ndb" or "custom" """ hid = hashid(obj) if hid: if entity == "field": global _OOB_FIELD_UPDATE_HOOKS _OOB_FIELD_UPDATE_HOOKS[hid][name] = True return elif entity == "property": global _OOB_PROP_UPDATE_HOOKS _OOB_PROP_UPDATE_HOOKS[hid][name] = True elif entity == "db": global _OOB_ATTR_UPDATE_HOOKS _OOB_ATTR_UPDATE_HOOKS[hid][name] = True elif entity == "ndb": global _OOB_NDB_UPDATE_HOOKS _OOB_NDB_UPDATE_HOOKS[hid][name] = True elif entity == "custom": global _OOB_CUSTOM_UPDATE_HOOKS _OOB_CUSTOM_UPDATE_HOOKS[hid][name] = True else: return None def unregister_oob_update_hook(obj, name, entity="property"): """ Un-register a report hook """ hid = hashid(obj) if hid: global _OOB_FIELD_UPDATE_HOOKS,_OOB_PROP_UPDATE_HOOKS, _OOB_ATTR_UPDATE_HOOKS global _OOB_CUSTOM_UPDATE_HOOKS, _OOB_NDB_UPDATE_HOOKS if entity == "field" and name in _OOB_FIELD_UPDATE_HOOKS: del _OOB_FIELD_UPDATE_HOOKS[hid][name] elif entity == "property" and name in _OOB_PROP_UPDATE_HOOKS: del _OOB_PROP_UPDATE_HOOKS[hid][name] elif entity == "db" and name in _OOB_ATTR_UPDATE_HOOKS: del _OOB_ATTR_UPDATE_HOOKS[hid][name] elif entity == "ndb" and name in _OOB_NDB_UPDATE_HOOKS: del _OOB_NDB_UPDATE_HOOKS[hid][name] elif entity == "custom" and name in _OOB_CUSTOM_UPDATE_HOOKS: del _OOB_CUSTOM_UPDATE_HOOKS[hid][name] else: return None def call_ndb_hooks(obj, attrname, value): """ No caching is done of ndb here, but we use this as a way to call OOB hooks. """ hid = hashid(obj) if hid: oob_hook = _OOB_NDB_UPDATE_HOOKS[hid].get(attrname) if oob_hook: oob_hook[0](obj.typeclass, attrname, value, *oob_hook[1], **oob_hook[2]) def call_custom_hooks(obj, attrname, value): """ Custom handler for developers adding their own oob hooks, e.g. to custom typeclass properties. """ hid = hashid(obj) if hid: oob_hook = _OOB_CUSTOM_UPDATE_HOOKS[hid].get(attrname) if oob_hook: oob_hook[0](obj.typeclass, attrname, value, *oob_hook[1], **oob_hook[2]) if _ENABLE_LOCAL_CACHES: # Cache stores _ATTR_CACHE = defaultdict(dict) _FIELD_CACHE = defaultdict(dict) _PROP_CACHE = defaultdict(dict) def get_cache_sizes(): """ Get cache sizes, expressed in number of objects and memory size in MB """ global _ATTR_CACHE, _FIELD_CACHE, _PROP_CACHE attr_n = sum(len(dic) for dic in _ATTR_CACHE.values()) attr_mb = sum(sum(getsizeof(obj) for obj in dic.values()) for dic in _ATTR_CACHE.values()) / 1024.0 field_n = sum(len(dic) for dic in _FIELD_CACHE.values()) field_mb = sum(sum([getsizeof(obj) for obj in dic.values()]) for dic in _FIELD_CACHE.values()) / 1024.0 prop_n = sum(len(dic) for dic in _PROP_CACHE.values()) prop_mb = sum(sum([getsizeof(obj) for obj in dic.values()]) for dic in _PROP_CACHE.values()) / 1024.0 return (attr_n, attr_mb), (field_n, field_mb), (prop_n, prop_mb) # on-object database field cache def get_field_cache(obj, name): "On-model Cache handler." global _FIELD_CACHE hid = hashid(obj) if hid: try: return _FIELD_CACHE[hid][name] except KeyError: val = _GA(obj, "db_%s" % name) _FIELD_CACHE[hid][name] = val return val return _GA(obj, "db_%s" % name) def set_field_cache(obj, name, val): "On-model Cache setter. Also updates database." _SA(obj, "db_%s" % name, val) _GA(obj, "save")() hid = hashid(obj) if hid: global _FIELD_CACHE _FIELD_CACHE[hid][name] = val # oob hook functionality if _OOB_FIELD_UPDATE_HOOKS[hid].get(name): _OOB_HANDLER.update(hid, name, val) def del_field_cache(obj, name): "On-model cache deleter" hid = hashid(obj) _SA(obj, "db_%s" % name, None) _GA(obj, "save")() if hid: try: del _FIELD_CACHE[hid][name] except KeyError: pass if _OOB_FIELD_UPDATE_HOOKS[hid].get(name): _OOB_HANDLER.update(hid, name, None) def flush_field_cache(obj=None): "On-model cache resetter" hid = hashid(obj) global _FIELD_CACHE if hid: del _FIELD_CACHE[hashid(obj)] else: # clean cache completely _FIELD_CACHE = defaultdict(dict) # on-object property cache (unrelated to database) # Note that the get/set_prop_cache handler do not actually # get/set the property "on" the object but only reads the # value to/from the cache. This is intended to be used # with a get/setter property on the object. def get_prop_cache(obj, name, default=None): "On-model Cache handler." global _PROP_CACHE hid = hashid(obj) if hid: try: val = _PROP_CACHE[hid][name] except KeyError: return default _PROP_CACHE[hid][name] = val return val return default def set_prop_cache(obj, name, val): "On-model Cache setter. Also updates database." hid = hashid(obj) if hid: global _PROP_CACHE _PROP_CACHE[hid][name] = val # oob hook functionality oob_hook = _OOB_PROP_UPDATE_HOOKS[hid].get(name) if oob_hook: oob_hook[0](obj.typeclass, name, val, *oob_hook[1], **oob_hook[2]) def del_prop_cache(obj, name): "On-model cache deleter" try: del _PROP_CACHE[hashid(obj)][name] except KeyError: pass def flush_prop_cache(obj=None): "On-model cache resetter" hid = hashid(obj) global _PROP_CACHE if hid: del _PROP_CACHE[hashid(obj)] else: # clean cache completely _PROP_CACHE = defaultdict(dict) # attribute cache def get_attr_cache(obj, attrname): """ Attribute cache store """ return _ATTR_CACHE[hashid(obj)].get(attrname, None) def set_attr_cache(obj, attrname, attrobj): """ Cache an attribute object """ hid = hashid(obj) if hid: global _ATTR_CACHE _ATTR_CACHE[hid][attrname] = attrobj # oob hook functionality oob_hook = _OOB_ATTR_UPDATE_HOOKS[hid].get(attrname) if oob_hook: oob_hook[0](obj.typeclass, attrname, attrobj.value, *oob_hook[1], **oob_hook[2]) def del_attr_cache(obj, attrname): """ Remove attribute from cache """ global _ATTR_CACHE try: del _ATTR_CACHE[hashid(obj)][attrname] except KeyError: pass def flush_attr_cache(obj=None): """ Flush the attribute cache for this object. """ global _ATTR_CACHE if obj: del _ATTR_CACHE[hashid(obj)] else: # clean cache completely _ATTR_CACHE = defaultdict(dict) else: # local caches disabled. Use simple pass-through replacements def get_cache_sizes(): return (0, 0), (0, 0), (0, 0) def get_field_cache(obj, name): return _GA(obj, "db_%s" % name) def set_field_cache(obj, name, val): _SA(obj, "db_%s" % name, val) _GA(obj, "save")() hid = hashid(obj) if _OOB_FIELD_UPDATE_HOOKS[hid].get(name): _OOB_HANDLER.update(hid, name, val) def del_field_cache(obj, name): _SA(obj, "db_%s" % name, None) _GA(obj, "save")() hid = hashid(obj) if _OOB_FIELD_UPDATE_HOOKS[hid].get(name): _OOB_HANDLER.update(hid, name, None) def flush_field_cache(obj=None): pass # these should get oob handlers when oob is implemented. def get_prop_cache(obj, name, default=None): return None def set_prop_cache(obj, name, val): pass def del_prop_cache(obj, name): pass def flush_prop_cache(obj=None): pass def get_attr_cache(obj, attrname): return None def set_attr_cache(obj, attrname, attrobj): pass def del_attr_cache(obj, attrname): pass def flush_attr_cache(obj=None): pass
bsd-3-clause
2,784,834,849,276,704,300
31.59816
111
0.56714
false
openid/python-openid
openid/test/test_xrires.py
1
1571
from __future__ import unicode_literals from unittest import TestCase from openid.yadis import xrires class ProxyQueryTestCase(TestCase): def setUp(self): self.proxy_url = 'http://xri.example.com/' self.proxy = xrires.ProxyResolver(self.proxy_url) self.servicetype = 'xri://+i-service*(+forwarding)*($v*1.0)' self.servicetype_enc = 'xri%3A%2F%2F%2Bi-service%2A%28%2Bforwarding%29%2A%28%24v%2A1.0%29' def test_proxy_url(self): st = self.servicetype ste = self.servicetype_enc args_esc = "_xrd_r=application%2Fxrds%2Bxml&_xrd_t=" + ste pqu = self.proxy.queryURL h = self.proxy_url self.assertEqual(pqu('=foo', st), h + '=foo?' + args_esc) self.assertEqual(pqu('=foo/bar?baz', st), h + '=foo/bar?baz&' + args_esc) self.assertEqual(pqu('=foo/bar?baz=quux', st), h + '=foo/bar?baz=quux&' + args_esc) self.assertEqual(pqu('=foo/bar?mi=fa&so=la', st), h + '=foo/bar?mi=fa&so=la&' + args_esc) # With no service endpoint selection. args_esc = "_xrd_r=application%2Fxrds%2Bxml%3Bsep%3Dfalse" self.assertEqual(pqu('=foo', None), h + '=foo?' + args_esc) def test_proxy_url_qmarks(self): st = self.servicetype ste = self.servicetype_enc args_esc = "_xrd_r=application%2Fxrds%2Bxml&_xrd_t=" + ste pqu = self.proxy.queryURL h = self.proxy_url self.assertEqual(pqu('=foo/bar?', st), h + '=foo/bar??' + args_esc) self.assertEqual(pqu('=foo/bar???', st), h + '=foo/bar????' + args_esc)
apache-2.0
-4,338,642,598,698,818,600
41.459459
98
0.60471
false
ebt-hpc/cca
cca/scripts/materialize_fact.py
1
4532
#!/usr/bin/env python3 ''' Base library for fact materialization Copyright 2012-2020 Codinuum Software Lab <https://codinuum.com> 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.path import sys import re import pathsetup import dp import project import sparql from ns import VER_NS, FB_NS import virtuoso from virtuoso import VIRTUOSO_PW, DEFAULT_PORT MAX_VER_TRIPLES = 128 VER_ORDER_QUERY = ''' PREFIX ver: <%(ver_ns)s> WITH <%(graph)s> INSERT { %(ver_next_triples)s } ''' INSERT_PAT = re.compile(r'insert', re.I) class Materializer(dp.base): def __init__(self, qdir, queries, proj_id, method='odbc', pw=VIRTUOSO_PW, port=DEFAULT_PORT): self._query_dir = qdir self._queries = queries self._proj_id = proj_id self._graph_uri = FB_NS + proj_id self._sparql = sparql.get_driver(method, pw=pw, port=port) self._port = port self._pw = pw try: self._conf = project.get_conf(proj_id) except: self._conf = None def make_ver_next_triples(self): triples = [] ts = [] if self._conf: if self._conf.vpairs: for (u1, u2) in self._conf.vURIpairs: if len(ts) >= MAX_VER_TRIPLES: triples.append(ts) ts = [] ts.append('<%s> ver:next <%s> .' % (u1, u2)) else: uris = self._conf.versionURIs for i in range(self._conf.nversions - 1): if len(ts) >= MAX_VER_TRIPLES: triples.append(ts) ts = [] ts.append('<%s> ver:next <%s> .' % (uris[i], uris[i+1])) if ts: triples.append(ts) return triples def insert_ver_next_triples(self): for triples in self.make_ver_next_triples(): params = { 'ver_ns' : VER_NS, 'graph' : self._graph_uri, 'ver_next_triples' : '\n'.join(triples) } q = VER_ORDER_QUERY % params self.debug('query:\n%s' % q) self._sparql.execute(q) def get_query(self, lang, name): query = None path = os.path.join(self._query_dir, lang, name) try: f = open(path, 'r') q = f.read() query = INSERT_PAT.sub('WITH <%s>\nINSERT' % self._graph_uri, q, count=1).rstrip('\n ;') f.close() except Exception as e: self.error(str(e)) return query def materialize(self): self.message('materializing for "%s"...' % self._proj_id) self.message('materializing version order...') self.insert_ver_next_triples() for lang in self._queries.keys(): for qname in self._queries[lang]: self.message('processing \"%s\" for %s...' % (qname, lang)), sys.stdout.flush() query = self.get_query(lang, qname) self._sparql.execute(query) self.message('done.') virt = virtuoso.base(pw=self._pw, port=self._port) rc = virt.checkpoint() return rc def main(qdir, queries, desc, pw=VIRTUOSO_PW): from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=desc, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('proj_id', type=str, help='project id') parser.add_argument('-d', '--debug', dest='debug', action='store_true', help='enable debug printing') parser.add_argument('-p', '--port', dest='port', default=1111, metavar='PORT', type=int, help='port number') args = parser.parse_args() dp.debug_flag = args.debug m = Materializer(qdir, queries, args.proj_id, pw=pw, port=args.port) m.materialize() if __name__ == '__main__': main(None, {}, 'materialize version fact')
apache-2.0
-7,902,259,919,020,810,000
27.503145
100
0.560459
false
apanda/modeling
tests/examples/AclContentCacheSimpleTest.py
1
1446
import components def AclContentCacheSimpleTest (): """ACL content cache test""" ctx = components.Context (['a', 'b', 'cc'],\ ['ip_a', 'ip_b', 'ip_cc']) net = components.Network (ctx) a = components.EndHost(ctx.a, net, ctx) b = components.EndHost(ctx.b, net, ctx) cc = components.AclContentCache(ctx.cc, net, ctx) net.setAddressMappings([(a, ctx.ip_a), \ (b, ctx.ip_b), \ (cc, ctx.ip_cc)]) addresses = [ctx.ip_a, ctx.ip_b, ctx.ip_cc] net.RoutingTable(a, [(x, cc) for x in addresses]) net.RoutingTable(b, [(x, cc) for x in addresses]) net.RoutingTable(cc, [(ctx.ip_a, a), \ (ctx.ip_b, b)]) endhosts = [a, b] cc.AddAcls([(ctx.ip_a, ctx.ip_b)]) endhosts = [a, b] net.Attach(a, b, cc) class AclContentCacheSimpleReturn (object): def __init__ (self, net, ctx, a, b, cc): self.net = net self.ctx = ctx self.a = a self.b = b self.cc = cc self.check = components.PropertyChecker (ctx, net) return AclContentCacheSimpleReturn(net, ctx, a, b, cc) # To run in a Python shell # from examples import AclContentCacheSimpleTest # m = AclContentCacheSimpleTest() # For unsat result y = m.check.CheckDataIsolationProperty(m.a, m.b) # For sat result y = m.check.CheckDataIsolationProperty(m.b, m.a)
bsd-3-clause
4,938,725,288,037,914,000
38.081081
67
0.559474
false
appcove/DocStruct
Python/DocStruct/Jobs/Document.py
1
5181
# vim:fileencoding=utf-8:ts=2:sw=2:expandtab import re import os import os.path import glob import mimetypes import subprocess from ..Base import S3 from . import Job, S3BackedFile class S3BackedDocument(S3BackedFile): def __init__(self, *, OutputKey, **kw): super().__init__(**kw) self.OutputKey = OutputKey def GenerateImagesFromPDF(self, *, PDFPath): # Generate images from pages of PDF and save images to S3 PageNamePrefix = PDFPath.replace('.pdf', '') PageNameFormat = PageNamePrefix + '-%d.png' # Call ghostscript to produce the images try: out = subprocess.check_output((self.Binaries.Ghostscript, '-sDEVICE=png256', '-dNOPAUSE', '-r300', '-o', PageNameFormat, PDFPath), stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise Exception("ERROR: {0}".format(exc.output)) # search for all files with the relevant prefix and upload them to S3 images = glob.glob(PageNamePrefix + '-*.png') regex = re.compile(PageNamePrefix + '-(\d+)\.png') images.sort(key=lambda im: int(regex.sub('\g<1>', im))) thumbs = [] # Loop over the images of pages to create thumbnails from them for im in images: # Prepare filenames regular_thumnail_file = im.replace('.png', '.1200x1200.png') small_thumbnail_file = im.replace('.png', '.160x160.png') page_num = int(regex.sub('\g<1>', im)) # Now, upload the 2 thumbnails to S3 for fname in (regular_thumnail_file, small_thumbnail_file): # Get the size specification from the filename. # EX: if fname == thumb-1.1200x1200.png, fsize = 1200x1200 fsize = fname.split('.')[-2] # Create regular version try: cmd = ( self.Binaries.Convert, im, '-resize', fsize, fname, ) subprocess.call(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as exc: raise Exception("ERROR: {0}".format(exc.output)) # We'll upload using a stream with open(fname, 'rb') as fp: o_key = os.path.join(self.OutputKeyPrefix, fname.replace(PageNamePrefix, 'thumb')) o_mime = mimetypes.guess_type(fname)[0] or "application/octet-stream" S3.PutObject( session=self.Config.Session, bucket=self.Config.S3_OutputBucket, key=o_key, content=fp, type_=o_mime, ) # Log message saying that images has uploaded self.Logger.debug("Finished Upload of {0} to S3".format(o_key)) # Inspect the path so that we get image props props = self.InspectImage(fname) props['Key'] = o_key props['PageNumber'] = page_num thumbs.append(props) # Mark for cleanup self.MarkFilePathForCleanup(fname) # Make sure the main file gets deleted after we exit self.MarkFilePathForCleanup(im) # Return all the keys that have been uploaded to S3 return thumbs def ConvertToPDF(self): # Prepare some variables we need for this job FilePath = self.LocalFilePath OutputFilePath = self.GetLocalFilePathFromS3Key(Key=self.OutputKey, KeyPrefix=self.OutputKeyPrefix) self.Logger.debug("Will convert {0} to {1}".format(self.InputKey, self.OutputKey)) # Use pyuno to speak to the headless openoffice server try: out = subprocess.check_output((self.Binaries.Python2, self.Binaries.DocumentConverter, FilePath, OutputFilePath), stderr=subprocess.STDOUT) self.Logger.debug("Done with conversion") except subprocess.CalledProcessError as exc: raise Exception("ERROR: {0}".format(exc.output)) # After conversion upload the file to S3 o_key = os.path.join(self.OutputKeyPrefix, self.OutputKey) o_mime = mimetypes.guess_type(self.OutputKey)[0] or "application/octet-stream" with open(OutputFilePath, 'rb') as fp: S3.PutObject( session=self.Config.Session, bucket=self.Config.S3_OutputBucket, key=o_key, content=fp, type_=o_mime, ) # Save output key self.Output['Outputs'].append({'Key': o_key, 'Type': 'PDF'}) # Log a message self.Logger.debug("Finished Upload of {0} to S3".format(self.OutputKey)) # Generate images from all pages of PDF o_thumbs = self.GenerateImagesFromPDF(PDFPath=OutputFilePath) self.Output['Outputs'].extend(o_thumbs) # Add number of thumbnails to Input # NOTE: we create 2 thumbnails per input, hence the division by 2 self.Output['Input'] = {'NumPages': (len(o_thumbs) / 2)} # Mark the new file for deletion self.MarkFilePathForCleanup(OutputFilePath) def Run(self): self.ConvertToPDF() @Job def ConvertToPDF(*, InputKey, OutputKeyPrefix, Config, Logger, OutputKey='output.pdf'): Logger.debug("ResizeImage job for {0} started".format(InputKey)) # Prepare context in which we'll run ctxt = S3BackedDocument( InputKey=InputKey, OutputKeyPrefix=OutputKeyPrefix, OutputKey=OutputKey, Config=Config, Logger=Logger, ) # Start the processing with ctxt as doc: doc.Run()
apache-2.0
6,697,037,800,521,135,000
34.006757
162
0.652577
false
seishei/multiprocess
py3.4/multiprocess/queues.py
1
11410
# # Module implementing queues # # multiprocessing/queues.py # # Copyright (c) 2006-2008, R Oudkerk # Licensed to PSF under a Contributor Agreement. # __all__ = ['Queue', 'SimpleQueue', 'JoinableQueue'] import sys import os import threading import collections import time import weakref import errno from queue import Empty, Full import _multiprocess as _multiprocessing from . import connection from . import context from .util import debug, info, Finalize, register_after_fork, is_exiting from .reduction import ForkingPickler # # Queue type using a pipe, buffer and thread # class Queue(object): def __init__(self, maxsize=0, *, ctx): if maxsize <= 0: maxsize = _multiprocessing.SemLock.SEM_VALUE_MAX self._maxsize = maxsize self._reader, self._writer = connection.Pipe(duplex=False) self._rlock = ctx.Lock() self._opid = os.getpid() if sys.platform == 'win32': self._wlock = None else: self._wlock = ctx.Lock() self._sem = ctx.BoundedSemaphore(maxsize) # For use by concurrent.futures self._ignore_epipe = False self._after_fork() if sys.platform != 'win32': register_after_fork(self, Queue._after_fork) def __getstate__(self): context.assert_spawning(self) return (self._ignore_epipe, self._maxsize, self._reader, self._writer, self._rlock, self._wlock, self._sem, self._opid) def __setstate__(self, state): (self._ignore_epipe, self._maxsize, self._reader, self._writer, self._rlock, self._wlock, self._sem, self._opid) = state self._after_fork() def _after_fork(self): debug('Queue._after_fork()') self._notempty = threading.Condition(threading.Lock()) self._buffer = collections.deque() self._thread = None self._jointhread = None self._joincancelled = False self._closed = False self._close = None self._send_bytes = self._writer.send_bytes self._recv_bytes = self._reader.recv_bytes self._poll = self._reader.poll def put(self, obj, block=True, timeout=None): assert not self._closed if not self._sem.acquire(block, timeout): raise Full self._notempty.acquire() try: if self._thread is None: self._start_thread() self._buffer.append(obj) self._notempty.notify() finally: self._notempty.release() def get(self, block=True, timeout=None): if block and timeout is None: with self._rlock: res = self._recv_bytes() self._sem.release() else: if block: deadline = time.time() + timeout if not self._rlock.acquire(block, timeout): raise Empty try: if block: timeout = deadline - time.time() if timeout < 0 or not self._poll(timeout): raise Empty elif not self._poll(): raise Empty res = self._recv_bytes() self._sem.release() finally: self._rlock.release() # unserialize the data after having released the lock return ForkingPickler.loads(res) def qsize(self): # Raises NotImplementedError on Mac OSX because of broken sem_getvalue() return self._maxsize - self._sem._semlock._get_value() def empty(self): return not self._poll() def full(self): return self._sem._semlock._is_zero() def get_nowait(self): return self.get(False) def put_nowait(self, obj): return self.put(obj, False) def close(self): self._closed = True self._reader.close() if self._close: self._close() def join_thread(self): debug('Queue.join_thread()') assert self._closed if self._jointhread: self._jointhread() def cancel_join_thread(self): debug('Queue.cancel_join_thread()') self._joincancelled = True try: self._jointhread.cancel() except AttributeError: pass def _start_thread(self): debug('Queue._start_thread()') # Start thread which transfers data from buffer to pipe self._buffer.clear() self._thread = threading.Thread( target=Queue._feed, args=(self._buffer, self._notempty, self._send_bytes, self._wlock, self._writer.close, self._ignore_epipe), name='QueueFeederThread' ) self._thread.daemon = True debug('doing self._thread.start()') self._thread.start() debug('... done self._thread.start()') # On process exit we will wait for data to be flushed to pipe. # # However, if this process created the queue then all # processes which use the queue will be descendants of this # process. Therefore waiting for the queue to be flushed # is pointless once all the child processes have been joined. created_by_this_process = (self._opid == os.getpid()) if not self._joincancelled and not created_by_this_process: self._jointhread = Finalize( self._thread, Queue._finalize_join, [weakref.ref(self._thread)], exitpriority=-5 ) # Send sentinel to the thread queue object when garbage collected self._close = Finalize( self, Queue._finalize_close, [self._buffer, self._notempty], exitpriority=10 ) @staticmethod def _finalize_join(twr): debug('joining queue thread') thread = twr() if thread is not None: thread.join() debug('... queue thread joined') else: debug('... queue thread already dead') @staticmethod def _finalize_close(buffer, notempty): debug('telling queue thread to quit') notempty.acquire() try: buffer.append(_sentinel) notempty.notify() finally: notempty.release() @staticmethod def _feed(buffer, notempty, send_bytes, writelock, close, ignore_epipe): debug('starting thread to feed data to pipe') nacquire = notempty.acquire nrelease = notempty.release nwait = notempty.wait bpopleft = buffer.popleft sentinel = _sentinel if sys.platform != 'win32': wacquire = writelock.acquire wrelease = writelock.release else: wacquire = None try: while 1: nacquire() try: if not buffer: nwait() finally: nrelease() try: while 1: obj = bpopleft() if obj is sentinel: debug('feeder thread got sentinel -- exiting') close() return # serialize the data before acquiring the lock obj = ForkingPickler.dumps(obj) if wacquire is None: send_bytes(obj) else: wacquire() try: send_bytes(obj) finally: wrelease() except IndexError: pass except Exception as e: if ignore_epipe and getattr(e, 'errno', 0) == errno.EPIPE: return # Since this runs in a daemon thread the resources it uses # may be become unusable while the process is cleaning up. # We ignore errors which happen after the process has # started to cleanup. try: if is_exiting(): info('error in queue thread: %s', e) else: import traceback traceback.print_exc() except Exception: pass _sentinel = object() # # A queue type which also supports join() and task_done() methods # # Note that if you do not call task_done() for each finished task then # eventually the counter's semaphore may overflow causing Bad Things # to happen. # class JoinableQueue(Queue): def __init__(self, maxsize=0, *, ctx): Queue.__init__(self, maxsize, ctx=ctx) self._unfinished_tasks = ctx.Semaphore(0) self._cond = ctx.Condition() def __getstate__(self): return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks) def __setstate__(self, state): Queue.__setstate__(self, state[:-2]) self._cond, self._unfinished_tasks = state[-2:] def put(self, obj, block=True, timeout=None): assert not self._closed if not self._sem.acquire(block, timeout): raise Full self._notempty.acquire() self._cond.acquire() try: if self._thread is None: self._start_thread() self._buffer.append(obj) self._unfinished_tasks.release() self._notempty.notify() finally: self._cond.release() self._notempty.release() def task_done(self): self._cond.acquire() try: if not self._unfinished_tasks.acquire(False): raise ValueError('task_done() called too many times') if self._unfinished_tasks._semlock._is_zero(): self._cond.notify_all() finally: self._cond.release() def join(self): self._cond.acquire() try: if not self._unfinished_tasks._semlock._is_zero(): self._cond.wait() finally: self._cond.release() # # Simplified Queue type -- really just a locked pipe # class SimpleQueue(object): def __init__(self, *, ctx): self._reader, self._writer = connection.Pipe(duplex=False) self._rlock = ctx.Lock() self._poll = self._reader.poll if sys.platform == 'win32': self._wlock = None else: self._wlock = ctx.Lock() def empty(self): return not self._poll() def __getstate__(self): context.assert_spawning(self) return (self._reader, self._writer, self._rlock, self._wlock) def __setstate__(self, state): (self._reader, self._writer, self._rlock, self._wlock) = state def get(self): with self._rlock: res = self._reader.recv_bytes() # unserialize the data after having released the lock return ForkingPickler.loads(res) def put(self, obj): # serialize the data before acquiring the lock obj = ForkingPickler.dumps(obj) if self._wlock is None: # writes to a message oriented win32 pipe are atomic self._writer.send_bytes(obj) else: with self._wlock: self._writer.send_bytes(obj)
bsd-3-clause
1,002,262,573,594,378,100
30.089918
80
0.539965
false
sebcagnon/PyGoogleForm
PyGoogleForm/FormParser.py
1
2990
import collections import urllib, urllib2 from bs4 import BeautifulSoup from FormQuestion import GFQuestion class GFParser(object): """Allows to access all the questions from a GForm and submit a response""" def __init__(self, url): """Loads form from its public page url""" self.url = url res = urllib2.urlopen(self.url) self.soup = BeautifulSoup(res.read(), 'html.parser') if len(self.soup.find_all("h1", "ss-form-title")) == 0: raise ValueError("The url did not correspond to a valid Google Form") questionsList = [GFQuestion(qSoup) for qSoup in self.soup.form.findChildren("div", "ss-form-question")] self.questions = collections.OrderedDict((q.getID(), q) for q in questionsList) def getFormInfos(self): """returns general form info [title, desc]""" info = [] info.append(self.soup.find_all("h1", "ss-form-title")[0].string) info.append(self.soup.find_all("div", "ss-form-desc")[0].string) return info def getQuestionIDs(self): """Returns list of question IDs""" return self.questions.keys() def getQuestionInfo(self, id): """Returns the info necessary to answer question as a list [id, type, question, choices] """ return self.questions[id].getQuestionAsList() def __getitem__(self, id): """If id is string, same as getQuestionInfo, if int, returns i-th question info""" if isinstance(id, basestring): return getQuestionInfo(id) elif isinstance(id, int): return getQuestionInfo(self.questions[self.questions.keys()[id]]) else: raise TypeError("id can only be str (a question id), or int (the index of the question") def answerQuestion(self, id, answer): """Saves the answer of question with that id""" self.questions[id].answerQuestion(answer) def submit(self): """POST current answers to Google Forms""" tups = tuple() for q in self.questions.values(): if q.getAnswerData() is not None: tups += q.getAnswerData() data = urllib.urlencode(tups) postURL = self.soup.form["action"] request = urllib2.Request(postURL, data) urllib2.urlopen(request) def main(): # Testing GFParser basics url = "https://docs.google.com/forms/d/1jzDkEha066GwSCcSrCg1yaJJLpJAk0_aIFwf6GQgmmU/viewform" gForm = GFParser(url) assert gForm.getFormInfos() == ["Testing", "This form is a test"], "Form info is wrong" assert len(gForm.getQuestionIDs()) == 5, "Number of questions ain't right, got {}, should be 5".format(len(gForm.getQuestions())) # Testing filling the form and submitting questionIDs = gForm.getQuestionIDs() for id in questionIDs: question = gForm.getQuestionInfo(id) if question[1] in ['ss-radio', 'ss-select']: gForm.answerQuestion(question[0], question[3][0]) elif question[1] == 'ss-checkbox': gForm.answerQuestion(question[0], question[3][:-1]) else: gForm.answerQuestion(question[0], "hello test!") gForm.submit() import datetime print "New answer submitted: " + str(datetime.datetime.now()) print "All tests succesful!" if __name__ == '__main__': main()
mit
-3,894,057,165,791,160,000
33.77907
130
0.705686
false
splotz90/urh
src/urh/plugins/MessageBreak/MessageBreakPlugin.py
1
1516
from PyQt5.QtWidgets import QAction, QUndoStack, QMessageBox from urh.signalprocessing.ProtocolAnalyzer import ProtocolAnalyzer from ..Plugin import ProtocolPlugin from ..MessageBreak.MessageBreakAction import MessageBreakAction class MessageBreakPlugin(ProtocolPlugin): def __init__(self): super().__init__(name="MessageBreak") self.undo_stack = None self.command = None """:type: QUndoAction """ def get_action(self, parent, undo_stack: QUndoStack, sel_range, protocol: ProtocolAnalyzer, view: int): """ :type parent: QTableView :type undo_stack: QUndoStack :type protocol_analyzers: list of ProtocolAnalyzer """ min_row, max_row, start, end = sel_range if min_row == -1 or max_row == -1 or start == -1 or end == -1: return None if max_row != min_row: QMessageBox.critical(parent, self.tr("Error in MessageBreak"), self.tr("You can only break one line per action.")) return None end = protocol.convert_index(end, view, 0, True, message_indx=min_row)[0] # factor = 1 if view == 0 else 4 if view == 1 else 8 self.command = MessageBreakAction(protocol, max_row, end) action = QAction(self.command.text(), parent) action.triggered.connect(self.action_triggered) self.undo_stack = undo_stack return action def action_triggered(self): self.undo_stack.push(self.command)
gpl-3.0
-3,533,856,325,746,229,000
35.97561
107
0.631266
false
monkeython/scriba
scriba/schemes/scriba_pop.py
1
2120
"""Handle mailto URL""" import email import os import poplib import socket import multipla content_encodings = multipla.power_up('scriba.content_encodings') content_types = multipla.power_up('scriba.content_types') email_mimes = multipla.power_up('scriba.email_mimes') class BadPOP3Response(Exception): pass def read(url, **args): """Get the object from a ftp URL.""" all_ = args.pop('all', False) password = args.pop('password', '') if not password: raise ValueError('password') try: username, __ = url.username.split(';') except ValueError: username = url.username if not username: username = os.environ.get('USERNAME') username = os.environ.get('LOGNAME', username) username = os.environ.get('USER', username) client = poplib.POP3(url.hostname, url.port or poplib.POP3_PORT, args.pop('timeout', socket._GLOBAL_DEFAULT_TIMEOUT)) response, count, __ = client.apop(username, password) if 'OK' not in response: raise BadPOP3Response(response) if count == 0: raise ValueError('count: 0') collection = [] for id_ in range(count if all_ is True else 1): response, lines, __ = client.retr(id_ + 1) if 'OK' not in response: raise BadPOP3Response(response) client.dele(id_ + 1) message = email.message_from_string('\n'.join(lines)) content_type = message.get_content_type() filename = message.get_filename('') encoding = message['Content-Encoding'] content = message.get_payload(decode=True) content = content_encodings.get(encoding).decode(content) content = content_types.get(content_type).parse(content) collection.append((filename, content)) client.quit() return collection if len(collection) > 0 else collection[0][1] # 01612147400 # 07443866622 def write(url, collection, **args): """Put an object into a ftp URL.""" raise NotImplementedError def erase(url, **args): """Remove the sample from a file URL.""" raise NotImplementedError
bsd-3-clause
-8,228,334,765,132,890,000
30.176471
77
0.641038
false
AnnalisaS/migration_geonode
setup.py
1
3970
######################################################################### # # Copyright (C) 2012 OpenPlans # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### from distutils.core import setup from distutils.command.install import INSTALL_SCHEMES import os import sys def fullsplit(path, result=None): """ Split a pathname into components (the opposite of os.path.join) in a platform-neutral way. """ if result is None: result = [] head, tail = os.path.split(path) if head == '': return [tail] + result if head == path: return result return fullsplit(head, [tail] + result) # Tell distutils not to put the data_files in platform-specific installation # locations. See here for an explanation: # http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] # Compile the list of packages available, because distutils doesn't have # an easy way to do this. packages, data_files = [], [] root_dir = os.path.dirname(__file__) if root_dir != '': os.chdir(root_dir) geonode_dir = 'geonode' for dirpath, dirnames, filenames in os.walk(geonode_dir): # Ignore dirnames that start with '.' for i, dirname in enumerate(dirnames): if dirname.startswith('.'): del dirnames[i] if '__init__.py' in filenames: packages.append('.'.join(fullsplit(dirpath))) elif filenames: data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]]) setup(name='GeoNode', version=__import__('geonode').get_version(), description="Application for serving and sharing geospatial data", long_description=open('README').read(), classifiers=[ "Development Status :: 4 - Beta"], keywords='', author='GeoNode Developers', author_email='[email protected]', url='http://geonode.org', license='GPL', packages=packages, data_files=data_files, install_requires=[ # native dependencies "pillow", "lxml", # python dependencies "gsconfig==0.6.7", "OWSLib==0.7.2", "Django==1.5.5", # Django Apps "pinax-theme-bootstrap==3.0a11", "pinax-theme-bootstrap-account==1.0b2", "django-user-accounts==1.0b14", "django-forms-bootstrap==2.0.3.post1", "django-pagination==1.0.7", "django-jsonfield==0.9.10", "django-friendly-tag-loader==1.1", "django-taggit==0.10a1", "django-taggit-templatetags", "django-geoexplorer==4.0.2", "django-notification==1.0", "django-announcements==1.0.2", "django-activity-stream==0.4.4", "django-extensions", "user-messages==0.1.1", "geonode-avatar==2.1.1", "dialogos==0.2", "agon-ratings==0.2", "South==0.7.3", "django-downloadview==1.2", #catalogue "pycsw==1.6.1", # setup "Paver", # sample and test data / metadata "gisdata==0.5.4", # testing "django-nose", "nose>=1.0", "beautifulsoup4", "MultipartPostHandler", # translation "transifex-client", ], zip_safe=False, )
gpl-3.0
-922,430,017,735,541,800
32.361345
104
0.602519
false
nion-software/nionswift
nion/swift/model/Model.py
1
14253
"""Description of data model. Reference: https://en.wikipedia.org/wiki/Data_modeling """ from __future__ import annotations import copy import datetime import gettext import typing import uuid from nion.swift.model import Schema _ = gettext.gettext # TODO: description of physical schema # TODO: created and modified should be implicit in all records # TODO: should timezone, timezone offset be implicit? # TODO: some data must be copied on read/write (dict's) # TODO: support external data concept with loaded/unloaded property # TODO: support loaded/unloaded entities? # TODO: support mounted/unmounted entity concept (projects) # TODO: support write delay / transactions # TODO: access to auto proxy items for references # TODO: closing, reading, inserting, removing, modifying, copying, container # TODO: notifying, storage, resolving, moving # TODO: are interval descriptors implicit now? # TODO: display_layers could be a record # TODO: display_properties could be a record # TODO: layout could be a record # TODO: closed_items should be a set of references Calibration = Schema.record({ "offset": Schema.prop(Schema.FLOAT), "scale": Schema.prop(Schema.FLOAT), "units": Schema.prop(Schema.STRING), }) Point = Schema.fixed_tuple([Schema.prop(Schema.FLOAT), Schema.prop(Schema.FLOAT)]) Size = Schema.fixed_tuple([Schema.prop(Schema.FLOAT), Schema.prop(Schema.FLOAT)]) Rect = Schema.fixed_tuple([Point, Size]) Vector = Schema.fixed_tuple([Point, Point]) Interval = Schema.fixed_tuple([Schema.prop(Schema.FLOAT), Schema.prop(Schema.FLOAT)]) DataItem = Schema.entity("data-item", None, 13, { "created": Schema.prop(Schema.TIMESTAMP), "data_shape": Schema.indefinite_tuple(Schema.prop(Schema.INT)), "data_dtype": Schema.prop(Schema.STRING), "is_sequence": Schema.prop(Schema.BOOLEAN), "collection_dimension_count": Schema.prop(Schema.INT), "datum_dimension_count": Schema.prop(Schema.INT), "intensity_calibration": Calibration, "dimensional_calibrations": Schema.array(Calibration), "data_modified": Schema.prop(Schema.TIMESTAMP), "timezone": Schema.prop(Schema.STRING), "timezone_offset": Schema.prop(Schema.STRING), "metadata": Schema.prop(Schema.DICT), "title": Schema.prop(Schema.STRING), "caption": Schema.prop(Schema.STRING), "description": Schema.prop(Schema.STRING), "session_id": Schema.prop(Schema.STRING), "session": Schema.prop(Schema.DICT), "category": Schema.prop(Schema.STRING, default="persistent"), "source": Schema.reference(), }) DataItem.rename("source", "source_uuid") DisplayAdjustment = Schema.entity("display_adjustment", None, None, { }) GammaDisplayAdjustment = Schema.entity("gamma", DisplayAdjustment, None, { "gamma": Schema.prop(Schema.FLOAT), }) LogDisplayAdjustment = Schema.entity("log", DisplayAdjustment, None, { }) EqualizedDisplayAdjustment = Schema.entity("equalized", DisplayAdjustment, None, { }) DisplayDataChannel = Schema.entity("display_data_channel", None, None, { "brightness": Schema.prop(Schema.FLOAT), "contrast": Schema.prop(Schema.FLOAT), "adjustments": Schema.array(Schema.component(DisplayAdjustment)), "complex_display_type": Schema.prop(Schema.STRING), "display_limits": Schema.fixed_tuple([Schema.prop(Schema.FLOAT), Schema.prop(Schema.FLOAT)]), "color_map_id": Schema.prop(Schema.STRING), "sequence_index": Schema.prop(Schema.INT), "collection_index": Schema.indefinite_tuple(Schema.prop(Schema.INT)), "slice_center": Schema.prop(Schema.INT), "slice_width": Schema.prop(Schema.INT), "data_item": Schema.reference(DataItem), }) DisplayDataChannel.rename("data_item", "data_item_reference") DisplayLayer = Schema.entity("display_layer", None, None, { "data_row": Schema.prop(Schema.INT), "stroke_color": Schema.prop(Schema.STRING), "fill_color": Schema.prop(Schema.STRING), "label": Schema.prop(Schema.STRING), "display_data_channel": Schema.reference(DisplayDataChannel), "stroke_width": Schema.prop(Schema.FLOAT), }) Graphic = Schema.entity("graphic", None, None, { "graphic_id": Schema.prop(Schema.STRING), "stroke_color": Schema.prop(Schema.STRING), "fill_color": Schema.prop(Schema.STRING), "label": Schema.prop(Schema.STRING), "is_position_locked": Schema.prop(Schema.BOOLEAN), "is_shape_locked": Schema.prop(Schema.BOOLEAN), "is_bounds_constrained": Schema.prop(Schema.BOOLEAN), "role": Schema.prop(Schema.STRING), "source": Schema.reference(), }) Graphic.rename("source", "source_uuid") Graphic.rename("stroke_color", "color") RectangleTypeGraphic = Schema.entity("rect-type-graphic", Graphic, None, { "bounds": Rect, "rotation": Schema.prop(Schema.FLOAT), }) RectangleGraphic = Schema.entity("rect-graphic", RectangleTypeGraphic, None, {}) EllipseGraphic = Schema.entity("ellipse-graphic", RectangleTypeGraphic, None, {}) LineTypeGraphic = Schema.entity("line-type-graphic", Graphic, None, { "start": Point, "end": Point, "start_arrow_enabled": Schema.prop(Schema.BOOLEAN), "end_arrow_enabled": Schema.prop(Schema.BOOLEAN), }) LineGraphic = Schema.entity("line-graphic", LineTypeGraphic, None, {}) LineProfileGraphic = Schema.entity("line-profile-graphic", LineTypeGraphic, None, { "width": Schema.prop(Schema.FLOAT, default=1.0), "interval_descriptors": Schema.prop(Schema.LIST), }) PointGraphic = Schema.entity("point-graphic", Graphic, None, { "position": Point, }) IntervalGraphic = Schema.entity("interval-graphic", Graphic, None, { "start": Schema.prop(Schema.FLOAT, default=0.0), "end": Schema.prop(Schema.FLOAT, default=1.0), }) ChannelGraphic = Schema.entity("channel-graphic", Graphic, None, { "position": Schema.prop(Schema.FLOAT, default=0.5), }) SpotGraphic = Schema.entity("spot-graphic", Graphic, None, { "bounds": Rect, "rotation": Schema.prop(Schema.FLOAT), }) WedgeGraphic = Schema.entity("wedge-graphic", Graphic, None, { "angle_interval": Interval, }) RingGraphic = Schema.entity("ring-graphic", Graphic, None, { "radius_1": Schema.prop(Schema.FLOAT, default=0.2), "radius_2": Schema.prop(Schema.FLOAT, default=0.4), "mode": Schema.prop(Schema.STRING, default="band-pass"), }) LatticeGraphic = Schema.entity("lattice-graphic", Graphic, None, { "u_pos": Point, "v_pos": Point, "u_count": Schema.prop(Schema.INT, default=1), "v_count": Schema.prop(Schema.INT, default=1), "radius": Schema.prop(Schema.FLOAT, default=0.1), }) DisplayItem = Schema.entity("display_item", None, None, { "created": Schema.prop(Schema.TIMESTAMP), "display_type": Schema.prop(Schema.STRING), "title": Schema.prop(Schema.STRING), "caption": Schema.prop(Schema.STRING), "description": Schema.prop(Schema.STRING), "session_id": Schema.prop(Schema.STRING), "calibration_style_id": Schema.prop(Schema.STRING, default="calibrated"), "display_properties": Schema.prop(Schema.DICT), "display_layers": Schema.array(Schema.component(DisplayLayer)), "graphics": Schema.array(Schema.component(Graphic)), "display_data_channels": Schema.array(Schema.component(DisplayDataChannel)), }) ComputationVariable = Schema.entity("variable", None, None, { "name": Schema.prop(Schema.STRING), "label": Schema.prop(Schema.STRING), "value_type": Schema.prop(Schema.STRING), "value": Schema.prop(Schema.ANY), "value_default": Schema.prop(Schema.ANY), "value_min": Schema.prop(Schema.ANY), "value_max": Schema.prop(Schema.ANY), "item": Schema.reference(), "item2": Schema.reference(), "items": Schema.array(Schema.reference(), Schema.OPTIONAL), "property_name": Schema.prop(Schema.STRING), "control_type": Schema.prop(Schema.STRING), }) ComputationVariable.rename("item", "specifier") ComputationVariable.rename("item2", "secondary_specifier") ComputationVariable.rename("items", "object_specifiers") ComputationResult = Schema.entity("output", None, None, { "name": Schema.prop(Schema.STRING), "label": Schema.prop(Schema.STRING), "item": Schema.reference(), "items": Schema.array(Schema.reference(), Schema.OPTIONAL), }) ComputationResult.rename("item", "specifier") ComputationResult.rename("items", "specifiers") Computation = Schema.entity("computation", None, None, { "source": Schema.reference(), "original_expression": Schema.prop(Schema.STRING), "error_text": Schema.prop(Schema.STRING), "label": Schema.prop(Schema.STRING), "processing_id": Schema.prop(Schema.STRING), "variables": Schema.array(Schema.component(ComputationVariable)), "results": Schema.array(Schema.component(ComputationResult)), }) Computation.rename("source", "source_uuid") DataStructure = Schema.entity("data_structure", None, None, { "source": Schema.reference(), "structure_type": Schema.prop(Schema.STRING), "properties": Schema.prop(Schema.DICT), }) DataStructure.rename("source", "source_uuid") Connection = Schema.entity("connection", None, None, { "parent": Schema.reference(), }) Connection.rename("parent", "parent_uuid") PropertyConnection = Schema.entity("property-connection", Connection, None, { "source": Schema.reference(), "source_property": Schema.prop(Schema.STRING), "target": Schema.reference(), "target_property": Schema.prop(Schema.STRING), }) PropertyConnection.rename("source", "source_uuid") PropertyConnection.rename("target", "target_uuid") IntervalListConnection = Schema.entity("interval-list-connection", Connection, None, { "source": Schema.reference(), "target": Schema.reference(), }) IntervalListConnection.rename("source", "source_uuid") IntervalListConnection.rename("target", "target_uuid") DataGroup = Schema.entity("data_group", None, None, { "title": Schema.prop(Schema.STRING, default=_("Untitled")), "display_items": Schema.array(Schema.component(DisplayItem)), "data_groups": Schema.array(Schema.component("data_group")), }) DataGroup.rename("display_items", "display_item_references") Workspace = Schema.entity("workspace", None, None, { "name": Schema.prop(Schema.STRING), "layout": Schema.prop(Schema.DICT, Schema.OPTIONAL), "workspace_id": Schema.prop(Schema.STRING, Schema.OPTIONAL), }) Project = Schema.entity("project", None, 3, { "title": Schema.prop(Schema.STRING), "data_items": Schema.array(Schema.component(DataItem), Schema.OPTIONAL), "display_items": Schema.array(Schema.component(DisplayItem)), "computations": Schema.array(Schema.component(Computation)), "data_structures": Schema.array(Schema.component(DataStructure)), "connections": Schema.array(Schema.component(Connection)), "data_groups": Schema.array(Schema.component(DataGroup)), "workspaces": Schema.array(Schema.component(Workspace)), "workspace": Schema.reference(Workspace), "data_item_references": Schema.map(Schema.STRING, Schema.reference(DataItem)), "mapped_items": Schema.array(Schema.reference(DataItem), Schema.OPTIONAL), "project_data_folders": Schema.array(Schema.prop(Schema.PATH)), }) Project.rename("workspace", "workspace_uuid") def transform_forward(d: typing.Dict) -> typing.Dict: for display_item in d.get("display_items", list()): display_data_channels = display_item.get("display_data_channels", list()) for display_layer in display_item.get("display_layers", list()): display_layer["type"] = "display_layer" display_layer["uuid"] = str(uuid.uuid4()) display_layer["modified"] = copy.copy(display_item.get("modified", str(datetime.datetime.utcnow()))) data_index = display_layer.pop("data_index", None) if data_index is not None and 0 <= data_index < len(display_data_channels): display_layer["display_data_channel"] = display_data_channels[data_index]["uuid"] return d def transform_backward(d: typing.Dict) -> typing.Dict: for display_item in d.get("display_items", list()): display_data_channels = display_item.get("display_data_channels", list()) display_data_channel_map = {display_data_channel["uuid"]: index for index, display_data_channel in enumerate(display_data_channels)} for display_layer in display_item.get("display_layers", list()): display_layer.pop("type", None) display_layer.pop("uuid", None) display_layer.pop("modified", None) display_data_channel_uuid = display_layer.pop("display_data_channel", None) data_index = display_data_channel_map.get(display_data_channel_uuid, None) if data_index is not None: display_layer["data_index"] = data_index return d Project.transform(transform_forward, transform_backward) ProjectReference = Schema.entity("project_reference", None, None, { "project": Schema.reference(Project), "is_active": Schema.prop(Schema.BOOLEAN), "last_used": Schema.prop(Schema.TIMESTAMP), }) ProjectReference.rename("project", "project_uuid") IndexProjectReference = Schema.entity("project_index", ProjectReference, None, { "project_path": Schema.prop(Schema.PATH), }) FolderProjectReference = Schema.entity("project_folder", ProjectReference, None, { "project_folder_path": Schema.prop(Schema.PATH), }) MemoryProjectReference = Schema.entity("project_memory", ProjectReference, None, { }) ScriptItem = Schema.entity("script_item", None, None, { }) FileScriptItem = Schema.entity("file_script_item", ScriptItem, None, { "path": Schema.prop(Schema.PATH), }) FolderScriptItem = Schema.entity("folder_script_item", ScriptItem, None, { "folder_path": Schema.prop(Schema.PATH), "is_closed": Schema.prop(Schema.BOOLEAN), }) Profile = Schema.entity("profile", None, 2, { "project_references": Schema.array(Schema.component(ProjectReference)), "last_project_reference": Schema.reference(ProjectReference), "work_project": Schema.reference(ProjectReference), "closed_items": Schema.prop(Schema.SET), "script_items": Schema.array(Schema.component(ScriptItem)), }) Profile.rename("target_project", "target_project_reference_uuid") Profile.rename("work_project", "work_project_reference_uuid")
gpl-3.0
-2,147,612,418,482,599,200
36.806366
140
0.704343
false
OriHoch/pysiogame
classes/layout.py
1
5022
class Layout: def __init__(self,mainloop, screen_w, screen_h,x_count=26,y_count=11,game_type="Board"): self.screen_w = screen_w self.screen_h = screen_h self.mainloop = mainloop self.game_type = game_type self.update_layout(x_count,y_count) def update_layout(self,x_count=0,y_count=0): self.mainloop.sb.update_me = True self.x_count = x_count self.y_count = y_count self.score_bar_h = 36 self.menu_w = 166#124 #+5 - extra space to make the gap for tabs to look ok self.menu_a_w = self.menu_w #50+10+50+10+1 self.grid_line_w = 1 self.info_bar_h = 90 #76 self.info_bar_offset_h_init = 80 #76 self.top_margin = self.score_bar_h + self.info_bar_h #self.info_bar_m_top = 10 #margin top - moved to info_bar self.menu_w_offset = 0 self.avail_game_w = self.screen_w - self.menu_w - 10 self.avail_game_h = self.screen_h - self.top_margin #- self.info_bar_h #self.score_bar_h = 0 #32 if self.game_type == "Board": #find the right size (scale) for a single square and calculate panels' sizes scale_x = (self.screen_w - self.menu_w - self.grid_line_w - 6) // x_count scale_y = (self.screen_h - self.grid_line_w-self.top_margin) // y_count if scale_x < scale_y: self.scale = scale_x else: self.scale = scale_y self.menu_w_offset = 0#(self.screen_w - self.menu_w) - self.scale*x_count - self.grid_line_w#(screen_w - menu_w) % x_count #self.game_bg_l = ((self.screen_w - self.menu_w) - self.scale*x_count - self.grid_line_w) self.game_margin = ((self.screen_w - self.menu_w) - self.scale*x_count - self.grid_line_w) // 2 self.game_left = self.menu_w + self.game_margin self.game_right = self.screen_w - self.game_margin self.menu_w_offset = ((self.screen_w - self.menu_w) - self.scale*x_count - self.grid_line_w) // 2 #self.menu_w += self.menu_w_offset self.width = self.scale #width of a single square self.height = self.scale self.game_h = y_count*self.height+self.grid_line_w elif self.game_type == "Puzzle": self.game_h = self.screen_h - self.top_margin #- self.info_bar_h self.game_w = self.scale*x_count# - self.grid_line_w #self.menu_w self.info_bar_offset_h = self.screen_h - self.game_h -self.top_margin self.score_bar_top = 0 #self.info_bar_offset_h - self.info_bar_h - self.top_margin self.menu_pos = (0,0, self.menu_w, self.screen_h) self.menu_l_w = 96 self.menu_r_w = 70 #self.menu_w - self.menu_l_w self.menu_l_pos = (0,0, self.menu_l_w, self.screen_h) self.menu_r_pos = (self.menu_l_w,0, self.menu_r_w, self.screen_h) #self.game_pos = (self.menu_w,0, self.game_w, self.game_h) #changed #self.game_pos = (self.menu_w,self.top_margin, self.game_w, self.game_h) #changed self.game_pos = (self.game_left,self.top_margin, self.game_w, self.game_h) #changed self.misio_pos = (0,0, 166, 146) """ self.info_bar_offset_pos = (self.menu_w - self.menu_w_offset, self.game_h+self.top_margin, self.game_w + self.menu_w_offset, self.info_bar_offset_h) self.info_bar_pos = (1, self.info_bar_offset_h - self.info_bar_h, self.game_w - 1 + self.menu_w_offset, self.info_bar_h) self.score_bar_pos = (self.menu_w - self.menu_w_offset, 0, self.game_w + self.menu_w_offset, self.score_bar_h) self.info_top = self.game_h + self.info_bar_pos[1] + self.top_margin """ #self.info_bar_offset_pos = (self.menu_w, self.game_h+self.top_margin, self.screen_w - self.menu_w, self.info_bar_offset_h) self.info_bar_pos = (self.menu_w, self.top_margin - self.info_bar_h, self.screen_w - self.menu_w, self.info_bar_h) self.score_bar_pos = (self.menu_w, 0, self.screen_w - self.menu_w, self.score_bar_h) self.info_top = self.top_margin - self.info_bar_h #self.game_h + self.info_bar_pos[1] + self.top_margin self.game_bg_pos = (self.menu_w, self.top_margin, self.screen_w - self.menu_w, self.screen_h - self.top_margin) self.dialogwnd_w = 620 self.dialogwnd_h = 400 self.dialogwnd_pos = ((self.screen_w-self.menu_w - self.dialogwnd_w)//2+self.menu_w,(self.screen_h - self.dialogwnd_h)//2,self.dialogwnd_w,self.dialogwnd_h) self.dialogbg_pos = (0,0,self.screen_w,self.screen_h) self.mainloop.redraw_needed = [True, True, True] def draw_layout(self): pass def update_layout_fs(self,screen_w, screen_h,x_count,y_count): #update layout after switching from fullscreen to windowed view self.game_type = self.mainloop.game_board.game_type self.__init__(self.mainloop, screen_w, screen_h,x_count,y_count,self.game_type) #self.mainloop.m.update_scroll_pos()
gpl-3.0
3,021,111,897,255,968,300
49.22
164
0.602748
false
calancha/DIRAC
ResourceStatusSystem/Agent/CacheFeederAgent.py
1
6141
# $HeadURL: $ ''' CacheFeederAgent This agent feeds the Cache tables with the outputs of the cache commands. ''' from DIRAC import S_OK#, S_ERROR, gConfig from DIRAC.AccountingSystem.Client.ReportsClient import ReportsClient from DIRAC.Core.Base.AgentModule import AgentModule from DIRAC.Core.DISET.RPCClient import RPCClient from DIRAC.Core.LCG.GOCDBClient import GOCDBClient from DIRAC.ResourceStatusSystem.Client.ResourceStatusClient import ResourceStatusClient from DIRAC.ResourceStatusSystem.Command import CommandCaller #from DIRAC.ResourceStatusSystem.Utilities import CSHelpers from DIRAC.ResourceStatusSystem.Utilities import Utils ResourceManagementClient = getattr(Utils.voimport( 'DIRAC.ResourceStatusSystem.Client.ResourceManagementClient' ),'ResourceManagementClient') __RCSID__ = '$Id: $' AGENT_NAME = 'ResourceStatus/CacheFeederAgent' class CacheFeederAgent( AgentModule ): ''' The CacheFeederAgent feeds the cache tables for the client and the accounting. It runs periodically a set of commands, and stores it's results on the tables. ''' # Too many public methods # pylint: disable-msg=R0904 def __init__( self, *args, **kwargs ): AgentModule.__init__( self, *args, **kwargs ) self.commands = {} self.clients = {} self.cCaller = None self.rmClient = None def initialize( self ): self.am_setOption( 'shifterProxy', 'DataManager' ) self.rmClient = ResourceManagementClient() self.commands[ 'Downtime' ] = [ { 'Downtime' : {} } ] self.commands[ 'SpaceTokenOccupancy' ] = [ { 'SpaceTokenOccupancy' : {} } ] #PilotsCommand # self.commands[ 'Pilots' ] = [ # { 'PilotsWMS' : { 'element' : 'Site', 'siteName' : None } }, # { 'PilotsWMS' : { 'element' : 'Resource', 'siteName' : None } } # ] #FIXME: do not forget about hourly vs Always ...etc #AccountingCacheCommand # self.commands[ 'AccountingCache' ] = [ # {'SuccessfullJobsBySiteSplitted' :{'hours' :24, 'plotType' :'Job' }}, # {'FailedJobsBySiteSplitted' :{'hours' :24, 'plotType' :'Job' }}, # {'SuccessfullPilotsBySiteSplitted' :{'hours' :24, 'plotType' :'Pilot' }}, # {'FailedPilotsBySiteSplitted' :{'hours' :24, 'plotType' :'Pilot' }}, # {'SuccessfullPilotsByCESplitted' :{'hours' :24, 'plotType' :'Pilot' }}, # {'FailedPilotsByCESplitted' :{'hours' :24, 'plotType' :'Pilot' }}, # {'RunningJobsBySiteSplitted' :{'hours' :24, 'plotType' :'Job' }}, ## {'RunningJobsBySiteSplitted' :{'hours' :168, 'plotType' :'Job' }}, ## {'RunningJobsBySiteSplitted' :{'hours' :720, 'plotType' :'Job' }}, ## {'RunningJobsBySiteSplitted' :{'hours' :8760, 'plotType' :'Job' }}, # ] #VOBOXAvailability # self.commands[ 'VOBOXAvailability' ] = [ # { 'VOBOXAvailability' : {} } # #Reuse clients for the commands self.clients[ 'GOCDBClient' ] = GOCDBClient() self.clients[ 'ReportGenerator' ] = RPCClient( 'Accounting/ReportGenerator' ) self.clients[ 'ReportsClient' ] = ReportsClient() self.clients[ 'ResourceStatusClient' ] = ResourceStatusClient() self.clients[ 'ResourceManagementClient' ] = ResourceManagementClient() self.clients[ 'WMSAdministrator' ] = RPCClient( 'WorkloadManagement/WMSAdministrator' ) self.cCaller = CommandCaller return S_OK() def loadCommand( self, commandModule, commandDict ): commandName = commandDict.keys()[ 0 ] commandArgs = commandDict[ commandName ] commandTuple = ( '%sCommand' % commandModule, '%sCommand' % commandName ) commandObject = self.cCaller.commandInvocation( commandTuple, pArgs = commandArgs, clients = self.clients ) if not commandObject[ 'OK' ]: self.log.error( 'Error initializing %s' % commandName ) return commandObject commandObject = commandObject[ 'Value' ] # Set master mode commandObject.masterMode = True self.log.info( '%s/%s' % ( commandModule, commandName ) ) return S_OK( commandObject ) def execute( self ): for commandModule, commandList in self.commands.items(): self.log.info( '%s module initialization' % commandModule ) for commandDict in commandList: commandObject = self.loadCommand( commandModule, commandDict ) if not commandObject[ 'OK' ]: self.log.error( commandObject[ 'Message' ] ) continue commandObject = commandObject[ 'Value' ] results = commandObject.doCommand() if not results[ 'OK' ]: self.log.error( results[ 'Message' ] ) continue results = results[ 'Value' ] if not results: self.log.info( 'Empty results' ) continue self.log.verbose( 'Command OK Results' ) self.log.verbose( results ) return S_OK() ################################################################################ #EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
gpl-3.0
-431,948,442,126,667,650
41.645833
141
0.528741
false
Mo-Talha/Nomad
data/analysis/importer.py
1
16902
import re from datetime import datetime from dateutil.relativedelta import relativedelta import engine import data.search.elastic as elastic from models.exceptions import DataIntegrityError from models.employer import Employer from models.job import Job from models.applicant import Applicant from models.location import Location from models.comment import Comment from models.job_keyword import Keyword from models.rating import AggregateRating import models.term as Term import models.program as Program import models.employer_alias as employer_alias import shared.logger as logger COMPONENT = 'Importer' def import_job(**kwargs): """Import job. Keyword arguments: employer_name -- Employer name job_title -- Title of job summary -- Job summary year -- Year the job was advertised term -- Term job was advertised [Fall, Winter, Spring] location -- Location job was advertised openings -- Number of job openings remaining -- Number of job openings remaining applicants -- Number of applicants job has (Optional) levels -- Levels job is intended for [Junior, Intermediate, Senior] programs -- Programs the job is specified for url -- URL of job date -- Date job was crawled (useful for knowing exactly # of applicants at what time) index -- Boolean to indicate whether to index or not (default True) """ employer_name = kwargs['employer_name'].lower() job_title = kwargs['job_title'].lower() term = kwargs['term'] levels = [] for level in kwargs['levels']: uw_level = Term.get_level(level) if uw_level: levels.append(uw_level) else: logger.error(COMPONENT, 'Error processing level: {}'.format(level)) programs = [] for program in kwargs['programs']: uw_program = Program.get_program(program) if uw_program: programs.append(uw_program) else: logger.error(COMPONENT, 'Error processing program: {}'.format(program)) location = kwargs['location'].lower() openings = int(kwargs['openings']) remaining = int(kwargs['remaining']) if 'remaining' in kwargs else openings summary = kwargs['summary'] filtered_summary = engine.filter_summary(summary) summary_keywords = engine.get_keywords(filtered_summary, programs) date = kwargs['date'] year = date.year url = kwargs['url'] applicants = 0 try: if kwargs['applicants']: applicants = int(kwargs['applicants']) except Exception: pass index = False if index in kwargs: index = kwargs['index'] logger.info(COMPONENT, 'Importing job: {} from {}'.format(job_title, employer_name)) # If employer does not exist, create it if not Employer.employer_exists(employer_name): logger.info(COMPONENT, 'Employer: {} does not exist, creating..'.format(employer_name)) employer = Employer(name=employer_name) logger.info(COMPONENT, 'Creating job: {}'.format(job_title)) location = Location(name=location) applicant = Applicant(applicants=applicants, date=date) keywords = [Keyword(keyword=k['keyword'], types=k['types']) for k in summary_keywords] # New job so number of remaining positions is same as openings job = Job(title=job_title, summary=filtered_summary, year=year, term=term, location=[location], openings=openings, remaining=remaining, applicants=[applicant], levels=levels, programs=programs, url=url, keywords=keywords) job.save() job.reload() employer.jobs.append(job) employer.save() employer.reload() if index: elastic.index_employer_waterlooworks(employer) elastic.index_job_waterlooworks(employer, job) # Employer already exists else: employer = Employer.objects(name=employer_name).no_dereference().first() logger.info(COMPONENT, 'Employer: {} already exists'.format(employer_name)) # If job does not exist, create it if not employer.job_exists(job_title): logger.info(COMPONENT, 'Creating job: {}'.format(job_title)) location = Location(name=location) applicant = Applicant(applicants=applicants, date=date) keywords = [Keyword(keyword=k['keyword'], types=k['types']) for k in summary_keywords] # New job so number of remaining positions is same as openings job = Job(title=job_title, summary=engine.filter_summary(summary), year=year, term=term, location=[location], openings=openings, remaining=remaining, applicants=[applicant], levels=levels, programs=programs, url=url, keywords=keywords) job.save() job.reload() employer.update(push__jobs=job) if index: elastic.update_employer_waterlooworks(employer) elastic.index_job_waterlooworks(employer, job) # Job already exists else: logger.info(COMPONENT, 'Job: {} already exists'.format(job_title)) job = Job.objects(id__in=[job.id for job in employer.jobs], title=job_title).first() if not year >= job.year: raise DataIntegrityError('Job: {} by {} cannot be advertised before {}' .format(job_title, employer_name, job.year)) filtered_summary_compare = re.sub(r'\W+', '', filtered_summary.lower().strip()).strip() job_summary_compare = re.sub(r'\W+', '', job.summary.lower().strip()).strip() # Job summary is not the same. In this case the employer most likely changed the job if not filtered_summary_compare == job_summary_compare: if openings >= 1: logger.info(COMPONENT, 'Job: {}: different summary detected, deprecating and creating new job..' .format(job_title)) job.update(set__deprecated=True) location = Location(name=location) applicant = Applicant(applicants=applicants, date=date) keywords = [Keyword(keyword=k['keyword'], types=k['types']) for k in summary_keywords] # Assume new job so number of remaining positions is same as openings new_job = Job(title=job_title, summary=filtered_summary, year=year, term=term, location=[location], openings=openings, remaining=remaining, applicants=[applicant], levels=levels, programs=programs, url=url, keywords=keywords) new_job.save() new_job.reload() employer.update(push__jobs=new_job) if index: elastic.delete_employer_waterlooworks(employer) elastic.delete_job_waterlooworks(employer, job) elastic.index_employer_waterlooworks(employer) elastic.index_job_waterlooworks(employer, new_job) else: logger.info(COMPONENT, 'Job: {}: different summary detected but invalid openings: {}, ignoring..' .format(job_title, openings)) # Job is the same (same title and description) else: # If job is being advertised in new term if year != job.year or term != job.term: logger.info(COMPONENT, 'Job: {}: being advertised in new term, updating..'.format(job_title)) # Add hire ratio for previous term hire_ratio = float(job.openings - job.remaining) / job.openings job.hire_rate.add_rating(hire_ratio) location = Location(name=location) applicant = Applicant(applicants=applicants, date=date) hire_rate = AggregateRating(rating=job.hire_rate.rating, count=job.hire_rate.count) job.update(set__year=year, set__term=term, add_to_set__location=location, set__openings=openings, set__remaining=remaining, push__applicants=applicant, set__hire_rate=hire_rate, set__levels=levels, set__programs=programs, set__url=url, set__last_indexed=datetime.now()) if index: elastic.update_job_waterlooworks(employer, job) # Job is being updated. We need to update location, openings, levels, remaining, hire_rate, applicants else: logger.info(COMPONENT, 'Job: {}: updating for current term'.format(job_title)) remaining = job.remaining # Job posting has decreased, some positions filled up if openings < remaining: remaining = openings location = Location(name=location) applicant = Applicant(applicants=applicants, date=date) job.update(add_to_set__location=location, set__remaining=remaining, set__levels=list(set(levels + job.levels)), push__applicants=applicant, set__programs=list(set(programs + job.programs)), set__url=url, set__last_indexed=datetime.now()) if index: elastic.update_job_waterlooworks(employer, job) def update_job(**kwargs): """Update job. Keyword arguments: id -- Job ID summary -- Job summary location -- Location job was advertised programs -- Programs the job is specified for levels -- Levels job is intended for [Junior, Intermediate, Senior] openings -- Number of job openings index -- Boolean to indicate whether to index or not (default True) """ summary = kwargs['summary'] location = kwargs['location'].lower() levels = kwargs['levels'] programs = [] for program in kwargs['programs']: uw_program = Program.get_program(program) if uw_program: programs.append(uw_program) else: logger.error(COMPONENT, 'Error processing program: {}'.format(program)) openings = 0 try: if kwargs['openings']: openings = int(kwargs['openings']) or 0 except Exception: pass index = False if index in kwargs: index = kwargs['index'] job = Job.objects(id=kwargs['id']).first() remaining = job.openings # Job posting has decreased, some positions filled up if openings < job.openings: remaining = openings filtered_summary = engine.filter_summary(summary) summary_keywords = engine.get_keywords(filtered_summary, programs) filtered_summary_compare = re.sub(r'\W+', '', filtered_summary.lower().strip()).strip() job_summary_compare = re.sub(r'\W+', '', job.summary.lower().strip()).strip() employer = Employer.objects(jobs=kwargs['id']).first() # Job summary is not the same. In this case the employer most likely changed the job if not filtered_summary_compare == job_summary_compare: if openings >= 1: logger.info(COMPONENT, 'Job: {}: different summary detected, deprecating and creating new job..' .format(kwargs['id'])) job.update(set__deprecated=True) location = Location(name=location) keywords = [Keyword(keyword=k['keyword'], types=k['types']) for k in summary_keywords] # Assume new job so number of remaining positions is same as openings new_job = Job(title=job.title, summary=filtered_summary, year=job.year, term=job.term, location=[location], openings=openings, remaining=openings, levels=levels, programs=programs, url=job.url, keywords=keywords) new_job.save() employer.update(push__jobs=new_job) if index: elastic.delete_employer_waterlooworks(employer) elastic.delete_job_waterlooworks(employer, job) elastic.index_employer_waterlooworks(employer) elastic.index_job_waterlooworks(employer, new_job) else: logger.info(COMPONENT, 'Job: {}: different summary detected but invalid openings: {}, ignoring..' .format(job.title, openings)) else: logger.info(COMPONENT, 'Job: {}: updating for current term'.format(kwargs['id'])) location = Location(name=location) job.update(add_to_set__location=location, set__remaining=remaining, set__levels=list(set(levels + job.levels)), set__programs=list(set(programs + job.programs)), set__last_indexed=datetime.now()) if index: elastic.update_job_waterlooworks(employer, job) def import_comment(**kwargs): """Import comment from RateMyCoopJob. Keyword arguments: employer_name -- Employer name job_title -- Title of job comments: -- Array of comments comment -- Comment comment_date -- Date comment was submitted. Note: in non-standard form such as: 5 years ago, 3 weeks ago etc salary -- Job salary (hourly) rating -- Job rating out of 5 (1 - 5 stars on ratemycoopjob) """ employer_name = kwargs['employer_name'].lower() job_title = kwargs['job_title'].lower() # If employer alias exists (ex. Research in motion -> Blackberry), use instead if employer_name in employer_alias.aliases: employer_name = employer_alias.aliases[employer_name].lower() # If employer does not exist if not Employer.objects.search_text("\"{}\"".format(employer_name)).count() > 0: logger.info(COMPONENT, 'Employer: {} does not exist, ignoring..'.format(employer_name)) return logger.info(COMPONENT, 'Importing comments for job: {} from employer: {}'.format(job_title, employer_name)) employer = Employer.objects.search_text("\"{}\"".format(employer_name)).no_dereference().first() # Iterate through all comments for index, comment_obj in enumerate(kwargs['comments']): comment = comment_obj['comment'] comment_date = _get_comment_date(comment_obj['comment_date']) salary = float(comment_obj['salary']) rating = float(comment_obj['rating']) / 5 # If job does not exist add to employer if not employer.job_exists(job_title): if employer.comment_exists(comment=comment, date=comment_date, salary=salary, rating=rating): logger.info(COMPONENT, 'Comment: {} already exists for employer: {}, ignoring' .format(index, employer_name)) else: logger.info(COMPONENT, 'Adding comment: {} to employer: {}'.format(index, employer_name)) new_comment = Comment(comment=comment, date=comment_date, salary=salary, crawled=True, rating=AggregateRating(rating=rating, count=1)) employer.update(push__comments=new_comment) # Job already exists else: job = Job.objects(id__in=[job.id for job in employer.jobs], title=job_title).first() if job.comment_exists(comment=comment, date=comment_date, salary=salary, rating=rating): logger.info(COMPONENT, 'Comment: {} already exists for job: {} for employer: {}, ignoring' .format(index, job_title, employer_name)) else: logger.info(COMPONENT, 'Adding comment: {} for job: {} from {}'.format(index, job_title, employer_name)) new_comment = Comment(comment=comment, date=comment_date, salary=salary, crawled=True, rating=AggregateRating(rating=rating, count=1)) job.update(push__comments=new_comment) def _get_comment_date(date_str): now = datetime.now() date = datetime(now.year, now.month, now.day) date_re = re.search(r'(\d+)\s(month[s]?|year[s]?|day[s]?)', date_str) # Ex. for 5 days ago, date_num = 5 date_num = int(date_re.group(1)) # Ex. for 5 days ago, date_time = days date_time = date_re.group(2) if 'day' in date_time: if date_num < 1: date_num = 1 date -= relativedelta(days=date_num) elif 'month' in date_time: if date_num < 1: date_num = 1 date -= relativedelta(months=date_num) elif 'year' in date_time: date -= relativedelta(years=date_num) return date
mit
-3,097,911,385,798,250,000
35.663774
122
0.601941
false
brennv/pyArango
pyArango/index.py
1
1497
import json from .theExceptions import (CreationError, DeletionError, UpdateError) class Index(object) : """An index on a collection's fields. Indexes are meant to de created by ensureXXX functions of Collections. Indexes have a .infos dictionary that stores all the infos about the index""" def __init__(self, collection, infos = None, creationData = None) : self.collection = collection self.connection = self.collection.database.connection self.indexesURL = "%s/index" % self.collection.database.URL self.infos = None if infos : self.infos = infos elif creationData : self._create(creationData) if self.infos : self.URL = "%s/%s" % (self.indexesURL, self.infos["id"]) def _create(self, postData) : """Creates an index of any type according to postData""" if self.infos is None : r = self.connection.session.post(self.indexesURL, params = {"collection" : self.collection.name}, data = json.dumps(postData)) data = r.json() if (r.status_code >= 400) or data['error'] : raise CreationError(data['errorMessage'], data) self.infos = data def delete(self) : """Delete the index""" r = self.connection.session.delete(self.URL) data = r.json() if (r.status_code != 200 and r.status_code != 202) or data['error'] : raise DeletionError(data['errorMessage'], data)
apache-2.0
3,545,663,154,695,710,700
40.583333
138
0.61857
false
a3qz/networked_platformer
board.py
1
1909
import spikes import wall import constants import collectable import data class Board: def __init__(self, game): self.xsize = 10000 self.ysize = constants.HEIGHT self.game = game # create a reference dict for the parser based off of the json dicts of cards + the wall and spikes self.ref = { 0: wall.Wall, 1: spikes.Spike } for i in data.num_as_key: self.ref[int(i)] = collectable.Collectable # failsafe walls for i in range(0, self.ysize, 32): wall.Wall(game, i, constants.HEIGHT-32, 0) # interpret a file def parse(self, name): #first delete all spike and wall objects self.game.objects = [o for o in self.game.objects if (not isinstance(o, wall.Terrain)) and (not isinstance(o, collectable.Collectable))] #iterate through the file and separate into [type, xcoord, ycoord] with open(name) as f: for l in f: d = [int(x) for x in l.split()] # find the item in the reference dictionary and call its constructor self.ref[d[0]](self.game, d[1], d[2], d[0]) # create the "bottom" of the level, where the player dies self.game.deathzone = max([o.rect.y for o in self.game.objects if isinstance(o, wall.Wall)]) + 200 def save(self, name): #first delete all spike and wall objects d = ['{} {} {}\n'.format(o.descriptor, o.rect.centerx, o.rect.centery) for o in self.game.objects if (isinstance(o, wall.Terrain)) or (isinstance(o, collectable.Collectable))] #writes lines to the temp file with open(name, 'w') as f: f.writelines(d)
gpl-3.0
3,744,833,302,310,442,000
37.959184
107
0.542169
false
blundeln/pylens
pylens/settings.py
1
2094
# # Copyright (c) 2010-2011, Nick Blundell # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of Nick Blundell nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # # # Author: Nick Blundell <blundeln [AT] gmail [DOT] com> # Organisation: www.nickblundell.org.uk # # Description: # # class GlobalSettings: """ These are some global settings that affect the functionality of the framework. """ """ Check that the (outer most) lens fully consumes the input string and that containers are fully consumed in the PUT direction, where is possible to know such a thing. You might wish to set this to False when developing or debugging your own lenses. """ check_consumption = True
bsd-3-clause
-1,643,515,080,644,396,000
42.625
83
0.754537
false
deepfield/ibis
ibis/impala/api.py
1
3847
from ibis.impala.client import (ImpalaConnection, # noqa: F401 ImpalaClient, ImpalaDatabase, ImpalaTable) from ibis.impala.compiler import dialect # noqa: F401 from ibis.impala.udf import * # noqa: F401,F403 from ibis.config import options import ibis.common as com def compile(expr, params=None): """ Force compilation of expression as though it were an expression depending on Impala. Note you can also call expr.compile() Returns ------- compiled : string """ from ibis.impala.compiler import to_sql return to_sql(expr, dialect.make_context(params=params)) def verify(expr, params=None): """ Determine if expression can be successfully translated to execute on Impala """ try: compile(expr, params=params) return True except com.TranslationError: return False def connect(host='localhost', port=21050, database='default', timeout=45, use_ssl=False, ca_cert=None, user=None, password=None, auth_mechanism='NOSASL', kerberos_service_name='impala', pool_size=8, hdfs_client=None): """Create an ImpalaClient for use with Ibis. Parameters ---------- host : str, optional Host name of the impalad or HiveServer2 in Hive port : int, optional Impala's HiveServer2 port database : str, optional Default database when obtaining new cursors timeout : int, optional Connection timeout in seconds when communicating with HiveServer2 use_ssl : bool, optional Use SSL when connecting to HiveServer2 ca_cert : str, optional Local path to 3rd party CA certificate or copy of server certificate for self-signed certificates. If SSL is enabled, but this argument is ``None``, then certificate validation is skipped. user : str, optional LDAP user to authenticate password : str, optional LDAP password to authenticate auth_mechanism : str, optional {'NOSASL' <- default, 'PLAIN', 'GSSAPI', 'LDAP'}. Use NOSASL for non-secured Impala connections. Use PLAIN for non-secured Hive clusters. Use LDAP for LDAP authenticated connections. Use GSSAPI for Kerberos-secured clusters. kerberos_service_name : str, optional Specify particular impalad service principal. Examples -------- >>> import ibis >>> import os >>> hdfs_host = os.environ.get('IBIS_TEST_NN_HOST', 'localhost') >>> hdfs_port = int(os.environ.get('IBIS_TEST_NN_PORT', 50070)) >>> impala_host = os.environ.get('IBIS_TEST_IMPALA_HOST', 'localhost') >>> impala_port = int(os.environ.get('IBIS_TEST_IMPALA_PORT', 21050)) >>> hdfs = ibis.hdfs_connect(host=hdfs_host, port=hdfs_port) >>> hdfs # doctest: +ELLIPSIS <ibis.filesystems.WebHDFS object at 0x...> >>> client = ibis.impala.connect( ... host=impala_host, ... port=impala_port, ... hdfs_client=hdfs, ... ) >>> client # doctest: +ELLIPSIS <ibis.impala.client.ImpalaClient object at 0x...> Returns ------- ImpalaClient """ params = { 'host': host, 'port': port, 'database': database, 'timeout': timeout, 'use_ssl': use_ssl, 'ca_cert': ca_cert, 'user': user, 'password': password, 'auth_mechanism': auth_mechanism, 'kerberos_service_name': kerberos_service_name } con = ImpalaConnection(pool_size=pool_size, **params) try: client = ImpalaClient(con, hdfs_client=hdfs_client) except Exception: con.close() raise else: if options.default_backend is None: options.default_backend = client return client
apache-2.0
-1,175,559,354,645,159,200
32.452174
79
0.621263
false
grengojbo/st2
st2client/st2client/commands/action.py
1
41136
# Licensed to the StackStorm, Inc ('StackStorm') 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 os import ast import copy import json import logging import textwrap import time import six import sys from os.path import join as pjoin from st2client import models from st2client.commands import resource from st2client.commands.resource import add_auth_token_to_kwargs_from_cli from st2client.exceptions.operations import OperationFailureException from st2client.formatters import table from st2client.formatters import execution as execution_formatter from st2client.utils import jsutil from st2client.utils.date import format_isodate from st2client.utils.color import format_status LOG = logging.getLogger(__name__) LIVEACTION_STATUS_REQUESTED = 'requested' LIVEACTION_STATUS_SCHEDULED = 'scheduled' LIVEACTION_STATUS_RUNNING = 'running' LIVEACTION_STATUS_CANCELED = 'canceled' # Who parameters should be masked when displaying action execution output PARAMETERS_TO_MASK = [ 'password', 'private_key' ] # A list of environment variables which are never inherited when using run # --inherit-env flag ENV_VARS_BLACKLIST = [ 'pwd', 'mail', 'username', 'user', 'path', 'home', 'ps1', 'shell', 'pythonpath', 'ssh_tty', 'ssh_connection', 'lang', 'ls_colors', 'logname', 'oldpwd', 'term', 'xdg_session_id' ] WORKFLOW_RUNNER_TYPES = [ 'action-chain', 'mistral-v2', ] def format_parameters(value): # Mask sensitive parameters if not isinstance(value, dict): # No parameters, leave it as it is return value for param_name, _ in value.items(): if param_name in PARAMETERS_TO_MASK: value[param_name] = '********' return value # String for indenting etc. WF_PREFIX = '+ ' NON_WF_PREFIX = ' ' INDENT_CHAR = ' ' def format_wf_instances(instances): """ Adds identification characters to a workflow and appropriately shifts the non-workflow instances. If no workflows are found does nothing. """ # only add extr chars if there are workflows. has_wf = False for instance in instances: if not getattr(instance, 'children', None): continue else: has_wf = True break if not has_wf: return instances # Prepend wf and non_wf prefixes. for instance in instances: if getattr(instance, 'children', None): instance.id = WF_PREFIX + instance.id else: instance.id = NON_WF_PREFIX + instance.id return instances class ActionBranch(resource.ResourceBranch): def __init__(self, description, app, subparsers, parent_parser=None): super(ActionBranch, self).__init__( models.Action, description, app, subparsers, parent_parser=parent_parser, commands={ 'list': ActionListCommand, 'get': ActionGetCommand, 'update': ActionUpdateCommand, 'delete': ActionDeleteCommand }) # Registers extended commands self.commands['execute'] = ActionRunCommand( self.resource, self.app, self.subparsers, add_help=False) class ActionListCommand(resource.ContentPackResourceListCommand): display_attributes = ['ref', 'pack', 'name', 'description'] class ActionGetCommand(resource.ContentPackResourceGetCommand): display_attributes = ['all'] attribute_display_order = ['id', 'ref', 'pack', 'name', 'description', 'enabled', 'entry_point', 'runner_type', 'parameters'] class ActionUpdateCommand(resource.ContentPackResourceUpdateCommand): pass class ActionDeleteCommand(resource.ContentPackResourceDeleteCommand): pass class ActionRunCommandMixin(object): """ Mixin class which contains utility functions related to action execution. """ display_attributes = ['id', 'action.ref', 'context.user', 'parameters', 'status', 'start_timestamp', 'end_timestamp', 'result'] attribute_display_order = ['id', 'action.ref', 'context.user', 'parameters', 'status', 'start_timestamp', 'end_timestamp', 'result'] attribute_transform_functions = { 'start_timestamp': format_isodate, 'end_timestamp': format_isodate, 'parameters': format_parameters, 'status': format_status } poll_interval = 2 # how often to poll for execution completion when using sync mode def get_resource(self, ref_or_id, **kwargs): return self.get_resource_by_ref_or_id(ref_or_id=ref_or_id, **kwargs) @add_auth_token_to_kwargs_from_cli def run_and_print(self, args, **kwargs): if self._print_help(args, **kwargs): return execution = self.run(args, **kwargs) if args.async: self.print_output('To get the results, execute:\n st2 execution get %s' % (execution.id), six.text_type) else: return self._print_execution_details(execution=execution, args=args, **kwargs) def _add_common_options(self): root_arg_grp = self.parser.add_mutually_exclusive_group() # Display options task_list_arg_grp = root_arg_grp.add_argument_group() task_list_arg_grp.add_argument('--raw', action='store_true', help='Raw output, don\'t shot sub-tasks for workflows.') task_list_arg_grp.add_argument('--tasks', action='store_true', help='Whether to show sub-tasks of an execution.') task_list_arg_grp.add_argument('--depth', type=int, default=-1, help='Depth to which to show sub-tasks. \ By default all are shown.') task_list_arg_grp.add_argument('-w', '--width', nargs='+', type=int, default=None, help='Set the width of columns in output.') execution_details_arg_grp = root_arg_grp.add_mutually_exclusive_group() detail_arg_grp = execution_details_arg_grp.add_mutually_exclusive_group() detail_arg_grp.add_argument('--attr', nargs='+', default=['id', 'status', 'result'], help=('List of attributes to include in the ' 'output. "all" or unspecified will ' 'return all attributes.')) detail_arg_grp.add_argument('-d', '--detail', action='store_true', help='Display full detail of the execution in table format.') result_arg_grp = execution_details_arg_grp.add_mutually_exclusive_group() result_arg_grp.add_argument('-k', '--key', help=('If result is type of JSON, then print specific ' 'key-value pair; dot notation for nested JSON is ' 'supported.')) return root_arg_grp def _print_execution_details(self, execution, args, **kwargs): """ Print the execution detail to stdout. This method takes into account if an executed action was workflow or not and formats the output accordingly. """ runner_type = execution.action.get('runner_type', 'unknown') is_workflow_action = runner_type in WORKFLOW_RUNNER_TYPES tasks = getattr(args, 'tasks', False) raw = getattr(args, 'raw', False) detail = getattr(args, 'detail', False) key = getattr(args, 'key', None) attr = getattr(args, 'attr', []) if tasks and not is_workflow_action: raise ValueError('--tasks option can only be used with workflow actions') if not raw and not detail and (tasks or is_workflow_action): self._run_and_print_child_task_list(execution=execution, args=args, **kwargs) else: instance = execution if detail: formatter = table.PropertyValueTable else: formatter = execution_formatter.ExecutionResult if detail: options = {'attributes': copy.copy(self.display_attributes)} elif key: options = {'attributes': ['result.%s' % (key)], 'key': key} else: options = {'attributes': attr} options['json'] = args.json options['attribute_transform_functions'] = self.attribute_transform_functions self.print_output(instance, formatter, **options) def _run_and_print_child_task_list(self, execution, args, **kwargs): action_exec_mgr = self.app.client.managers['LiveAction'] instance = execution options = {'attributes': ['id', 'action.ref', 'status', 'start_timestamp', 'end_timestamp']} options['json'] = args.json options['attribute_transform_functions'] = self.attribute_transform_functions formatter = execution_formatter.ExecutionResult kwargs['depth'] = args.depth child_instances = action_exec_mgr.get_property(execution.id, 'children', **kwargs) child_instances = self._format_child_instances(child_instances, execution.id) if not child_instances: # No child error, there might be a global error, include result in the output options['attributes'].append('result') # On failure we also want to include error message and traceback at the top level if instance.status == 'failed': status_index = options['attributes'].index('status') if isinstance(instance.result, dict): tasks = instance.result.get('tasks', []) else: tasks = [] top_level_error, top_level_traceback = self._get_top_level_error(live_action=instance) if len(tasks) >= 1: task_error, task_traceback = self._get_task_error(task=tasks[-1]) else: task_error, task_traceback = None, None if top_level_error: # Top-level error instance.error = top_level_error instance.traceback = top_level_traceback options['attributes'].insert(status_index + 1, 'error') options['attributes'].insert(status_index + 2, 'traceback') elif task_error: # Task error instance.error = task_error instance.traceback = task_traceback instance.failed_on = tasks[-1].get('name', 'unknown') options['attributes'].insert(status_index + 1, 'error') options['attributes'].insert(status_index + 2, 'traceback') options['attributes'].insert(status_index + 3, 'failed_on') # print root task self.print_output(instance, formatter, **options) # print child tasks if child_instances: self.print_output(child_instances, table.MultiColumnTable, attributes=['id', 'status', 'task', 'action', 'start_timestamp'], widths=args.width, json=args.json, attribute_transform_functions=self.attribute_transform_functions) def _get_execution_result(self, execution, action_exec_mgr, args, **kwargs): pending_statuses = [ LIVEACTION_STATUS_REQUESTED, LIVEACTION_STATUS_SCHEDULED, LIVEACTION_STATUS_RUNNING ] if not args.async: while execution.status in pending_statuses: time.sleep(self.poll_interval) if not args.json: sys.stdout.write('.') sys.stdout.flush() execution = action_exec_mgr.get_by_id(execution.id, **kwargs) sys.stdout.write('\n') if execution.status == 'LIVEACTION_STATUS_CANCELED': return execution if self._is_error_result(result=execution.result): execution.result = self._format_error_result(execution.result) return execution def _get_top_level_error(self, live_action): """ Retrieve a top level workflow error. :return: (error, traceback) """ if isinstance(live_action.result, dict): error = live_action.result.get('error', None) traceback = live_action.result.get('traceback', None) else: error = "See result" traceback = "See result" return error, traceback def _get_task_error(self, task): """ Retrieve error message from the provided task. :return: (error, traceback) """ if not task: return None, None result = task['result'] if isinstance(result, dict): stderr = result.get('stderr', None) error = result.get('error', None) traceback = result.get('traceback', None) error = error if error else stderr else: stderr = None error = None traceback = None return error, traceback def _is_error_result(self, result): if not isinstance(result, dict): return False if 'message' not in result: return False if 'traceback' not in result: return False return True def _format_error_result(self, result): result = 'Message: %s\nTraceback: %s' % (result['message'], result['traceback']) return result def _get_action_parameters_from_args(self, action, runner, args): """ Build a dictionary with parameters which will be passed to the action by parsing parameters passed to the CLI. :param args: CLI argument. :type args: ``object`` :rtype: ``dict`` """ action_ref_or_id = action.ref def read_file(file_path): if not os.path.exists(file_path): raise ValueError('File "%s" doesn\'t exist' % (file_path)) if not os.path.isfile(file_path): raise ValueError('"%s" is not a file' % (file_path)) with open(file_path, 'rb') as fp: content = fp.read() return content def transform_object(value): # Also support simple key1=val1,key2=val2 syntax if value.startswith('{'): # Assume it's JSON result = value = json.loads(value) else: pairs = value.split(',') result = {} for pair in pairs: split = pair.split('=', 1) if len(split) != 2: continue key, value = split result[key] = value return result transformer = { 'array': (lambda cs_x: [v.strip() for v in cs_x.split(',')]), 'boolean': (lambda x: ast.literal_eval(x.capitalize())), 'integer': int, 'number': float, 'object': transform_object, 'string': str } def normalize(name, value): if name in runner.runner_parameters: param = runner.runner_parameters[name] if 'type' in param and param['type'] in transformer: return transformer[param['type']](value) if name in action.parameters: param = action.parameters[name] if 'type' in param and param['type'] in transformer: return transformer[param['type']](value) return value result = {} for idx in range(len(args.parameters)): arg = args.parameters[idx] if '=' in arg: k, v = arg.split('=', 1) # Attribute for files are prefixed with "@" if k.startswith('@'): k = k[1:] is_file = True else: is_file = False try: if is_file: # Files are handled a bit differently since we ship the content # over the wire file_path = os.path.normpath(pjoin(os.getcwd(), v)) file_name = os.path.basename(file_path) content = read_file(file_path=file_path) if action_ref_or_id == 'core.http': # Special case for http runner result['_file_name'] = file_name result['file_content'] = content else: result[k] = content else: result[k] = normalize(k, v) except Exception as e: # TODO: Move transformers in a separate module and handle # exceptions there if 'malformed string' in str(e): message = ('Invalid value for boolean parameter. ' 'Valid values are: true, false') raise ValueError(message) else: raise e else: result['cmd'] = ' '.join(args.parameters[idx:]) break # Special case for http runner if 'file_content' in result: if 'method' not in result: # Default to POST if a method is not provided result['method'] = 'POST' if 'file_name' not in result: # File name not provided, use default file name result['file_name'] = result['_file_name'] del result['_file_name'] if args.inherit_env: result['env'] = self._get_inherited_env_vars() return result @add_auth_token_to_kwargs_from_cli def _print_help(self, args, **kwargs): # Print appropriate help message if the help option is given. action_mgr = self.app.client.managers['Action'] action_exec_mgr = self.app.client.managers['LiveAction'] if args.help: action_ref_or_id = getattr(args, 'ref_or_id', None) action_exec_id = getattr(args, 'id', None) if action_exec_id and not action_ref_or_id: action_exec = action_exec_mgr.get_by_id(action_exec_id, **kwargs) args.ref_or_id = action_exec.action if action_ref_or_id: try: action = action_mgr.get_by_ref_or_id(args.ref_or_id, **kwargs) if not action: raise resource.ResourceNotFoundError('Action %s not found', args.ref_or_id) runner_mgr = self.app.client.managers['RunnerType'] runner = runner_mgr.get_by_name(action.runner_type, **kwargs) parameters, required, optional, _ = self._get_params_types(runner, action) print('') print(textwrap.fill(action.description)) print('') if required: required = self._sort_parameters(parameters=parameters, names=required) print('Required Parameters:') [self._print_param(name, parameters.get(name)) for name in required] if optional: optional = self._sort_parameters(parameters=parameters, names=optional) print('Optional Parameters:') [self._print_param(name, parameters.get(name)) for name in optional] except resource.ResourceNotFoundError: print(('Action "%s" is not found. ' % args.ref_or_id) + 'Do "st2 action list" to see list of available actions.') except Exception as e: print('ERROR: Unable to print help for action "%s". %s' % (args.ref_or_id, e)) else: self.parser.print_help() return True return False @staticmethod def _print_param(name, schema): if not schema: raise ValueError('Missing schema for parameter "%s"' % (name)) wrapper = textwrap.TextWrapper(width=78) wrapper.initial_indent = ' ' * 4 wrapper.subsequent_indent = wrapper.initial_indent print(wrapper.fill(name)) wrapper.initial_indent = ' ' * 8 wrapper.subsequent_indent = wrapper.initial_indent if 'description' in schema and schema['description']: print(wrapper.fill(schema['description'])) if 'type' in schema and schema['type']: print(wrapper.fill('Type: %s' % schema['type'])) if 'enum' in schema and schema['enum']: print(wrapper.fill('Enum: %s' % ', '.join(schema['enum']))) if 'default' in schema and schema['default'] is not None: print(wrapper.fill('Default: %s' % schema['default'])) print('') @staticmethod def _get_params_types(runner, action): runner_params = runner.runner_parameters action_params = action.parameters parameters = copy.copy(runner_params) parameters.update(copy.copy(action_params)) required = set([k for k, v in six.iteritems(parameters) if v.get('required')]) def is_immutable(runner_param_meta, action_param_meta): # If runner sets a param as immutable, action cannot override that. if runner_param_meta.get('immutable', False): return True else: return action_param_meta.get('immutable', False) immutable = set() for param in parameters.keys(): if is_immutable(runner_params.get(param, {}), action_params.get(param, {})): immutable.add(param) required = required - immutable optional = set(parameters.keys()) - required - immutable return parameters, required, optional, immutable def _format_child_instances(self, children, parent_id): ''' The goal of this method is to add an indent at every level. This way the WF is represented as a tree structure while in a list. For the right visuals representation the list must be a DF traversal else the idents will end up looking strange. ''' # apply basic WF formating first. children = format_wf_instances(children) # setup a depth lookup table depth = {parent_id: 0} result = [] # main loop that indents each entry correctly for child in children: # make sure child.parent is in depth and while at it compute the # right depth for indentation purposes. if child.parent not in depth: parent = None for instance in children: if WF_PREFIX in instance.id: instance_id = instance.id[instance.id.index(WF_PREFIX) + len(WF_PREFIX):] else: instance_id = instance.id if instance_id == child.parent: parent = instance if parent and parent.parent and parent.parent in depth: depth[child.parent] = depth[parent.parent] + 1 else: depth[child.parent] = 0 # now ident for the right visuals child.id = INDENT_CHAR * depth[child.parent] + child.id result.append(self._format_for_common_representation(child)) return result def _format_for_common_representation(self, task): ''' Formats a task for common representation between mistral and action-chain. ''' # This really needs to be better handled on the back-end but that would be a bigger # change so handling in cli. context = getattr(task, 'context', None) if context and 'chain' in context: task_name_key = 'context.chain.name' elif context and 'mistral' in context: task_name_key = 'context.mistral.task_name' # Use LiveAction as the object so that the formatter lookup does not change. # AKA HACK! return models.action.LiveAction(**{ 'id': task.id, 'status': task.status, 'task': jsutil.get_value(vars(task), task_name_key), 'action': task.action.get('ref', None), 'start_timestamp': task.start_timestamp }) def _sort_parameters(self, parameters, names): """ Sort a provided list of action parameters. :type parameters: ``list`` :type names: ``list`` or ``set`` """ sorted_parameters = sorted(names, key=lambda name: self._get_parameter_sort_value( parameters=parameters, name=name)) return sorted_parameters def _get_parameter_sort_value(self, parameters, name): """ Return a value which determines sort order for a particular parameter. By default, parameters are sorted using "position" parameter attribute. If this attribute is not available, parameter is sorted based on the name. """ parameter = parameters.get(name, None) if not parameter: return None sort_value = parameter.get('position', name) return sort_value def _get_inherited_env_vars(self): env_vars = os.environ.copy() for var_name in ENV_VARS_BLACKLIST: if var_name.lower() in env_vars: del env_vars[var_name.lower()] if var_name.upper() in env_vars: del env_vars[var_name.upper()] return env_vars class ActionRunCommand(ActionRunCommandMixin, resource.ResourceCommand): def __init__(self, resource, *args, **kwargs): super(ActionRunCommand, self).__init__( resource, kwargs.pop('name', 'execute'), 'A command to invoke an action manually.', *args, **kwargs) self.parser.add_argument('ref_or_id', nargs='?', metavar='ref-or-id', help='Action reference (pack.action_name) ' + 'or ID of the action.') self.parser.add_argument('parameters', nargs='*', help='List of keyword args, positional args, ' 'and optional args for the action.') self.parser.add_argument('-h', '--help', action='store_true', dest='help', help='Print usage for the given action.') self._add_common_options() if self.name in ['run', 'execute']: self.parser.add_argument('-a', '--async', action='store_true', dest='async', help='Do not wait for action to finish.') self.parser.add_argument('-e', '--inherit-env', action='store_true', dest='inherit_env', help='Pass all the environment variables ' 'which are accessible to the CLI as "env" ' 'parameter to the action. Note: Only works ' 'with python, local and remote runners.') if self.name == 'run': self.parser.set_defaults(async=False) else: self.parser.set_defaults(async=True) @add_auth_token_to_kwargs_from_cli def run(self, args, **kwargs): if not args.ref_or_id: self.parser.error('Missing action reference or id') action = self.get_resource(args.ref_or_id, **kwargs) if not action: raise resource.ResourceNotFoundError('Action "%s" cannot be found.' % (args.ref_or_id)) runner_mgr = self.app.client.managers['RunnerType'] runner = runner_mgr.get_by_name(action.runner_type, **kwargs) if not runner: raise resource.ResourceNotFoundError('Runner type "%s" for action "%s" cannot be found.' % (action.runner_type, action.name)) action_ref = '.'.join([action.pack, action.name]) action_parameters = self._get_action_parameters_from_args(action=action, runner=runner, args=args) execution = models.LiveAction() execution.action = action_ref execution.parameters = action_parameters action_exec_mgr = self.app.client.managers['LiveAction'] execution = action_exec_mgr.create(execution, **kwargs) execution = self._get_execution_result(execution=execution, action_exec_mgr=action_exec_mgr, args=args, **kwargs) return execution class ActionExecutionBranch(resource.ResourceBranch): def __init__(self, description, app, subparsers, parent_parser=None): super(ActionExecutionBranch, self).__init__( models.LiveAction, description, app, subparsers, parent_parser=parent_parser, read_only=True, commands={'list': ActionExecutionListCommand, 'get': ActionExecutionGetCommand}) # Register extended commands self.commands['re-run'] = ActionExecutionReRunCommand(self.resource, self.app, self.subparsers, add_help=False) self.commands['cancel'] = ActionExecutionCancelCommand(self.resource, self.app, self.subparsers, add_help=False) POSSIBLE_ACTION_STATUS_VALUES = ('succeeded', 'running', 'scheduled', 'failed', 'canceled') class ActionExecutionListCommand(resource.ResourceCommand): display_attributes = ['id', 'action.ref', 'context.user', 'status', 'start_timestamp', 'end_timestamp'] attribute_transform_functions = { 'start_timestamp': format_isodate, 'end_timestamp': format_isodate, 'parameters': format_parameters, 'status': format_status } def __init__(self, resource, *args, **kwargs): super(ActionExecutionListCommand, self).__init__( resource, 'list', 'Get the list of the 50 most recent %s.' % resource.get_plural_display_name().lower(), *args, **kwargs) self.group = self.parser.add_argument_group() self.parser.add_argument('-n', '--last', type=int, dest='last', default=50, help=('List N most recent %s; ' 'list all if 0.' % resource.get_plural_display_name().lower())) # Filter options self.group.add_argument('--action', help='Action reference to filter the list.') self.group.add_argument('--status', help=('Only return executions with the provided status.' ' Possible values are \'%s\', \'%s\', \'%s\',' '\'%s\' or \'%s\'' '.' % POSSIBLE_ACTION_STATUS_VALUES)) self.group.add_argument('--trigger_instance', help='Trigger instance id to filter the list.') self.parser.add_argument('-tg', '--timestamp-gt', type=str, dest='timestamp_gt', default=None, help=('Only return executions with timestamp ' 'greater than the one provided. ' 'Use time in the format "2000-01-01T12:00:00.000Z".')) self.parser.add_argument('-tl', '--timestamp-lt', type=str, dest='timestamp_lt', default=None, help=('Only return executions with timestamp ' 'lower than the one provided. ' 'Use time in the format "2000-01-01T12:00:00.000Z".')) self.parser.add_argument('-l', '--showall', action='store_true', help='') # Display options self.parser.add_argument('-a', '--attr', nargs='+', default=self.display_attributes, help=('List of attributes to include in the ' 'output. "all" will return all ' 'attributes.')) self.parser.add_argument('-w', '--width', nargs='+', type=int, default=None, help=('Set the width of columns in output.')) @add_auth_token_to_kwargs_from_cli def run(self, args, **kwargs): # Filtering options if args.action: kwargs['action'] = args.action if args.status: kwargs['status'] = args.status if args.trigger_instance: kwargs['trigger_instance'] = args.trigger_instance if not args.showall: # null is the magic string that translates to does not exist. kwargs['parent'] = 'null' if args.timestamp_gt: kwargs['timestamp_gt'] = args.timestamp_gt if args.timestamp_lt: kwargs['timestamp_lt'] = args.timestamp_lt return self.manager.query(limit=args.last, **kwargs) def run_and_print(self, args, **kwargs): instances = format_wf_instances(self.run(args, **kwargs)) self.print_output(reversed(instances), table.MultiColumnTable, attributes=args.attr, widths=args.width, json=args.json, attribute_transform_functions=self.attribute_transform_functions) class ActionExecutionGetCommand(ActionRunCommandMixin, resource.ResourceCommand): display_attributes = ['id', 'action.ref', 'context.user', 'parameters', 'status', 'start_timestamp', 'end_timestamp', 'result', 'liveaction'] def __init__(self, resource, *args, **kwargs): super(ActionExecutionGetCommand, self).__init__( resource, 'get', 'Get individual %s.' % resource.get_display_name().lower(), *args, **kwargs) self.parser.add_argument('id', help=('ID of the %s.' % resource.get_display_name().lower())) self._add_common_options() @add_auth_token_to_kwargs_from_cli def run(self, args, **kwargs): execution = self.get_resource_by_id(id=args.id, **kwargs) return execution @add_auth_token_to_kwargs_from_cli def run_and_print(self, args, **kwargs): try: execution = self.run(args, **kwargs) except resource.ResourceNotFoundError: self.print_not_found(args.id) raise OperationFailureException('Execution %s not found.' % (args.id)) return self._print_execution_details(execution=execution, args=args, **kwargs) class ActionExecutionCancelCommand(resource.ResourceCommand): def __init__(self, resource, *args, **kwargs): super(ActionExecutionCancelCommand, self).__init__( resource, 'cancel', 'Cancel an %s.' % resource.get_plural_display_name().lower(), *args, **kwargs) self.parser.add_argument('id', help=('ID of the %s.' % resource.get_display_name().lower())) def run(self, args, **kwargs): return self.manager.delete_by_id(args.id) @add_auth_token_to_kwargs_from_cli def run_and_print(self, args, **kwargs): response = self.run(args, **kwargs) if response and 'faultstring' in response: message = response.get('faultstring', '%s with id %s canceled.' % (self.resource.get_display_name().lower(), args.id)) elif response: message = '%s with id %s canceled.' % (self.resource.get_display_name().lower(), args.id) else: message = 'Cannot cancel %s with id %s.' % (self.resource.get_display_name().lower(), args.id) print(message) class ActionExecutionReRunCommand(ActionRunCommandMixin, resource.ResourceCommand): def __init__(self, resource, *args, **kwargs): super(ActionExecutionReRunCommand, self).__init__( resource, kwargs.pop('name', 're-run'), 'A command to re-run a particular action.', *args, **kwargs) self.parser.add_argument('id', nargs='?', metavar='id', help='ID of action execution to re-run ') self.parser.add_argument('parameters', nargs='*', help='List of keyword args, positional args, ' 'and optional args for the action.') self.parser.add_argument('-a', '--async', action='store_true', dest='async', help='Do not wait for action to finish.') self.parser.add_argument('-e', '--inherit-env', action='store_true', dest='inherit_env', help='Pass all the environment variables ' 'which are accessible to the CLI as "env" ' 'parameter to the action. Note: Only works ' 'with python, local and remote runners.') self.parser.add_argument('-h', '--help', action='store_true', dest='help', help='Print usage for the given action.') self._add_common_options() @add_auth_token_to_kwargs_from_cli def run(self, args, **kwargs): existing_execution = self.manager.get_by_id(args.id, **kwargs) if not existing_execution: raise resource.ResourceNotFoundError('Action execution with id "%s" cannot be found.' % (args.id)) action_mgr = self.app.client.managers['Action'] runner_mgr = self.app.client.managers['RunnerType'] action_exec_mgr = self.app.client.managers['LiveAction'] action_ref = existing_execution.action['ref'] action = action_mgr.get_by_ref_or_id(action_ref) runner = runner_mgr.get_by_name(action.runner_type) action_parameters = self._get_action_parameters_from_args(action=action, runner=runner, args=args) execution = action_exec_mgr.re_run(execution_id=args.id, parameters=action_parameters, **kwargs) execution = self._get_execution_result(execution=execution, action_exec_mgr=action_exec_mgr, args=args, **kwargs) return execution
apache-2.0
1,807,176,016,032,545,500
39.85005
100
0.540257
false
joshmoore/openmicroscopy
components/tools/OmeroPy/test/clitest/sess.py
1
11995
#!/usr/bin/env python """ Test of the sessions plugin Copyright 2009 Glencoe Software, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import unittest, os, subprocess, StringIO, exceptions import Ice import Glacier2 import omero import omero_ext.uuid as uuid # see ticket:3774 from path import path from omero.cli import Context, BaseControl, CLI, NonZeroReturnCode from omero.util import get_user from omero.util.sessions import SessionsStore from omero.util.temp_files import create_path from omero.plugins.sessions import SessionsControl omeroDir = path(os.getcwd()) / "build" testsess = "testsess" testuser = "testuser" testhost = "testhost" class MyStore(SessionsStore): def __init__(self, *args, **kwargs): SessionsStore.__init__(self, *args, **kwargs) self.clients = [] self.exceptions = [] def create(self, name, pasw, props, new = True, set_current = True): if not isinstance(props, dict): raise exceptions.Exception("Bad type") if self.exceptions: raise self.exceptions.pop(0) cb = getattr(self, "create_callback", None) if cb: cb(*args, **kwargs) self.create_callback = None return_tuple, add_tuple, should_be_new = self.clients.pop(0) assert should_be_new == new, ("should_be_new=%s wasn't!" % should_be_new) if new: self.add(*add_tuple) if set_current: self.set_current(*add_tuple[0:3]) return return_tuple def __del__(self): assert len(self.clients) == 0, ("clients not empty! %s" % self.clients) assert len(self.exceptions) == 0, ("exceptions not empty! %s" % self.exceptions) class MyClient(object): def __init__(self, user, group, props): self.sf = self self.userName = user self.groupName = group self.props = {"omero.port":"4064"} # Fix after #3883 self.props.update(props) def __del__(self, *args): pass def enableKeepAlive(self, *args): pass def getSession(self): return self def keepAlive(self, prx): pass def closeSession(self): pass def getAdminService(self): return self def getEventContext(self): return self def getProperty(self, key): return self.props[key] class MyCLI(CLI): def __init__(self, *args, **kwargs): CLI.__init__(self, *args, **kwargs) self.DIR = create_path(folder=True) self.REQRESP = {} self.STORE = MyStore(self.DIR) self.STORE.clear(testhost, testuser) self.register("s", SessionsControl, "TEST") self.controls["s"].FACTORY = lambda ignore: self.STORE assert self.STORE.count(testhost, testuser) == 0 def __del__(self): del self.STORE def creates_client(self, name="testuser", host="testhost", sess="sess_id", port=None, group=None, new=True): props = dict() if port: props["omero.port"] = port if group: props["omero.group"] = group else: group = "mygroup" # For use via IAdmin.EventContext #props = {"omero.group":group, "omero.port":port} return_tuple = (MyClient(name, group, {"omero.host":host}), sess, 0, 0) add_tuple = (host, name, sess, props) self.STORE.clients.append((return_tuple, add_tuple, new)) def throw_on_create(self, e): self.STORE.exceptions.append(e) def requests_host(self, host = "testhost"): self.REQRESP["Server: [localhost]"] = host def requests_user(self, user = 'testuser'): self.REQRESP["Username: [%s]" % get_user("Unknown")] = user def requests_pass(self, pasw = "pasw"): self.REQRESP["Password:"] = pasw def requests_size(self): return len(self.REQRESP) def assertReqSize(self, test, size): test.assertEquals(size, self.requests_size(), "size!=%s: %s" % (size, self.REQRESP)) def input(self, prompt, hidden=False, required=False): if prompt not in self.REQRESP: raise exceptions.Exception("Missing prompt: '%s'" % prompt) return self.REQRESP.pop(prompt) def invoke(self, *args): CLI.invoke(self, *args, strict = True) class TestStore(unittest.TestCase): def store(self): p = create_path(folder=True) return MyStore(p) def testReport(self): s = self.store() s.report() def testAdd(self): s = self.store() s.add("srv", "usr", "uuid", {}) self.assertEquals(1, len(s.available("srv", "usr"))) def testDefaults(self): s = self.store() self.assertEquals("localhost", s.last_host()) def testCurrent(self): s = self.store() s.set_current("srv", "usr", "uuid") # Using last_* methods self.assertEquals("srv", s.last_host()) # Using helprs self.assertEquals("uuid", s.sess_file("srv", "usr").text().strip()) self.assertEquals("usr", s.user_file("srv").text().strip()) self.assertEquals("srv", s.host_file().text().strip()) def testContents(self): s = self.store() s.add("a", "a", "a", {}) s.add("b", "b", "b", {}) rv = s.contents() self.assertEquals(2, len(rv)) self.assertTrue("a" in rv) self.assertTrue("a" in rv["a"]) self.assertTrue("a" in rv["a"]["a"]) self.assertTrue("b" in rv) self.assertTrue("b" in rv["b"]) self.assertTrue("b" in rv["b"]["b"]) def testCount(self): s = self.store() self.assertEquals(0, s.count()) s.add("a","a","a",{}) self.assertEquals(1, s.count()) s.remove("a","a","a") self.assertEquals(0, s.count()) def testGet(self): s = self.store() s.add("a","b","c", {"foo":"1"}) rv = s.get("a","b","c") expect = { "foo":"1", "omero.host":"a", "omero.user":"b", "omero.sess":"c" } self.assertEquals(expect, rv) def testConflicts(self): s = self.store() s.add("a", "b", "c", {"omero.group":"1"}) conflicts = s.conflicts("a", "b", "c", {}) self.assertNotEqual("", conflicts) conflicts = s.conflicts("a", "b", "c", {"omero.group":"2"}) self.assertNotEqual("", conflicts) class TestSessions(unittest.TestCase): def testLoginWithNoArgumentsRequests(self): cli = MyCLI() cli.requests_host() cli.requests_user() cli.requests_pass() cli.creates_client() cli.invoke(["s","login"]) self.assertEquals(0, cli.rv) def test2(self): cli = MyCLI() cli.requests_pass() cli.creates_client(name="user") cli.invoke(["s","login","user@host"]) self.assertEquals(0, cli.rv) def test3(self): cli = MyCLI() cli.creates_client(name="user") cli.invoke(["-s", "localhost","-u", "user", "-w", "pasw", "s", "login"]) self.assertEquals(0, cli.rv) def test4(self): cli = MyCLI() cli.STORE.add("testhost","testuser","key", {}) cli.creates_client(sess="key", new=False) cli.invoke(["-s", "testuser@testhost","-k", "key", "s", "login"]) self.assertEquals(0, cli.rv) def testReuseWorks(self): cli = MyCLI() cli.STORE.add("testhost","testuser","testsessid", {}) cli.creates_client(new=False) cli.invoke("-s testhost -u testuser s login".split()) self.assert_(cli._client is not None) def testReuseFromDifferentGroupDoesntWork(self): cli = MyCLI() cli.STORE.add("testhost","testuser","testsessid", {}) cli.requests_pass() cli.assertReqSize(self, 1) cli.creates_client(group="mygroup2") cli.invoke("-s testhost -u testuser -g mygroup2 s login".split()) cli.assertReqSize(self, 0) def testReuseFromSameGroupDoesWork(self): cli = MyCLI() cli.STORE.add("testhost","testuser","testsessid", {"omero.group":"mygroup"}) cli.assertReqSize(self, 0) cli.creates_client(group="mygroup", new=False) cli.invoke("-s testhost -u testuser -g mygroup s login".split()) cli.assertReqSize(self, 0) def testReuseFromDifferentPortDoesntWork(self): cli = MyCLI() cli.STORE.add("testhost","testuser","testsessid", {}) cli.requests_pass() cli.assertReqSize(self, 1) cli.creates_client(port="4444") cli.invoke("-s testhost -u testuser -p 4444 s login".split()) cli.assertReqSize(self, 0) def testReuseFromSamePortDoesWork(self): cli = MyCLI() cli.STORE.add("testhost","testuser","testsessid", {"omero.port":"4444"}) cli.assertReqSize(self, 0) cli.creates_client(port="4444", new=False) cli.invoke("-s testhost -u testuser -p 4444 s login".split()) cli.assertReqSize(self, 0) def testLogicOfConflictsOnNoLocalhostRequested(self): cli = MyCLI() cli.creates_client() cli.invoke("-s testhost -u testuser -w testpass s login") cli.invoke("s login") # Should work. No conflict cli.invoke("-p 4444 s login") def testPortThenNothingShouldReuse(self): cli = MyCLI() cli.creates_client(port="4444") cli.requests_host() cli.requests_user() cli.requests_pass() cli.invoke("-p 4444 s login") cli.assertReqSize(self, 0) # All were requested cli._client = None # Forcing new instance cli.creates_client(port="4444", new=False) cli.invoke("s login") # Should work. No conflict del cli def testBadSessionKeyDies(self): """ As seen in ticket 4223, when a bad session is provided, a password shouldn't be asked for. """ cli = MyCLI() MOCKKEY = "MOCKKEY" # First, successful login cli.creates_client(sess=MOCKKEY) cli.requests_pass() cli.invoke("-s testuser@testhost s login") cli.assertReqSize(self, 0) # All were requested cli._client = None # Forcing new instance key_login = "-s testuser@testhost -k %s s login" % MOCKKEY # Now try with session when it's still available cli.creates_client(sess=MOCKKEY, new=False) cli.invoke(key_login) cli._client = None # Forcing new instance # Don't do creates_client, so the session key # is now bad. cli.throw_on_create(Glacier2.PermissionDeniedException("MOCKKEY EXPIRED")) try: cli.invoke(key_login) self.fail("This must throw 'Bad session key'") except NonZeroReturnCode: pass cli._client = None # Forcing new instance del cli def testCopiedSessionWorks(self): """ Found by Colin while using a session key from a non-CLI-source. """ cli = MyCLI() MOCKKEY = "MOCKKEY%s" % uuid.uuid4() key_login = "-s testuser@testhost -k %s s login" % MOCKKEY # Try with session when it's still available cli.creates_client(sess=MOCKKEY, new=True) cli.invoke(key_login) cli._client = None # Forcing new instance def assert5975(self, key, cli): host, name, uuid = cli.STORE.get_current() self.assert_(key != name) def test5975(self): """ Runs various tests which try to force the stored user name to be a session uuid (which should never happen) """ cli = MyCLI() key = str(uuid.uuid4()) key_login = "-s testuser@testhost -k %s s login" % key cli.creates_client(sess=key, new=True) cli.invoke(key_login) self.assert5975(key, cli) cli.invoke("s logout") self.assert5975(key, cli) if __name__ == '__main__': unittest.main()
gpl-2.0
-3,384,975,792,573,513,700
29.835476
112
0.580825
false
ddebrunner/streamsx.topology
test/python/topology/test2_submission_params.py
1
7613
# coding=utf-8 # Licensed Materials - Property of IBM # Copyright IBM Corp. 2016 import unittest import sys import itertools from enum import IntEnum import datetime import decimal import random from streamsx.topology.schema import StreamSchema from streamsx.topology.topology import * from streamsx.topology.tester import Tester from streamsx.topology.context import JobConfig import streamsx.spl.op as op class AddIt(object): def __init__(self, sp): self.sp = sp def __enter__(self): self.spv = self.sp() def __exit__(self, exc_type, exc_value, traceback): pass def __call__(self, t): return str(t) + '-' + self.spv class TestSubmissionParams(unittest.TestCase): """ Test submission params (standalone). """ _multiprocess_can_split_ = True def setUp(self): Tester.setup_standalone(self) def test_spl_default(self): """ Test passing as with default using SPL """ N=27 G='hey there' t = ''.join(random.choice('0123456789abcdef') for x in range(20)) topic = 'topology/test/python/' + t topo = Topology() spGreet = topo.create_submission_parameter('greeting', default=G) self.assertIsNone(spGreet()) sch = StreamSchema('tuple<uint64 seq, rstring s>') b = op.Source(topo, "spl.utility::Beacon", sch, params = {'initDelay': 10.0, 'period': 0.02, 'iterations':N}) b.seq = b.output('IterationCount()') b.s = b.output(spGreet) tester = Tester(topo) tester.tuple_count(b.stream, N) tester.contents(b.stream, [{'seq':i, 's':G} for i in range(N)]) tester.test(self.test_ctxtype, self.test_config) def test_topo(self): topo = Topology() s = topo.source(range(38)) lower = topo.create_submission_parameter('lower') upper = topo.create_submission_parameter('upper') addin = topo.create_submission_parameter('addin') s = s.filter(lambda v: v < int(lower()) or v > int(upper())) m = s.filter(lambda v : v < 3) m = m.map(AddIt(addin)) jc = JobConfig() jc.submission_parameters['lower'] = 7 jc.submission_parameters['upper'] = 33 jc.submission_parameters['addin'] = 'Yeah!' jc.add(self.test_config) tester = Tester(topo) tester.contents(s, [0,1,2,3,4,5,6,34,35,36,37]) tester.contents(m, ['0-Yeah!','1-Yeah!','2-Yeah!']) tester.test(self.test_ctxtype, self.test_config) def test_topo_with_def_and_type(self): topo = Topology() s = topo.source(range(38)) lower = topo.create_submission_parameter('lower', default=0) upper = topo.create_submission_parameter('upper', default=30) s = s.filter(lambda v: v < lower() or v > upper()) jc = JobConfig() jc.submission_parameters['lower'] = 5 jc.add(self.test_config) tester = Tester(topo) tester.contents(s, [0,1,2,3,4,31,32,33,34,35,36,37]) tester.test(self.test_ctxtype, self.test_config) def test_topo_types_from_default(self): topo = Topology() sp_str = topo.create_submission_parameter('sp_str', default='Hi') sp_int = topo.create_submission_parameter('sp_int', default=89) sp_float = topo.create_submission_parameter('sp_float', default=0.5) sp_bool = topo.create_submission_parameter('sp_bool', default=False) s = topo.source(range(17)) s = s.filter(lambda v : isinstance(sp_str(), str) and sp_str() == 'Hi') s = s.filter(lambda v : isinstance(sp_int(), int) and sp_int() == 89) s = s.filter(lambda v : isinstance(sp_float(), float) and sp_float() == 0.5) s = s.filter(lambda v : isinstance(sp_bool(), bool) and sp_bool() is False) tester = Tester(topo) tester.tuple_count(s, 17) tester.test(self.test_ctxtype, self.test_config) def test_topo_types_explicit_set(self): topo = Topology() sp_str = topo.create_submission_parameter('sp_str', type_=str) sp_int = topo.create_submission_parameter('sp_int', type_=int) sp_float = topo.create_submission_parameter('sp_float', type_=float) sp_bool = topo.create_submission_parameter('sp_bool', type_=bool) s = topo.source(range(17)) s = s.filter(lambda v : isinstance(sp_str(), str) and sp_str() == 'SeeYa') s = s.filter(lambda v : isinstance(sp_int(), int) and sp_int() == 10) s = s.filter(lambda v : isinstance(sp_float(), float) and sp_float() == -0.5) s = s.filter(lambda v : isinstance(sp_bool(), bool) and sp_bool() is True) jc = JobConfig() jc.submission_parameters['sp_str'] = 'SeeYa' jc.submission_parameters['sp_int'] = 10 jc.submission_parameters['sp_float'] = -0.5 jc.submission_parameters['sp_bool'] = True jc.add(self.test_config) tester = Tester(topo) tester.tuple_count(s, 17) tester.test(self.test_ctxtype, self.test_config) def test_parallel(self): topo = Topology() sp_w1 = topo.create_submission_parameter('w1', type_=int) sp_w2 = topo.create_submission_parameter('w2', type_=int) s = topo.source(range(67)).set_parallel(sp_w1) s = s.filter(lambda v : v % sp_w1() == 0) s = s.end_parallel() s = s.parallel(width=sp_w2) s = s.filter(lambda v : v % sp_w2() == 0) s = s.end_parallel() jc = JobConfig() jc.submission_parameters['w1'] = 3 jc.submission_parameters['w2'] = 5 jc.add(self.test_config) tester = Tester(topo) tester.contents(s,[0,15,30,45,60]*3, ordered=False) tester.test(self.test_ctxtype, self.test_config) class TestDistributedSubmissionParams(TestSubmissionParams): """ Test submission params (distributed). """ def setUp(self): Tester.setup_distributed(self) def test_spl(self): """ Test passing as an SPL parameter. """ N=22 G='hey' t = ''.join(random.choice('0123456789abcdef') for x in range(20)) topic = 'topology/test/python/' + t topo = Topology() spTopic = topo.create_submission_parameter('mytopic') spGreet = topo.create_submission_parameter('greeting') self.assertIsNone(spTopic()) self.assertIsNone(spGreet()) sch = StreamSchema('tuple<uint64 seq, rstring s>') b = op.Source(topo, "spl.utility::Beacon", sch, params = {'initDelay': 10.0, 'period': 0.02, 'iterations':N}) b.seq = b.output('IterationCount()') b.s = b.output(spGreet) p = op.Sink("com.ibm.streamsx.topology.topic::Publish", b.stream, params={'topic': topic}) s = op.Source(topo, "com.ibm.streamsx.topology.topic::Subscribe", sch, params = {'streamType': sch, 'topic': spTopic}) jc = JobConfig() jc.submission_parameters['mytopic'] = topic jc.submission_parameters['greeting'] = G jc.add(self.test_config) tester = Tester(topo) tester.tuple_count(s.stream, N) #tester.run_for(300) tester.contents(s.stream, [{'seq':i, 's':G} for i in range(N)]) tester.test(self.test_ctxtype, self.test_config) class TestSasSubmissionParams(TestDistributedSubmissionParams): """ Test submission params (service). """ def setUp(self): Tester.setup_streaming_analytics(self, force_remote_build=True)
apache-2.0
7,939,775,946,423,901,000
35.252381
85
0.596611
false
davidh-ssec/pyresample
pyresample/geometry.py
1
79231
#!/usr/bin/env python # -*- coding: utf-8 -*- # pyresample, Resampling of remote sensing image data in python # # Copyright (C) 2010-2016 # # Authors: # Esben S. Nielsen # Thomas Lavergne # Adam Dybbroe # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This program 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 Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Classes for geometry operations""" import hashlib import warnings from collections import OrderedDict from logging import getLogger import numpy as np import yaml from pyproj import Geod, transform from pyresample import CHUNK_SIZE from pyresample._spatial_mp import Cartesian, Cartesian_MP, Proj, Proj_MP from pyresample.boundary import AreaDefBoundary, Boundary, SimpleBoundary from pyresample.utils import proj4_str_to_dict, proj4_dict_to_str, convert_proj_floats from pyresample.area_config import create_area_def try: from xarray import DataArray except ImportError: DataArray = np.ndarray logger = getLogger(__name__) class DimensionError(ValueError): pass class IncompatibleAreas(ValueError): """Error when the areas to combine are not compatible.""" class BaseDefinition(object): """Base class for geometry definitions. .. versionchanged:: 1.8.0 `BaseDefinition` no longer checks the validity of the provided longitude and latitude coordinates to improve performance. Longitude arrays are expected to be between -180 and 180 degrees, latitude -90 to 90 degrees. Use :func:`~pyresample.utils.check_and_wrap` to preprocess your arrays. """ def __init__(self, lons=None, lats=None, nprocs=1): if type(lons) != type(lats): raise TypeError('lons and lats must be of same type') elif lons is not None: if not isinstance(lons, (np.ndarray, DataArray)): lons = np.asanyarray(lons) lats = np.asanyarray(lats) if lons.shape != lats.shape: raise ValueError('lons and lats must have same shape') self.nprocs = nprocs self.lats = lats self.lons = lons self.ndim = None self.cartesian_coords = None self.hash = None def __getitem__(self, key): """Slice a 2D geographic definition.""" y_slice, x_slice = key return self.__class__( lons=self.lons[y_slice, x_slice], lats=self.lats[y_slice, x_slice], nprocs=self.nprocs ) def __hash__(self): """Compute the hash of this object.""" if self.hash is None: self.hash = int(self.update_hash().hexdigest(), 16) return self.hash def __eq__(self, other): """Test for approximate equality""" if self is other: return True if other.lons is None or other.lats is None: other_lons, other_lats = other.get_lonlats() else: other_lons = other.lons other_lats = other.lats if self.lons is None or self.lats is None: self_lons, self_lats = self.get_lonlats() else: self_lons = self.lons self_lats = self.lats if self_lons is other_lons and self_lats is other_lats: return True if isinstance(self_lons, DataArray) and np.ndarray is not DataArray: self_lons = self_lons.data self_lats = self_lats.data if isinstance(other_lons, DataArray) and np.ndarray is not DataArray: other_lons = other_lons.data other_lats = other_lats.data try: from dask.array import allclose except ImportError: from numpy import allclose try: return (allclose(self_lons, other_lons, atol=1e-6, rtol=5e-9, equal_nan=True) and allclose(self_lats, other_lats, atol=1e-6, rtol=5e-9, equal_nan=True)) except (AttributeError, ValueError): return False def __ne__(self, other): """Test for approximate equality""" return not self.__eq__(other) def get_area_extent_for_subset(self, row_LR, col_LR, row_UL, col_UL): """Calculate extent for a subdomain of this area Rows are counted from upper left to lower left and columns are counted from upper left to upper right. Args: row_LR (int): row of the lower right pixel col_LR (int): col of the lower right pixel row_UL (int): row of the upper left pixel col_UL (int): col of the upper left pixel Returns: area_extent (tuple): Area extent (LL_x, LL_y, UR_x, UR_y) of the subset Author: Ulrich Hamann """ (a, b) = self.get_proj_coords(data_slice=(row_LR, col_LR)) a = a - 0.5 * self.pixel_size_x b = b - 0.5 * self.pixel_size_y (c, d) = self.get_proj_coords(data_slice=(row_UL, col_UL)) c = c + 0.5 * self.pixel_size_x d = d + 0.5 * self.pixel_size_y return a, b, c, d def get_lonlat(self, row, col): """Retrieve lon and lat of single pixel Parameters ---------- row : int col : int Returns ------- (lon, lat) : tuple of floats """ if self.ndim != 2: raise DimensionError(('operation undefined ' 'for %sD geometry ') % self.ndim) elif self.lons is None or self.lats is None: raise ValueError('lon/lat values are not defined') return self.lons[row, col], self.lats[row, col] def get_lonlats(self, data_slice=None, chunks=None, **kwargs): """Get longitude and latitude arrays representing this geometry. Returns ------- (lon, lat) : tuple of numpy arrays If `chunks` is provided then the arrays will be dask arrays with the provided chunk size. If `chunks` is not provided then the returned arrays are the same as the internal data types of this geometry object (numpy or dask). """ lons = self.lons lats = self.lats if lons is None or lats is None: raise ValueError('lon/lat values are not defined') elif DataArray is not np.ndarray and isinstance(lons, DataArray): # lons/lats are xarray DataArray objects, use numpy/dask array underneath lons = lons.data lats = lats.data if chunks is not None: import dask.array as da if isinstance(lons, da.Array): # rechunk to this specific chunk size lons = lons.rechunk(chunks) lats = lats.rechunk(chunks) elif not isinstance(lons, da.Array): # convert numpy array to dask array lons = da.from_array(np.asanyarray(lons), chunks=chunks) lats = da.from_array(np.asanyarray(lats), chunks=chunks) if data_slice is not None: lons, lats = lons[data_slice], lats[data_slice] return lons, lats def get_lonlats_dask(self, chunks=None): """Get the lon lats as a single dask array.""" warnings.warn("'get_lonlats_dask' is deprecated, please use " "'get_lonlats' with the 'chunks' keyword argument specified.", DeprecationWarning) if chunks is None: chunks = CHUNK_SIZE # FUTURE: Use a global config object instead return self.get_lonlats(chunks=chunks) def get_boundary_lonlats(self): """Return Boundary objects.""" s1_lon, s1_lat = self.get_lonlats(data_slice=(0, slice(None))) s2_lon, s2_lat = self.get_lonlats(data_slice=(slice(None), -1)) s3_lon, s3_lat = self.get_lonlats(data_slice=(-1, slice(None, None, -1))) s4_lon, s4_lat = self.get_lonlats(data_slice=(slice(None, None, -1), 0)) return (SimpleBoundary(s1_lon.squeeze(), s2_lon.squeeze(), s3_lon.squeeze(), s4_lon.squeeze()), SimpleBoundary(s1_lat.squeeze(), s2_lat.squeeze(), s3_lat.squeeze(), s4_lat.squeeze())) def get_bbox_lonlats(self): """Returns the bounding box lons and lats""" s1_lon, s1_lat = self.get_lonlats(data_slice=(0, slice(None))) s2_lon, s2_lat = self.get_lonlats(data_slice=(slice(None), -1)) s3_lon, s3_lat = self.get_lonlats(data_slice=(-1, slice(None, None, -1))) s4_lon, s4_lat = self.get_lonlats(data_slice=(slice(None, None, -1), 0)) return zip(*[(s1_lon.squeeze(), s1_lat.squeeze()), (s2_lon.squeeze(), s2_lat.squeeze()), (s3_lon.squeeze(), s3_lat.squeeze()), (s4_lon.squeeze(), s4_lat.squeeze())]) def get_cartesian_coords(self, nprocs=None, data_slice=None, cache=False): """Retrieve cartesian coordinates of geometry definition Parameters ---------- nprocs : int, optional Number of processor cores to be used. Defaults to the nprocs set when instantiating object data_slice : slice object, optional Calculate only cartesian coordnates for the defined slice cache : bool, optional Store result the result. Requires data_slice to be None Returns ------- cartesian_coords : numpy array """ if cache: warnings.warn("'cache' keyword argument will be removed in the " "future and data will not be cached.", PendingDeprecationWarning) if self.cartesian_coords is None: # Coordinates are not cached if nprocs is None: nprocs = self.nprocs if data_slice is None: # Use full slice data_slice = slice(None) lons, lats = self.get_lonlats(nprocs=nprocs, data_slice=data_slice) if nprocs > 1: cartesian = Cartesian_MP(nprocs) else: cartesian = Cartesian() cartesian_coords = cartesian.transform_lonlats(np.ravel(lons), np.ravel(lats)) if isinstance(lons, np.ndarray) and lons.ndim > 1: # Reshape to correct shape cartesian_coords = cartesian_coords.reshape(lons.shape[0], lons.shape[1], 3) if cache and data_slice is None: self.cartesian_coords = cartesian_coords else: # Coordinates are cached if data_slice is None: cartesian_coords = self.cartesian_coords else: cartesian_coords = self.cartesian_coords[data_slice] return cartesian_coords @property def corners(self): """Returns the corners of the current area. """ from pyresample.spherical_geometry import Coordinate return [Coordinate(*self.get_lonlat(0, 0)), Coordinate(*self.get_lonlat(0, -1)), Coordinate(*self.get_lonlat(-1, -1)), Coordinate(*self.get_lonlat(-1, 0))] def __contains__(self, point): """Is a point inside the 4 corners of the current area? This uses great circle arcs as area boundaries. """ from pyresample.spherical_geometry import point_inside, Coordinate corners = self.corners if isinstance(point, tuple): return point_inside(Coordinate(*point), corners) else: return point_inside(point, corners) def overlaps(self, other): """Tests if the current area overlaps the *other* area. This is based solely on the corners of areas, assuming the boundaries to be great circles. Parameters ---------- other : object Instance of subclass of BaseDefinition Returns ------- overlaps : bool """ from pyresample.spherical_geometry import Arc self_corners = self.corners other_corners = other.corners for i in self_corners: if i in other: return True for i in other_corners: if i in self: return True self_arc1 = Arc(self_corners[0], self_corners[1]) self_arc2 = Arc(self_corners[1], self_corners[2]) self_arc3 = Arc(self_corners[2], self_corners[3]) self_arc4 = Arc(self_corners[3], self_corners[0]) other_arc1 = Arc(other_corners[0], other_corners[1]) other_arc2 = Arc(other_corners[1], other_corners[2]) other_arc3 = Arc(other_corners[2], other_corners[3]) other_arc4 = Arc(other_corners[3], other_corners[0]) for i in (self_arc1, self_arc2, self_arc3, self_arc4): for j in (other_arc1, other_arc2, other_arc3, other_arc4): if i.intersects(j): return True return False def get_area(self): """Get the area of the convex area defined by the corners of the current area. """ from pyresample.spherical_geometry import get_polygon_area return get_polygon_area(self.corners) def intersection(self, other): """Returns the corners of the intersection polygon of the current area with *other*. Parameters ---------- other : object Instance of subclass of BaseDefinition Returns ------- (corner1, corner2, corner3, corner4) : tuple of points """ from pyresample.spherical_geometry import intersection_polygon return intersection_polygon(self.corners, other.corners) def overlap_rate(self, other): """Get how much the current area overlaps an *other* area. Parameters ---------- other : object Instance of subclass of BaseDefinition Returns ------- overlap_rate : float """ from pyresample.spherical_geometry import get_polygon_area other_area = other.get_area() inter_area = get_polygon_area(self.intersection(other)) return inter_area / other_area def get_area_slices(self, area_to_cover): """Compute the slice to read based on an `area_to_cover`.""" raise NotImplementedError class CoordinateDefinition(BaseDefinition): """Base class for geometry definitions defined by lons and lats only""" def __init__(self, lons, lats, nprocs=1): if not isinstance(lons, (np.ndarray, DataArray)): lons = np.asanyarray(lons) lats = np.asanyarray(lats) super(CoordinateDefinition, self).__init__(lons, lats, nprocs) if lons.shape == lats.shape and lons.dtype == lats.dtype: self.shape = lons.shape self.size = lons.size self.ndim = lons.ndim self.dtype = lons.dtype else: raise ValueError(('%s must be created with either ' 'lon/lats of the same shape with same dtype') % self.__class__.__name__) def concatenate(self, other): if self.ndim != other.ndim: raise DimensionError(('Unable to concatenate %sD and %sD ' 'geometries') % (self.ndim, other.ndim)) klass = _get_highest_level_class(self, other) lons = np.concatenate((self.lons, other.lons)) lats = np.concatenate((self.lats, other.lats)) nprocs = min(self.nprocs, other.nprocs) return klass(lons, lats, nprocs=nprocs) def append(self, other): if self.ndim != other.ndim: raise DimensionError(('Unable to append %sD and %sD ' 'geometries') % (self.ndim, other.ndim)) self.lons = np.concatenate((self.lons, other.lons)) self.lats = np.concatenate((self.lats, other.lats)) self.shape = self.lons.shape self.size = self.lons.size def __str__(self): # Rely on numpy's object printing return ('Shape: %s\nLons: %s\nLats: %s') % (str(self.shape), str(self.lons), str(self.lats)) class GridDefinition(CoordinateDefinition): """Grid defined by lons and lats Parameters ---------- lons : numpy array lats : numpy array nprocs : int, optional Number of processor cores to be used for calculations. Attributes ---------- shape : tuple Grid shape as (rows, cols) size : int Number of elements in grid lons : object Grid lons lats : object Grid lats cartesian_coords : object Grid cartesian coordinates """ def __init__(self, lons, lats, nprocs=1): super(GridDefinition, self).__init__(lons, lats, nprocs) if lons.shape != lats.shape: raise ValueError('lon and lat grid must have same shape') elif lons.ndim != 2: raise ValueError('2 dimensional lon lat grid expected') def get_array_hashable(arr): """Compute a hashable form of the array `arr`. Works with numpy arrays, dask.array.Array, and xarray.DataArray. """ # look for precomputed value if isinstance(arr, DataArray) and np.ndarray is not DataArray: return arr.attrs.get('hash', get_array_hashable(arr.data)) else: try: return arr.name.encode('utf-8') # dask array except AttributeError: return np.asarray(arr).view(np.uint8) # np array class SwathDefinition(CoordinateDefinition): """Swath defined by lons and lats. Parameters ---------- lons : numpy array lats : numpy array nprocs : int, optional Number of processor cores to be used for calculations. Attributes ---------- shape : tuple Swath shape size : int Number of elements in swath ndims : int Swath dimensions lons : object Swath lons lats : object Swath lats cartesian_coords : object Swath cartesian coordinates """ def __init__(self, lons, lats, nprocs=1): if not isinstance(lons, (np.ndarray, DataArray)): lons = np.asanyarray(lons) lats = np.asanyarray(lats) super(SwathDefinition, self).__init__(lons, lats, nprocs) if lons.shape != lats.shape: raise ValueError('lon and lat arrays must have same shape') elif lons.ndim > 2: raise ValueError('Only 1 and 2 dimensional swaths are allowed') def copy(self): """Copy the current swath.""" return SwathDefinition(self.lons, self.lats) @staticmethod def _do_transform(src, dst, lons, lats, alt): """Helper for 'aggregate' method.""" x, y, z = transform(src, dst, lons, lats, alt) return np.dstack((x, y, z)) def aggregate(self, **dims): """Aggregate the current swath definition by averaging. For example, averaging over 2x2 windows: `sd.aggregate(x=2, y=2)` """ import pyproj import dask.array as da geocent = pyproj.Proj(proj='geocent') latlong = pyproj.Proj(proj='latlong') res = da.map_blocks(self._do_transform, latlong, geocent, self.lons.data, self.lats.data, da.zeros_like(self.lons.data), new_axis=[2], chunks=(self.lons.chunks[0], self.lons.chunks[1], 3)) res = DataArray(res, dims=['y', 'x', 'coord'], coords=self.lons.coords) res = res.coarsen(**dims).mean() lonlatalt = da.map_blocks(self._do_transform, geocent, latlong, res[:, :, 0].data, res[:, :, 1].data, res[:, :, 2].data, new_axis=[2], chunks=res.data.chunks) lons = DataArray(lonlatalt[:, :, 0], dims=self.lons.dims, coords=res.coords, attrs=self.lons.attrs.copy()) lats = DataArray(lonlatalt[:, :, 1], dims=self.lons.dims, coords=res.coords, attrs=self.lons.attrs.copy()) try: resolution = lons.attrs['resolution'] / ((dims.get('x', 1) + dims.get('y', 1)) / 2) lons.attrs['resolution'] = resolution lats.attrs['resolution'] = resolution except KeyError: pass return SwathDefinition(lons, lats) def __hash__(self): """Compute the hash of this object.""" if self.hash is None: self.hash = int(self.update_hash().hexdigest(), 16) return self.hash def update_hash(self, the_hash=None): if the_hash is None: the_hash = hashlib.sha1() the_hash.update(get_array_hashable(self.lons)) the_hash.update(get_array_hashable(self.lats)) try: if self.lons.mask is not np.bool_(False): the_hash.update(get_array_hashable(self.lons.mask)) except AttributeError: pass return the_hash def _compute_omerc_parameters(self, ellipsoid): """Compute the oblique mercator projection bouding box parameters.""" lines, cols = self.lons.shape lon1, lon2 = np.asanyarray(self.lons[[0, -1], int(cols / 2)]) lat1, lat, lat2 = np.asanyarray( self.lats[[0, int(lines / 2), -1], int(cols / 2)]) if any(np.isnan((lon1, lon2, lat1, lat, lat2))): thelons = self.lons[:, int(cols / 2)] thelons = thelons.where(thelons.notnull(), drop=True) thelats = self.lats[:, int(cols / 2)] thelats = thelats.where(thelats.notnull(), drop=True) lon1, lon2 = np.asanyarray(thelons[[0, -1]]) lines = len(thelats) lat1, lat, lat2 = np.asanyarray(thelats[[0, int(lines / 2), -1]]) proj_dict2points = {'proj': 'omerc', 'lat_0': lat, 'ellps': ellipsoid, 'lat_1': lat1, 'lon_1': lon1, 'lat_2': lat2, 'lon_2': lon2, 'no_rot': True } # We need to compute alpha-based omerc for geotiff support lonc, lat0 = Proj(**proj_dict2points)(0, 0, inverse=True) az1, az2, dist = Geod(**proj_dict2points).inv(lonc, lat0, lon2, lat2) azimuth = az1 az1, az2, dist = Geod(**proj_dict2points).inv(lonc, lat0, lon1, lat1) if abs(az1 - azimuth) > 1: if abs(az2 - azimuth) > 1: logger.warning("Can't find appropriate azimuth.") else: azimuth += az2 azimuth /= 2 else: azimuth += az1 azimuth /= 2 if abs(azimuth) > 90: azimuth = 180 + azimuth prj_params = {'proj': 'omerc', 'alpha': float(azimuth), 'lat_0': float(lat0), 'lonc': float(lonc), 'gamma': 0, 'ellps': ellipsoid} return prj_params def _compute_generic_parameters(self, projection, ellipsoid): """Compute the projection bb parameters for most projections.""" lines, cols = self.lons.shape lat_0 = self.lats[int(lines / 2), int(cols / 2)] lon_0 = self.lons[int(lines / 2), int(cols / 2)] return {'proj': projection, 'ellps': ellipsoid, 'lat_0': lat_0, 'lon_0': lon_0} def get_edge_lonlats(self): """Get the concatenated boundary of the current swath.""" lons, lats = self.get_bbox_lonlats() blons = np.ma.concatenate(lons) blats = np.ma.concatenate(lats) return blons, blats def compute_bb_proj_params(self, proj_dict): projection = proj_dict['proj'] ellipsoid = proj_dict.get('ellps', 'WGS84') if projection == 'omerc': return self._compute_omerc_parameters(ellipsoid) else: new_proj = self._compute_generic_parameters(projection, ellipsoid) new_proj.update(proj_dict) return new_proj def _compute_uniform_shape(self): """Compute the height and width of a domain to have uniform resolution across dimensions.""" g = Geod(ellps='WGS84') leftlons = self.lons[:, 0] leftlons = leftlons.where(leftlons.notnull(), drop=True) rightlons = self.lons[:, -1] rightlons = rightlons.where(rightlons.notnull(), drop=True) middlelons = self.lons[:, int(self.lons.shape[1] / 2)] middlelons = middlelons.where(middlelons.notnull(), drop=True) leftlats = self.lats[:, 0] leftlats = leftlats.where(leftlats.notnull(), drop=True) rightlats = self.lats[:, -1] rightlats = rightlats.where(rightlats.notnull(), drop=True) middlelats = self.lats[:, int(self.lats.shape[1] / 2)] middlelats = middlelats.where(middlelats.notnull(), drop=True) az1, az2, width1 = g.inv(leftlons[0], leftlats[0], rightlons[0], rightlats[0]) az1, az2, width2 = g.inv(leftlons[-1], leftlats[-1], rightlons[-1], rightlats[-1]) az1, az2, height = g.inv(middlelons[0], middlelats[0], middlelons[-1], middlelats[-1]) width = min(width1, width2) vresolution = height * 1.0 / self.lons.shape[0] hresolution = width * 1.0 / self.lons.shape[1] resolution = min(vresolution, hresolution) width = int(width * 1.1 / resolution) height = int(height * 1.1 / resolution) return height, width def compute_optimal_bb_area(self, proj_dict=None): """Compute the "best" bounding box area for this swath with `proj_dict`. By default, the projection is Oblique Mercator (`omerc` in proj.4), in which case the right projection angle `alpha` is computed from the swath centerline. For other projections, only the appropriate center of projection and area extents are computed. The height and width are computed so that the resolution is approximately the same across dimensions. """ if proj_dict is None: proj_dict = {} projection = proj_dict.setdefault('proj', 'omerc') area_id = projection + '_otf' description = 'On-the-fly ' + projection + ' area' height, width = self._compute_uniform_shape() proj_dict = self.compute_bb_proj_params(proj_dict) area = DynamicAreaDefinition(area_id, description, proj_dict) lons, lats = self.get_edge_lonlats() return area.freeze((lons, lats), shape=(height, width)) class DynamicAreaDefinition(object): """An AreaDefintion containing just a subset of the needed parameters. The purpose of this class is to be able to adapt the area extent and shape of the area to a given set of longitudes and latitudes, such that e.g. polar satellite granules can be resampled optimaly to a give projection. """ def __init__(self, area_id=None, description=None, projection=None, width=None, height=None, area_extent=None, resolution=None, optimize_projection=False, rotation=None): """Initialize the DynamicAreaDefinition. area_id: The name of the area. description: The description of the area. projection: The dictionary or string of projection parameters. Doesn't have to be complete. height, width: The shape of the resulting area. area_extent: The area extent of the area. resolution: the resolution of the resulting area. optimize_projection: Whether the projection parameters have to be optimized. rotation: Rotation in degrees (negative is cw) """ if isinstance(projection, str): proj_dict = proj4_str_to_dict(projection) elif isinstance(projection, dict): proj_dict = projection else: raise TypeError('Wrong type for projection: {0}. Expected dict or string.'.format(type(projection))) self.area_id = area_id self.description = description self.proj_dict = proj_dict self.width = self.width = width self.height = self.height = height self.area_extent = area_extent self.optimize_projection = optimize_projection self.resolution = resolution self.rotation = rotation # size = (x_size, y_size) and shape = (y_size, x_size) def compute_domain(self, corners, resolution=None, shape=None): """Compute shape and area_extent from corners and [shape or resolution] info. Corners represents the center of pixels, while area_extent represents the edge of pixels. """ if resolution is not None and shape is not None: raise ValueError("Both resolution and shape can't be provided.") elif resolution is None and shape is None: raise ValueError("Either resolution or shape must be provided.") if shape: height, width = shape x_resolution = (corners[2] - corners[0]) * 1.0 / (width - 1) y_resolution = (corners[3] - corners[1]) * 1.0 / (height - 1) else: try: x_resolution, y_resolution = resolution except TypeError: x_resolution = y_resolution = resolution width = int(np.rint((corners[2] - corners[0]) * 1.0 / x_resolution + 1)) height = int(np.rint((corners[3] - corners[1]) * 1.0 / y_resolution + 1)) area_extent = (corners[0] - x_resolution / 2, corners[1] - y_resolution / 2, corners[2] + x_resolution / 2, corners[3] + y_resolution / 2) return area_extent, width, height def freeze(self, lonslats=None, resolution=None, shape=None, proj_info=None): """Create an AreaDefinition from this area with help of some extra info. lonlats: the geographical coordinates to contain in the resulting area. resolution: the resolution of the resulting area. shape: the shape of the resulting area. proj_info: complementing parameters to the projection info. Resolution and shape parameters are ignored if the instance is created with the `optimize_projection` flag set to True. """ if proj_info is not None: self.proj_dict.update(proj_info) if self.optimize_projection: return lonslats.compute_optimal_bb_area(self.proj_dict) if resolution is None: resolution = self.resolution if not self.area_extent or not self.width or not self.height: proj4 = Proj(**self.proj_dict) try: lons, lats = lonslats except (TypeError, ValueError): lons, lats = lonslats.get_lonlats() xarr, yarr = proj4(np.asarray(lons), np.asarray(lats)) xarr[xarr > 9e29] = np.nan yarr[yarr > 9e29] = np.nan corners = [np.nanmin(xarr), np.nanmin(yarr), np.nanmax(xarr), np.nanmax(yarr)] # Note: size=(width, height) was changed to shape=(height, width). domain = self.compute_domain(corners, resolution, shape) self.area_extent, self.width, self.height = domain return AreaDefinition(self.area_id, self.description, '', self.proj_dict, self.width, self.height, self.area_extent, self.rotation) def invproj(data_x, data_y, proj_dict): """Perform inverse projection.""" # XXX: does pyproj copy arrays? What can we do so it doesn't? target_proj = Proj(**proj_dict) return np.dstack(target_proj(data_x, data_y, inverse=True)) class AreaDefinition(BaseDefinition): """Holds definition of an area. Parameters ---------- area_id : str Identifier for the area description : str Human-readable description of the area proj_id : str ID of projection projection: dict or str Dictionary or string of Proj.4 parameters width : int x dimension in number of pixels, aka number of grid columns height : int y dimension in number of pixels, aka number of grid rows rotation: float rotation in degrees (negative is cw) area_extent : list Area extent as a list (lower_left_x, lower_left_y, upper_right_x, upper_right_y) nprocs : int, optional Number of processor cores to be used for certain calculations Attributes ---------- area_id : str Identifier for the area description : str Human-readable description of the area proj_id : str ID of projection projection : dict or str Dictionary or string with Proj.4 parameters width : int x dimension in number of pixels, aka number of grid columns height : int y dimension in number of pixels, aka number of grid rows rotation: float rotation in degrees (negative is cw) shape : tuple Corresponding array shape as (height, width) size : int Number of points in grid area_extent : tuple Area extent as a tuple (lower_left_x, lower_left_y, upper_right_x, upper_right_y) area_extent_ll : tuple Area extent in lons lats as a tuple (lower_left_lon, lower_left_lat, upper_right_lon, upper_right_lat) pixel_size_x : float Pixel width in projection units pixel_size_y : float Pixel height in projection units upper_left_extent : tuple Coordinates (x, y) of upper left corner of upper left pixel in projection units pixel_upper_left : tuple Coordinates (x, y) of center of upper left pixel in projection units pixel_offset_x : float x offset between projection center and upper left corner of upper left pixel in units of pixels. pixel_offset_y : float y offset between projection center and upper left corner of upper left pixel in units of pixels.. proj4_string : str Projection defined as Proj.4 string cartesian_coords : object Grid cartesian coordinates projection_x_coords : object Grid projection x coordinate projection_y_coords : object Grid projection y coordinate """ def __init__(self, area_id, description, proj_id, projection, width, height, area_extent, rotation=None, nprocs=1, lons=None, lats=None, dtype=np.float64): if isinstance(projection, str): proj_dict = proj4_str_to_dict(projection) elif isinstance(projection, dict): proj_dict = projection else: raise TypeError('Wrong type for projection: {0}. Expected dict or string.'.format(type(projection))) super(AreaDefinition, self).__init__(lons, lats, nprocs) self.area_id = area_id self.description = description self.proj_id = proj_id self.width = int(width) self.height = int(height) self.crop_offset = (0, 0) try: self.rotation = float(rotation) except TypeError: self.rotation = 0 if lons is not None: if lons.shape != self.shape: raise ValueError('Shape of lon lat grid must match ' 'area definition') self.size = height * width self.ndim = 2 self.pixel_size_x = (area_extent[2] - area_extent[0]) / float(width) self.pixel_size_y = (area_extent[3] - area_extent[1]) / float(height) self.proj_dict = convert_proj_floats(proj_dict.items()) self.area_extent = tuple(area_extent) # Calculate area_extent in lon lat proj = Proj(**proj_dict) corner_lons, corner_lats = proj((area_extent[0], area_extent[2]), (area_extent[1], area_extent[3]), inverse=True) self.area_extent_ll = (corner_lons[0], corner_lats[0], corner_lons[1], corner_lats[1]) # Calculate projection coordinates of extent of upper left pixel self.upper_left_extent = (float(area_extent[0]), float(area_extent[3])) self.pixel_upper_left = (float(area_extent[0]) + float(self.pixel_size_x) / 2, float(area_extent[3]) - float(self.pixel_size_y) / 2) # Pixel_offset defines the distance to projection center from origin # (UL) of image in units of pixels. self.pixel_offset_x = -self.area_extent[0] / self.pixel_size_x self.pixel_offset_y = self.area_extent[3] / self.pixel_size_y self._projection_x_coords = None self._projection_y_coords = None self.dtype = dtype def copy(self, **override_kwargs): """Make a copy of the current area. This replaces the current values with anything in *override_kwargs*. """ kwargs = {'area_id': self.area_id, 'description': self.description, 'proj_id': self.proj_id, 'projection': self.proj_dict, 'width': self.width, 'height': self.height, 'area_extent': self.area_extent, 'rotation': self.rotation} kwargs.update(override_kwargs) return AreaDefinition(**kwargs) def aggregate(self, **dims): """Return an aggregated version of the area.""" width = int(self.width / dims.get('x', 1)) height = int(self.height / dims.get('y', 1)) return self.copy(height=height, width=width) @property def shape(self): return self.height, self.width @property def name(self): warnings.warn("'name' is deprecated, use 'description' instead.", PendingDeprecationWarning) return self.description @property def x_size(self): warnings.warn("'x_size' is deprecated, use 'width' instead.", PendingDeprecationWarning) return self.width @property def y_size(self): warnings.warn("'y_size' is deprecated, use 'height' instead.", PendingDeprecationWarning) return self.height @classmethod def from_extent(cls, area_id, projection, shape, area_extent, units=None, **kwargs): """Creates an AreaDefinition object from area_extent and shape. Parameters ---------- area_id : str ID of area projection : dict or str Projection parameters as a proj4_dict or proj4_string shape : list Number of pixels in the y and x direction (height, width) area_extent : list Area extent as a list (lower_left_x, lower_left_y, upper_right_x, upper_right_y) units : str, optional Units that provided arguments should be interpreted as. This can be one of 'deg', 'degrees', 'meters', 'metres', and any parameter supported by the `cs2cs -lu <https://proj4.org/apps/cs2cs.html#cmdoption-cs2cs-lu>`_ command. Units are determined in the following priority: 1. units expressed with each variable through a DataArray's attrs attribute. 2. units passed to ``units`` 3. units used in ``projection`` 4. meters description : str, optional Description/name of area. Defaults to area_id proj_id : str, optional ID of projection rotation: float, optional rotation in degrees (negative is cw) nprocs : int, optional Number of processor cores to be used lons : numpy array, optional Grid lons lats : numpy array, optional Grid lats Returns ------- AreaDefinition : AreaDefinition """ return create_area_def(area_id, projection, shape=shape, area_extent=area_extent, units=units, **kwargs) @classmethod def from_circle(cls, area_id, projection, center, radius, shape=None, resolution=None, units=None, **kwargs): """Creates an AreaDefinition object from center, radius, and shape or from center, radius, and resolution. Parameters ---------- area_id : str ID of area projection : dict or str Projection parameters as a proj4_dict or proj4_string center : list Center of projection (x, y) radius : list or float Length from the center to the edges of the projection (dx, dy) shape : list, optional Number of pixels in the y and x direction (height, width) resolution : list or float, optional Size of pixels: (dx, dy) units : str, optional Units that provided arguments should be interpreted as. This can be one of 'deg', 'degrees', 'meters', 'metres', and any parameter supported by the `cs2cs -lu <https://proj4.org/apps/cs2cs.html#cmdoption-cs2cs-lu>`_ command. Units are determined in the following priority: 1. units expressed with each variable through a DataArray's attrs attribute. 2. units passed to ``units`` 3. units used in ``projection`` 4. meters description : str, optional Description/name of area. Defaults to area_id proj_id : str, optional ID of projection rotation: float, optional rotation in degrees (negative is cw) nprocs : int, optional Number of processor cores to be used lons : numpy array, optional Grid lons lats : numpy array, optional Grid lats optimize_projection: Whether the projection parameters have to be optimized for a DynamicAreaDefinition. Returns ------- AreaDefinition or DynamicAreaDefinition : AreaDefinition or DynamicAreaDefinition If shape or resolution are provided, an AreaDefinition object is returned. Else a DynamicAreaDefinition object is returned Notes ----- * ``resolution`` and ``radius`` can be specified with one value if dx == dy """ return create_area_def(area_id, projection, shape=shape, center=center, radius=radius, resolution=resolution, units=units, **kwargs) @classmethod def from_area_of_interest(cls, area_id, projection, shape, center, resolution, units=None, **kwargs): """Creates an AreaDefinition object from center, resolution, and shape. Parameters ---------- area_id : str ID of area projection : dict or str Projection parameters as a proj4_dict or proj4_string shape : list Number of pixels in the y and x direction (height, width) center : list Center of projection (x, y) resolution : list or float Size of pixels: (dx, dy). Can be specified with one value if dx == dy units : str, optional Units that provided arguments should be interpreted as. This can be one of 'deg', 'degrees', 'meters', 'metres', and any parameter supported by the `cs2cs -lu <https://proj4.org/apps/cs2cs.html#cmdoption-cs2cs-lu>`_ command. Units are determined in the following priority: 1. units expressed with each variable through a DataArray's attrs attribute. 2. units passed to ``units`` 3. units used in ``projection`` 4. meters description : str, optional Description/name of area. Defaults to area_id proj_id : str, optional ID of projection rotation: float, optional rotation in degrees (negative is cw) nprocs : int, optional Number of processor cores to be used lons : numpy array, optional Grid lons lats : numpy array, optional Grid lats Returns ------- AreaDefinition : AreaDefinition """ return create_area_def(area_id, projection, shape=shape, center=center, resolution=resolution, units=units, **kwargs) @classmethod def from_ul_corner(cls, area_id, projection, shape, upper_left_extent, resolution, units=None, **kwargs): """Creates an AreaDefinition object from upper_left_extent, resolution, and shape. Parameters ---------- area_id : str ID of area projection : dict or str Projection parameters as a proj4_dict or proj4_string shape : list Number of pixels in the y and x direction (height, width) upper_left_extent : list Upper left corner of upper left pixel (x, y) resolution : list or float Size of pixels in **meters**: (dx, dy). Can be specified with one value if dx == dy units : str, optional Units that provided arguments should be interpreted as. This can be one of 'deg', 'degrees', 'meters', 'metres', and any parameter supported by the `cs2cs -lu <https://proj4.org/apps/cs2cs.html#cmdoption-cs2cs-lu>`_ command. Units are determined in the following priority: 1. units expressed with each variable through a DataArray's attrs attribute. 2. units passed to ``units`` 3. units used in ``projection`` 4. meters description : str, optional Description/name of area. Defaults to area_id proj_id : str, optional ID of projection rotation: float, optional rotation in degrees (negative is cw) nprocs : int, optional Number of processor cores to be used lons : numpy array, optional Grid lons lats : numpy array, optional Grid lats Returns ------- AreaDefinition : AreaDefinition """ return create_area_def(area_id, projection, shape=shape, upper_left_extent=upper_left_extent, resolution=resolution, units=units, **kwargs) def __hash__(self): """Compute the hash of this object.""" if self.hash is None: self.hash = int(self.update_hash().hexdigest(), 16) return self.hash @property def proj_str(self): return proj4_dict_to_str(self.proj_dict, sort=True) def __str__(self): # We need a sorted dictionary for a unique hash of str(self) proj_dict = self.proj_dict proj_str = ('{' + ', '.join(["'%s': '%s'" % (str(k), str(proj_dict[k])) for k in sorted(proj_dict.keys())]) + '}') if not self.proj_id: third_line = "" else: third_line = "Projection ID: {0}\n".format(self.proj_id) return ('Area ID: {0}\nDescription: {1}\n{2}' 'Projection: {3}\nNumber of columns: {4}\nNumber of rows: {5}\n' 'Area extent: {6}').format(self.area_id, self.description, third_line, proj_str, self.width, self.height, tuple(round(x, 4) for x in self.area_extent)) __repr__ = __str__ def to_cartopy_crs(self): from pyresample._cartopy import from_proj bounds = (self.area_extent[0], self.area_extent[2], self.area_extent[1], self.area_extent[3]) if Proj(self.proj_dict).is_latlong(): # Convert area extent from degrees to radians bounds = np.deg2rad(bounds) crs = from_proj(self.proj_str, bounds=bounds) return crs def create_areas_def(self): res = OrderedDict(description=self.description, projection=OrderedDict(self.proj_dict), shape=OrderedDict([('height', self.height), ('width', self.width)])) units = res['projection'].pop('units', None) extent = OrderedDict([('lower_left_xy', list(self.area_extent[:2])), ('upper_right_xy', list(self.area_extent[2:]))]) if units is not None: extent['units'] = units res['area_extent'] = extent return ordered_dump(OrderedDict([(self.area_id, res)])) def create_areas_def_legacy(self): proj_dict = self.proj_dict proj_str = ','.join(["%s=%s" % (str(k), str(proj_dict[k])) for k in sorted(proj_dict.keys())]) fmt = "REGION: {name} {{\n" fmt += "\tNAME:\t{name}\n" fmt += "\tPCS_ID:\t{area_id}\n" fmt += "\tPCS_DEF:\t{proj_str}\n" fmt += "\tXSIZE:\t{x_size}\n" fmt += "\tYSIZE:\t{y_size}\n" # fmt += "\tROTATION:\t{rotation}\n" fmt += "\tAREA_EXTENT: {area_extent}\n}};\n" area_def_str = fmt.format(name=self.description, area_id=self.area_id, proj_str=proj_str, x_size=self.width, y_size=self.height, area_extent=self.area_extent) return area_def_str def __eq__(self, other): """Test for equality""" try: return ((self.proj_str == other.proj_str) and (self.shape == other.shape) and (np.allclose(self.area_extent, other.area_extent))) except AttributeError: return super(AreaDefinition, self).__eq__(other) def __ne__(self, other): """Test for equality""" return not self.__eq__(other) def update_hash(self, the_hash=None): """Update a hash, or return a new one if needed.""" if the_hash is None: the_hash = hashlib.sha1() the_hash.update(self.proj_str.encode('utf-8')) the_hash.update(np.array(self.shape)) the_hash.update(np.array(self.area_extent)) return the_hash def colrow2lonlat(self, cols, rows): """ Return longitudes and latitudes for the given image columns and rows. Both scalars and arrays are supported. To be used with scarse data points instead of slices (see get_lonlats). """ p = Proj(self.proj_str) x = self.projection_x_coords y = self.projection_y_coords return p(y[y.size - cols], x[x.size - rows], inverse=True) def lonlat2colrow(self, lons, lats): """ Return image columns and rows for the given longitudes and latitudes. Both scalars and arrays are supported. Same as get_xy_from_lonlat, renamed for convenience. """ return self.get_xy_from_lonlat(lons, lats) def get_xy_from_lonlat(self, lon, lat): """Retrieve closest x and y coordinates (column, row indices) for the specified geolocation (lon,lat) if inside area. If lon,lat is a point a ValueError is raised if the return point is outside the area domain. If lon,lat is a tuple of sequences of longitudes and latitudes, a tuple of masked arrays are returned. :Input: lon : point or sequence (list or array) of longitudes lat : point or sequence (list or array) of latitudes :Returns: (x, y) : tuple of integer points/arrays """ if isinstance(lon, list): lon = np.array(lon) if isinstance(lat, list): lat = np.array(lat) if ((isinstance(lon, np.ndarray) and not isinstance(lat, np.ndarray)) or (not isinstance(lon, np.ndarray) and isinstance(lat, np.ndarray))): raise ValueError("Both lon and lat needs to be of " + "the same type and have the same dimensions!") if isinstance(lon, np.ndarray) and isinstance(lat, np.ndarray): if lon.shape != lat.shape: raise ValueError("lon and lat is not of the same shape!") pobj = Proj(self.proj_str) xm_, ym_ = pobj(lon, lat) return self.get_xy_from_proj_coords(xm_, ym_) def get_xy_from_proj_coords(self, xm, ym): """Find closest grid cell index for a specified projection coordinate. If xm, ym is a tuple of sequences of projection coordinates, a tuple of masked arrays are returned. Args: xm (list or array): point or sequence of x-coordinates in meters (map projection) ym (list or array): point or sequence of y-coordinates in meters (map projection) Returns: x, y : column and row grid cell indexes as 2 scalars or arrays Raises: ValueError: if the return point is outside the area domain """ if isinstance(xm, list): xm = np.array(xm) if isinstance(ym, list): ym = np.array(ym) if ((isinstance(xm, np.ndarray) and not isinstance(ym, np.ndarray)) or (not isinstance(xm, np.ndarray) and isinstance(ym, np.ndarray))): raise ValueError("Both projection coordinates xm and ym needs to be of " + "the same type and have the same dimensions!") if isinstance(xm, np.ndarray) and isinstance(ym, np.ndarray): if xm.shape != ym.shape: raise ValueError( "projection coordinates xm and ym is not of the same shape!") upl_x = self.area_extent[0] upl_y = self.area_extent[3] xscale = (self.area_extent[2] - self.area_extent[0]) / float(self.width) # because rows direction is the opposite of y's yscale = (self.area_extent[1] - self.area_extent[3]) / float(self.height) x__ = (xm - upl_x) / xscale y__ = (ym - upl_y) / yscale if isinstance(x__, np.ndarray) and isinstance(y__, np.ndarray): mask = (((x__ < 0) | (x__ >= self.width)) | ((y__ < 0) | (y__ >= self.height))) return (np.ma.masked_array(x__.astype('int'), mask=mask, fill_value=-1, copy=False), np.ma.masked_array(y__.astype('int'), mask=mask, fill_value=-1, copy=False)) else: if ((x__ < 0 or x__ >= self.width) or (y__ < 0 or y__ >= self.height)): raise ValueError('Point outside area:( %f %f)' % (x__, y__)) return int(x__), int(y__) def get_lonlat(self, row, col): """Retrieves lon and lat values of single point in area grid Parameters ---------- row : int col : int Returns ------- (lon, lat) : tuple of floats """ lon, lat = self.get_lonlats(nprocs=None, data_slice=(row, col)) return np.asscalar(lon), np.asscalar(lat) @staticmethod def _do_rotation(xspan, yspan, rot_deg=0): """Helper method to apply a rotation factor to a matrix of points.""" if hasattr(xspan, 'chunks'): # we were given dask arrays, use dask functions import dask.array as numpy else: numpy = np rot_rad = numpy.radians(rot_deg) rot_mat = numpy.array([[np.cos(rot_rad), np.sin(rot_rad)], [-np.sin(rot_rad), np.cos(rot_rad)]]) x, y = numpy.meshgrid(xspan, yspan) return numpy.einsum('ji, mni -> jmn', rot_mat, numpy.dstack([x, y])) def get_proj_vectors_dask(self, chunks=None, dtype=None): warnings.warn("'get_proj_vectors_dask' is deprecated, please use " "'get_proj_vectors' with the 'chunks' keyword argument specified.", DeprecationWarning) if chunks is None: chunks = CHUNK_SIZE # FUTURE: Use a global config object instead return self.get_proj_vectors(dtype=dtype, chunks=chunks) def _get_proj_vectors(self, dtype=None, check_rotation=True, chunks=None): """Helper for getting 1D projection coordinates.""" x_kwargs = {} y_kwargs = {} if chunks is not None and not isinstance(chunks, int): y_chunks = chunks[0] x_chunks = chunks[1] else: y_chunks = x_chunks = chunks if x_chunks is not None or y_chunks is not None: # use dask functions instead of numpy from dask.array import arange x_kwargs = {'chunks': x_chunks} y_kwargs = {'chunks': y_chunks} else: arange = np.arange if check_rotation and self.rotation != 0: warnings.warn("Projection vectors will not be accurate because rotation is not 0", RuntimeWarning) if dtype is None: dtype = self.dtype x_kwargs['dtype'] = dtype y_kwargs['dtype'] = dtype target_x = arange(self.width, **x_kwargs) * self.pixel_size_x + self.pixel_upper_left[0] target_y = arange(self.height, **y_kwargs) * -self.pixel_size_y + self.pixel_upper_left[1] return target_x, target_y def get_proj_vectors(self, dtype=None, chunks=None): """Calculate 1D projection coordinates for the X and Y dimension. Parameters ---------- dtype : numpy.dtype Numpy data type for the returned arrays chunks : int or tuple Return dask arrays with the chunk size specified. If this is a tuple then the first element is the Y array's chunk size and the second is the X array's chunk size. Returns ------- tuple: (X, Y) where X and Y are 1-dimensional numpy arrays The data type of the returned arrays can be controlled with the `dtype` keyword argument. If `chunks` is provided then dask arrays are returned instead. """ return self._get_proj_vectors(dtype=dtype, chunks=chunks) def get_proj_coords_dask(self, chunks=None, dtype=None): warnings.warn("'get_proj_coords_dask' is deprecated, please use " "'get_proj_coords' with the 'chunks' keyword argument specified.", DeprecationWarning) if chunks is None: chunks = CHUNK_SIZE # FUTURE: Use a global config object instead return self.get_proj_coords(chunks=chunks, dtype=dtype) def get_proj_coords(self, data_slice=None, dtype=None, chunks=None): """Get projection coordinates of grid. Parameters ---------- data_slice : slice object, optional Calculate only coordinates for specified slice dtype : numpy.dtype, optional Data type of the returned arrays chunks: int or tuple, optional Create dask arrays and use this chunk size Returns ------- (target_x, target_y) : tuple of numpy arrays Grids of area x- and y-coordinates in projection units .. versionchanged:: 1.11.0 Removed 'cache' keyword argument and add 'chunks' for creating dask arrays. """ target_x, target_y = self._get_proj_vectors(dtype=dtype, check_rotation=False, chunks=chunks) if data_slice is not None and isinstance(data_slice, slice): target_y = target_y[data_slice] elif data_slice is not None: target_y = target_y[data_slice[0]] target_x = target_x[data_slice[1]] if self.rotation != 0: res = self._do_rotation(target_x, target_y, self.rotation) target_x, target_y = res[0, :, :], res[1, :, :] elif chunks is not None: import dask.array as da target_x, target_y = da.meshgrid(target_x, target_y) else: target_x, target_y = np.meshgrid(target_x, target_y) return target_x, target_y @property def projection_x_coords(self): if self.rotation != 0: # rotation is only supported in 'get_proj_coords' right now return self.get_proj_coords(data_slice=(0, slice(None)))[0].squeeze() return self.get_proj_vectors()[0] @property def projection_y_coords(self): if self.rotation != 0: # rotation is only supported in 'get_proj_coords' right now return self.get_proj_coords(data_slice=(slice(None), 0))[1].squeeze() return self.get_proj_vectors()[1] @property def outer_boundary_corners(self): """Return the lon,lat of the outer edges of the corner points.""" from pyresample.spherical_geometry import Coordinate proj = Proj(**self.proj_dict) corner_lons, corner_lats = proj((self.area_extent[0], self.area_extent[2], self.area_extent[2], self.area_extent[0]), (self.area_extent[3], self.area_extent[3], self.area_extent[1], self.area_extent[1]), inverse=True) return [Coordinate(corner_lons[0], corner_lats[0]), Coordinate(corner_lons[1], corner_lats[1]), Coordinate(corner_lons[2], corner_lats[2]), Coordinate(corner_lons[3], corner_lats[3])] def get_lonlats_dask(self, chunks=None, dtype=None): warnings.warn("'get_lonlats_dask' is deprecated, please use " "'get_lonlats' with the 'chunks' keyword argument specified.", DeprecationWarning) if chunks is None: chunks = CHUNK_SIZE # FUTURE: Use a global config object instead return self.get_lonlats(chunks=chunks, dtype=dtype) def get_lonlats(self, nprocs=None, data_slice=None, cache=False, dtype=None, chunks=None): """Return lon and lat arrays of area. Parameters ---------- nprocs : int, optional Number of processor cores to be used. Defaults to the nprocs set when instantiating object data_slice : slice object, optional Calculate only coordinates for specified slice cache : bool, optional Store result the result. Requires data_slice to be None dtype : numpy.dtype, optional Data type of the returned arrays chunks: int or tuple, optional Create dask arrays and use this chunk size Returns ------- (lons, lats) : tuple of numpy arrays Grids of area lons and and lats """ if cache: warnings.warn("'cache' keyword argument will be removed in the " "future and data will not be cached.", PendingDeprecationWarning) if dtype is None: dtype = self.dtype if self.lons is not None: # Data is cache already lons = self.lons lats = self.lats if data_slice is not None: lons = lons[data_slice] lats = lats[data_slice] return lons, lats # Get X/Y coordinates for the whole area target_x, target_y = self.get_proj_coords(data_slice=data_slice, chunks=chunks, dtype=dtype) if nprocs is None and not hasattr(target_x, 'chunks'): nprocs = self.nprocs if nprocs is not None and hasattr(target_x, 'chunks'): # we let 'get_proj_coords' decide if dask arrays should be made # but if the user provided nprocs then this doesn't make sense raise ValueError("Can't specify 'nprocs' and 'chunks' at the same time") # Proj.4 definition of target area projection if hasattr(target_x, 'chunks'): # we are using dask arrays, map blocks to th from dask.array import map_blocks res = map_blocks(invproj, target_x, target_y, chunks=(target_x.chunks[0], target_x.chunks[1], 2), new_axis=[2], proj_dict=self.proj_dict) return res[:, :, 0], res[:, :, 1] if nprocs > 1: target_proj = Proj_MP(**self.proj_dict) else: target_proj = Proj(**self.proj_dict) # Get corresponding longitude and latitude values lons, lats = target_proj(target_x, target_y, inverse=True, nprocs=nprocs) lons = np.asanyarray(lons, dtype=dtype) lats = np.asanyarray(lats, dtype=dtype) if cache and data_slice is None: # Cache the result if requested self.lons = lons self.lats = lats return lons, lats @property def proj4_string(self): """Return projection definition as Proj.4 string.""" warnings.warn("'proj4_string' is deprecated, please use 'proj_str' " "instead.", DeprecationWarning) return proj4_dict_to_str(self.proj_dict) def get_area_slices(self, area_to_cover): """Compute the slice to read based on an `area_to_cover`.""" if not isinstance(area_to_cover, AreaDefinition): raise NotImplementedError('Only AreaDefinitions can be used') # Intersection only required for two different projections if area_to_cover.proj_str == self.proj_str: logger.debug('Projections for data and slice areas are' ' identical: %s', area_to_cover.proj_dict.get('proj', area_to_cover.proj_dict.get('init'))) # Get xy coordinates llx, lly, urx, ury = area_to_cover.area_extent x, y = self.get_xy_from_proj_coords([llx, urx], [lly, ury]) xstart = 0 if x[0] is np.ma.masked else x[0] ystart = 0 if y[1] is np.ma.masked else y[1] xstop = self.width if x[1] is np.ma.masked else x[1] + 1 ystop = self.height if y[0] is np.ma.masked else y[0] + 1 return slice(xstart, xstop), slice(ystart, ystop) if self.proj_dict.get('proj') != 'geos': raise NotImplementedError("Source projection must be 'geos' if " "source/target projections are not " "equal.") data_boundary = Boundary(*get_geostationary_bounding_box(self)) if area_to_cover.proj_dict.get('proj') == 'geos': area_boundary = Boundary( *get_geostationary_bounding_box(area_to_cover)) else: area_boundary = AreaDefBoundary(area_to_cover, 100) intersection = data_boundary.contour_poly.intersection( area_boundary.contour_poly) if intersection is None: logger.debug('Cannot determine appropriate slicing.') raise NotImplementedError x, y = self.get_xy_from_lonlat(np.rad2deg(intersection.lon), np.rad2deg(intersection.lat)) return (slice(np.ma.min(x), np.ma.max(x) + 1), slice(np.ma.min(y), np.ma.max(y) + 1)) def crop_around(self, other_area): """Crop this area around `other_area`.""" xslice, yslice = self.get_area_slices(other_area) return self[yslice, xslice] def __getitem__(self, key): """Apply slices to the area_extent and size of the area.""" yslice, xslice = key # Get actual values, replace Nones yindices = yslice.indices(self.height) total_rows = int((yindices[1] - yindices[0]) / yindices[2]) ystopactual = yindices[1] - (yindices[1] - 1) % yindices[2] xindices = xslice.indices(self.width) total_cols = int((xindices[1] - xindices[0]) / xindices[2]) xstopactual = xindices[1] - (xindices[1] - 1) % xindices[2] yslice = slice(yindices[0], ystopactual, yindices[2]) xslice = slice(xindices[0], xstopactual, xindices[2]) new_area_extent = ((self.pixel_upper_left[0] + (xslice.start - 0.5) * self.pixel_size_x), (self.pixel_upper_left[1] - (yslice.stop - 0.5) * self.pixel_size_y), (self.pixel_upper_left[0] + (xslice.stop - 0.5) * self.pixel_size_x), (self.pixel_upper_left[1] - (yslice.start - 0.5) * self.pixel_size_y)) new_area = AreaDefinition(self.area_id, self.description, self.proj_id, self.proj_dict, total_cols, total_rows, new_area_extent) new_area.crop_offset = (self.crop_offset[0] + yslice.start, self.crop_offset[1] + xslice.start) return new_area def get_geostationary_angle_extent(geos_area): """Get the max earth (vs space) viewing angles in x and y.""" # get some projection parameters req = geos_area.proj_dict['a'] / 1000 rp = geos_area.proj_dict['b'] / 1000 h = geos_area.proj_dict['h'] / 1000 + req # compute some constants aeq = 1 - req ** 2 / (h ** 2) ap_ = 1 - rp ** 2 / (h ** 2) # generate points around the north hemisphere in satellite projection # make it a bit smaller so that we stay inside the valid area xmax = np.arccos(np.sqrt(aeq)) ymax = np.arccos(np.sqrt(ap_)) return xmax, ymax def get_geostationary_bounding_box(geos_area, nb_points=50): """Get the bbox in lon/lats of the valid pixels inside `geos_area`. Args: nb_points: Number of points on the polygon """ xmax, ymax = get_geostationary_angle_extent(geos_area) # generate points around the north hemisphere in satellite projection # make it a bit smaller so that we stay inside the valid area x = np.cos(np.linspace(-np.pi, 0, int(nb_points / 2))) * (xmax - 0.0001) y = -np.sin(np.linspace(-np.pi, 0, int(nb_points / 2))) * (ymax - 0.0001) ll_x, ll_y, ur_x, ur_y = geos_area.area_extent x *= geos_area.proj_dict['h'] y *= geos_area.proj_dict['h'] x = np.clip(np.concatenate([x, x[::-1]]), min(ll_x, ur_x), max(ll_x, ur_x)) y = np.clip(np.concatenate([y, -y]), min(ll_y, ur_y), max(ll_y, ur_y)) return Proj(**geos_area.proj_dict)(x, y, inverse=True) def combine_area_extents_vertical(area1, area2): """Combine the area extents of areas 1 and 2.""" if (area1.area_extent[0] == area2.area_extent[0] and area1.area_extent[2] == area2.area_extent[2]): current_extent = list(area1.area_extent) if np.isclose(area1.area_extent[1], area2.area_extent[3]): current_extent[1] = area2.area_extent[1] elif np.isclose(area1.area_extent[3], area2.area_extent[1]): current_extent[3] = area2.area_extent[3] else: raise IncompatibleAreas( "Can't concatenate non-contiguous area definitions: " "{0} and {1}".format(area1, area2)) else: raise IncompatibleAreas( "Can't concatenate area definitions with " "incompatible area extents: " "{0} and {1}".format(area1, area2)) return current_extent def concatenate_area_defs(area1, area2, axis=0): """Append *area2* to *area1* and return the results.""" different_items = (set(area1.proj_dict.items()) ^ set(area2.proj_dict.items())) if axis == 0: same_size = area1.width == area2.width else: raise NotImplementedError('Only vertical contatenation is supported.') if different_items or not same_size: raise IncompatibleAreas("Can't concatenate area definitions with " "different projections: " "{0} and {1}".format(area1, area2)) if axis == 0: area_extent = combine_area_extents_vertical(area1, area2) x_size = int(area1.width) y_size = int(area1.height + area2.height) else: raise NotImplementedError('Only vertical contatenation is supported.') return AreaDefinition(area1.area_id, area1.description, area1.proj_id, area1.proj_dict, x_size, y_size, area_extent) class StackedAreaDefinition(BaseDefinition): """Definition based on muliple vertically stacked AreaDefinitions.""" def __init__(self, *definitions, **kwargs): """Base this instance on *definitions*. *kwargs* used here are `nprocs` and `dtype` (see AreaDefinition). """ nprocs = kwargs.get('nprocs', 1) super(StackedAreaDefinition, self).__init__(nprocs=nprocs) self.dtype = kwargs.get('dtype', np.float64) self.defs = [] self.proj_dict = {} for definition in definitions: self.append(definition) @property def width(self): return self.defs[0].width @property def x_size(self): warnings.warn("'x_size' is deprecated, use 'width' instead.", PendingDeprecationWarning) return self.width @property def height(self): return sum(definition.height for definition in self.defs) @property def y_size(self): warnings.warn("'y_size' is deprecated, use 'height' instead.", PendingDeprecationWarning) return self.height @property def size(self): return self.height * self.width def append(self, definition): """Append another definition to the area.""" if isinstance(definition, StackedAreaDefinition): for area in definition.defs: self.append(area) return if definition.height == 0: return if not self.defs: self.proj_dict = definition.proj_dict elif self.proj_dict != definition.proj_dict: raise NotImplementedError('Cannot append areas:' ' Proj.4 dict mismatch') try: self.defs[-1] = concatenate_area_defs(self.defs[-1], definition) except (IncompatibleAreas, IndexError): self.defs.append(definition) def get_lonlats(self, nprocs=None, data_slice=None, cache=False, dtype=None, chunks=None): """Return lon and lat arrays of the area.""" if chunks is not None: from dask.array import vstack else: vstack = np.vstack llons = [] llats = [] try: row_slice, col_slice = data_slice except TypeError: row_slice = slice(0, self.height) col_slice = slice(0, self.width) offset = 0 for definition in self.defs: local_row_slice = slice(max(row_slice.start - offset, 0), min(max(row_slice.stop - offset, 0), definition.height), row_slice.step) lons, lats = definition.get_lonlats(nprocs=nprocs, data_slice=(local_row_slice, col_slice), cache=cache, dtype=dtype, chunks=chunks) llons.append(lons) llats.append(lats) offset += lons.shape[0] self.lons = vstack(llons) self.lats = vstack(llats) return self.lons, self.lats def get_lonlats_dask(self, chunks=None, dtype=None): """"Return lon and lat dask arrays of the area.""" warnings.warn("'get_lonlats_dask' is deprecated, please use " "'get_lonlats' with the 'chunks' keyword argument specified.", DeprecationWarning) if chunks is None: chunks = CHUNK_SIZE # FUTURE: Use a global config object instead return self.get_lonlats(chunks=chunks, dtype=dtype) def squeeze(self): """Generate a single AreaDefinition if possible.""" if len(self.defs) == 1: return self.defs[0] else: return self @property def proj4_string(self): """Returns projection definition as Proj.4 string""" warnings.warn("'proj4_string' is deprecated, please use 'proj_str' " "instead.", DeprecationWarning) return self.defs[0].proj_str @property def proj_str(self): """Returns projection definition as Proj.4 string""" return self.defs[0].proj_str def update_hash(self, the_hash=None): for areadef in self.defs: the_hash = areadef.update_hash(the_hash) return the_hash def _get_slice(segments, shape): """Generator for segmenting a 1D or 2D array""" if not (1 <= len(shape) <= 2): raise ValueError('Cannot segment array of shape: %s' % str(shape)) else: size = shape[0] slice_length = int(np.ceil(float(size) / segments)) start_idx = 0 end_idx = slice_length while start_idx < size: if len(shape) == 1: yield slice(start_idx, end_idx) else: yield (slice(start_idx, end_idx), slice(None)) start_idx = end_idx end_idx = min(start_idx + slice_length, size) def _flatten_cartesian_coords(cartesian_coords): """Flatten array to (n, 3) shape""" shape = cartesian_coords.shape if len(shape) > 2: cartesian_coords = cartesian_coords.reshape(shape[0] * shape[1], 3) return cartesian_coords def _get_highest_level_class(obj1, obj2): if (not issubclass(obj1.__class__, obj2.__class__) or not issubclass(obj2.__class__, obj1.__class__)): raise TypeError('No common superclass for %s and %s' % (obj1.__class__, obj2.__class__)) if obj1.__class__ == obj2.__class__: klass = obj1.__class__ elif issubclass(obj1.__class__, obj2.__class__): klass = obj2.__class__ else: klass = obj1.__class__ return klass def ordered_dump(data, stream=None, Dumper=yaml.Dumper, **kwds): class OrderedDumper(Dumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items(), flow_style=False) OrderedDumper.add_representer(OrderedDict, _dict_representer) return yaml.dump(data, stream, OrderedDumper, **kwds)
lgpl-3.0
5,741,735,107,686,649,000
37.991634
116
0.577325
false
bwc126/MLND-interview-practice
Q4.py
1
4809
# Find the least common ancestor between two nodes on a binary search tree. The least common ancestor is the farthest node from the root that is an ancestor of both nodes. For example, the root is a common ancestor of all nodes on the tree, but if both nodes are descendents of the root's left child, then that left child might be the lowest common ancestor. You can assume that both nodes are in the tree, and the tree itself adheres to all BST properties. The function definition should look like question4(T, r, n1, n2), where T is the tree represented as a matrix, where the index of the list is equal to the integer stored in that node and a 1 represents a child node, r is a non-negative integer representing the root, and n1 and n2 are non-negative integers representing the two nodes in no particular order. For example, one test case might be # # question4([[0, 1, 0, 0, 0], # [0, 0, 0, 0, 0], # [0, 0, 0, 0, 0], # [1, 0, 0, 0, 1], # [0, 0, 0, 0, 0]], # 3, # 1, # 4) # # and the answer would be 3. # The matrix contains a number of rows equal to one plus the highest number in the BST. The index of a list within the matrix corresponds to each node's value. If the list for a node contains a 1, that node has a child whose value is the index of the position of the 1 within the list. For the example given above, the BST would have a 3 at the root, 0 on the left, 4 on the right. The 0 would have a child of 1 on the right. # The signature question4(T, r, n1, n2) includes T, a binary matrix as described previously, r, a non-neg integer corresponding to the value of the root. n1, n2 are each non-neg ints representing the two nodes for which we need to find the greatest common ancestor node. We can assume n1, n2 might be in any order, that both nodes are in fact within the tree, and the BST conforms to standard rules for a BST. import copy def question4(T, r, n1, n2): # We'll need to keep track of the lesser and greater node values to take full advantage of BST properties later on. n_1 = min(n1,n2) n_2 = max(n1,n2) # Lacking a BST matrix is a non-starter. if not T: return # Start by discarding trivial rows, storing the remaining rows with their node value in a dictionary as a key, and a list of their children as values. 0: [1] would be one such dictionary entry for the example in the question definition. nodes = {} # print T M = copy.deepcopy(T) for row in range(len(M)): if 1 in M[row]: children = [] for child in range(M[row].count(1)): loc = M[row].index(1) children.append(loc) M[row][loc] = 0 nodes[row] = children print nodes # This is strictly for handling the cases where n1 or n2 aren't in the BST. We build a simple list of all nodes in the tree to make sure n1 and n2 are actually in it before doing any more unnecessary computation. all_nodes = [] for children in nodes.values(): for node in children: all_nodes.append(node) all_nodes.extend(nodes.keys()) print all_nodes if n1 not in all_nodes or n2 not in all_nodes: return # We could look through the keys of 'nodes', which will be every node that is a parent of any node in the tree, and the first one we find that has a value between n1, n2 is our LCA. This assumes the keys are in order of their level on the tree, but they don't need to be in order relative to the other nodes on their level, because only nodes between n1 and n2 in value can be a parent of both. for parent in nodes.keys(): if parent < n_2 and parent > n_1: return parent # Test Cases matrix = [[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,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,1,0,0,0,0,1,0,0,0,0,0,0,0,0], # 3 [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,0,0,0,0,0], [0,0,0,0,1,0,0,1,0,0,0,0,0,0,0], # 6 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0,0,0,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], # 9 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [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,0,0,0,0,0], # 12 [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,0,0,0,1,0]] root = 8 n_1, n_2 = 4, 7 print question4(matrix, root, n_1, n_2) # Should be 6 n_3, n_4 = 1, 6 print question4(matrix, root, n_3, n_4) # Should be 3 n_5, n_6 = 4, 10 print question4(matrix, root, n_5, n_6) # Should be 8 n_7, n_8 = 16, 0 print question4(matrix, root, n_7, n_8) # Edge case: should be None n_9, n_10 = 4, 10 print question4(None, root, n_9, n_10) # Edge case: should be None
gpl-3.0
289,486,961,979,072,200
56.939759
851
0.6309
false
bit-team/backintime
qt/app.py
1
64835
# -*- coding: UTF-8 -*- # Back In Time # Copyright (C) 2008-2021 Oprea Dan, Bart de Koning, Richard Bailey, Germar Reitze # # This program 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 2 of the License, or # (at your option) any later version. # # This program 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 this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import os import sys if not os.getenv('DISPLAY', ''): os.putenv('DISPLAY', ':0.0') import datetime import gettext import re import subprocess import shutil import signal from contextlib import contextmanager from tempfile import TemporaryDirectory import qttools qttools.registerBackintimePath('common') import backintime import tools import logger import snapshots import guiapplicationinstance import mount import progress from exceptions import MountException from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import settingsdialog import snapshotsdialog import logviewdialog from restoredialog import RestoreDialog import messagebox _=gettext.gettext class MainWindow(QMainWindow): def __init__(self, config, appInstance, qapp): QMainWindow.__init__(self) self.config = config self.appInstance = appInstance self.qapp = qapp self.snapshots = snapshots.Snapshots(config) self.lastTakeSnapshotMessage = None self.tmpDirs = [] #main toolbar self.mainToolbar = self.addToolBar('main') self.mainToolbar.setFloatable(False) #window icon import icon self.qapp.setWindowIcon(icon.BIT_LOGO) #profiles self.firstUpdateAll = True self.disableProfileChanged = False self.comboProfiles = qttools.ProfileCombo(self) self.comboProfilesAction = self.mainToolbar.addWidget(self.comboProfiles) # take_snapshot button self.btnTakeSnapshot = self.mainToolbar.addAction(icon.TAKE_SNAPSHOT, _('Take snapshot')) self.btnTakeSnapshot.triggered.connect(self.btnTakeSnapshotClicked) takeSnapshotMenu = qttools.Menu() action = takeSnapshotMenu.addAction(icon.TAKE_SNAPSHOT, _('Take snapshot')) action.triggered.connect(self.btnTakeSnapshotClicked) self.btnTakeSnapshotChecksum = takeSnapshotMenu.addAction(icon.TAKE_SNAPSHOT, _('Take snapshot with checksums')) self.btnTakeSnapshotChecksum.setToolTip(_('Use checksum to detect changes')) self.btnTakeSnapshotChecksum.triggered.connect(self.btnTakeSnapshotChecksumClicked) self.btnTakeSnapshot.setMenu(takeSnapshotMenu) for action in takeSnapshotMenu.actions(): action.setIconVisibleInMenu(True) #pause snapshot button self.btnPauseTakeSnapshot = self.mainToolbar.addAction(icon.PAUSE, _('Pause snapshot process')) action = lambda: os.kill(self.snapshots.pid(), signal.SIGSTOP) self.btnPauseTakeSnapshot.triggered.connect(action) self.btnPauseTakeSnapshot.setVisible(False) #resume snapshot button self.btnResumeTakeSnapshot = self.mainToolbar.addAction(icon.RESUME, _('Resume snapshot process')) action = lambda: os.kill(self.snapshots.pid(), signal.SIGCONT) self.btnResumeTakeSnapshot.triggered.connect(action) self.btnResumeTakeSnapshot.setVisible(False) #stop snapshot button self.btnStopTakeSnapshot = self.mainToolbar.addAction(icon.STOP, _('Stop snapshot process')) self.btnStopTakeSnapshot.triggered.connect(self.btnStopTakeSnapshotClicked) self.btnStopTakeSnapshot.setVisible(False) # update snapshots button self.btnUpdateSnapshots = self.mainToolbar.addAction(icon.REFRESH_SNAPSHOT, _('Refresh snapshots list')) self.btnUpdateSnapshots.setShortcuts([Qt.Key_F5, QKeySequence(Qt.CTRL + Qt.Key_R)]) self.btnUpdateSnapshots.triggered.connect(self.btnUpdateSnapshotsClicked) self.btnNameSnapshot = self.mainToolbar.addAction(icon.SNAPSHOT_NAME, _('Snapshot Name')) self.btnNameSnapshot.triggered.connect(self.btnNameSnapshotClicked) self.btnRemoveSnapshot = self.mainToolbar.addAction(icon.REMOVE_SNAPSHOT, _('Remove Snapshot')) self.btnRemoveSnapshot.triggered.connect(self.btnRemoveSnapshotClicked) self.btnSnapshotLogView = self.mainToolbar.addAction(icon.VIEW_SNAPSHOT_LOG, _('View Snapshot Log')) self.btnSnapshotLogView.triggered.connect(self.btnSnapshotLogViewClicked) self.btnLastLogView = self.mainToolbar.addAction(icon.VIEW_LAST_LOG, _('View Last Log')) self.btnLastLogView.triggered.connect(self.btnLastLogViewClicked) self.mainToolbar.addSeparator() self.btnSettings = self.mainToolbar.addAction(icon.SETTINGS, _('Settings')) self.btnSettings.triggered.connect(self.btnSettingsClicked) self.mainToolbar.addSeparator() self.btnShutdown = self.mainToolbar.addAction(icon.SHUTDOWN, _('Shutdown')) self.btnShutdown.setToolTip(_('Shutdown system after snapshot has finished.')) self.btnShutdown.setCheckable(True) self.shutdown = tools.ShutDown() self.btnShutdown.setEnabled(self.shutdown.canShutdown()) self.btnShutdown.toggled.connect(self.btnShutdownToggled) self.btnQuit = self.mainToolbar.addAction(icon.EXIT, _('Exit')) self.btnQuit.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_W)) self.btnQuit.triggered.connect(self.close) empty = QWidget(self) empty.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.mainToolbar.addWidget(empty) menuHelp = QMenu(self) self.btnHelp = menuHelp.addAction(icon.HELP, _('Help')) self.btnHelp.triggered.connect(self.btnHelpClicked) self.btnHelpConfig = menuHelp.addAction(icon.HELP, _('Config File Help')) self.btnHelpConfig.triggered.connect(self.btnHelpConfigClicked) menuHelp.addSeparator() self.btnWebsite = menuHelp.addAction(icon.WEBSITE, _('Website')) self.btnWebsite.triggered.connect(self.btnWebsiteClicked) self.btnChangelog = menuHelp.addAction(icon.CHANGELOG, _('Changelog')) self.btnChangelog.triggered.connect(self.btnChangelogClicked) self.btnFaq = menuHelp.addAction(icon.FAQ, _('FAQ')) self.btnFaq.triggered.connect(self.btnFaqClicked) self.btnAskQuestion = menuHelp.addAction(icon.QUESTION, _('Ask a question')) self.btnAskQuestion.triggered.connect(self.btnAskQuestionClicked) self.btnReportBug = menuHelp.addAction(icon.BUG, _('Report a bug')) self.btnReportBug.triggered.connect(self.btnReportBugClicked) menuHelp.addSeparator() self.btnAbout = menuHelp.addAction(icon.ABOUT, _('About')) self.btnAbout.triggered.connect(self.btnAboutClicked) action = self.mainToolbar.addAction(icon.HELP, _('Help')) action.triggered.connect(self.btnHelpClicked) action.setMenu(menuHelp) for action in menuHelp.actions(): action.setIconVisibleInMenu(True) #main splitter self.mainSplitter = QSplitter(self) self.mainSplitter.setOrientation(Qt.Horizontal) #timeline self.timeLine = qttools.TimeLine(self) self.mainSplitter.addWidget(self.timeLine) self.timeLine.updateFilesView.connect(self.updateFilesView) #right widget self.filesWidget = QGroupBox(self) self.mainSplitter.addWidget(self.filesWidget) filesLayout = QVBoxLayout(self.filesWidget) left, top, right, bottom = filesLayout.getContentsMargins() filesLayout.setContentsMargins(0, 0, right, 0) #files toolbar self.filesViewToolbar = QToolBar(self) self.filesViewToolbar.setFloatable(False) self.btnFolderUp = self.filesViewToolbar.addAction(icon.UP, _('Up')) self.btnFolderUp.setShortcuts([QKeySequence(Qt.ALT + Qt.Key_Up), Qt.Key_Backspace]) self.btnFolderUp.triggered.connect(self.btnFolderUpClicked) self.editCurrentPath = QLineEdit(self) self.editCurrentPath.setReadOnly(True) self.filesViewToolbar.addWidget(self.editCurrentPath) #show hidden files self.showHiddenFiles = self.config.boolValue('qt.show_hidden_files', False) self.btnShowHiddenFiles = self.filesViewToolbar.addAction(icon.SHOW_HIDDEN, _('Show hidden files')) self.btnShowHiddenFiles.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_H)) self.btnShowHiddenFiles.setCheckable(True) self.btnShowHiddenFiles.setChecked(self.showHiddenFiles) self.btnShowHiddenFiles.toggled.connect(self.btnShowHiddenFilesToggled) self.filesViewToolbar.addSeparator() #restore menu self.menuRestore = qttools.Menu(self) self.btnRestore = self.menuRestore.addAction(icon.RESTORE, _('Restore')) self.btnRestore.setToolTip(_('Restore the selected files or folders ' 'to the original destination.')) self.btnRestore.triggered.connect(self.restoreThis) self.btnRestoreTo = self.menuRestore.addAction(icon.RESTORE_TO, _('Restore to ...')) self.btnRestoreTo.setToolTip(_('Restore the selected files or ' 'folders to a new destination.')) self.btnRestoreTo.triggered.connect(self.restoreThisTo) self.menuRestore.addSeparator() self.btnRestoreParent = self.menuRestore.addAction(icon.RESTORE, '') self.btnRestoreParent.setToolTip(_('Restore the currently shown ' 'folder and all its content to ' 'the original destination.')) self.btnRestoreParent.triggered.connect(self.restoreParent) self.btnRestoreParentTo = self.menuRestore.addAction(icon.RESTORE_TO, '') self.btnRestoreParentTo.setToolTip(_('Restore the currently shown ' 'folder and all its content ' 'to a new destination.')) self.btnRestoreParentTo.triggered.connect(self.restoreParentTo) self.menuRestore.addSeparator() for action in self.menuRestore.actions(): action.setIconVisibleInMenu(True) self.btnRestoreMenu = self.filesViewToolbar.addAction(icon.RESTORE, _('Restore')) self.btnRestoreMenu.setMenu(self.menuRestore) self.btnRestoreMenu.setToolTip(_('Restore selected file or folder.\n' 'If this button is grayed out this is most likely ' 'because "%(now)s" is selected in left hand snapshots list.') % {'now': _('Now')}) self.btnRestoreMenu.triggered.connect(self.restoreThis) self.btnSnapshots = self.filesViewToolbar.addAction(icon.SNAPSHOTS, _('Snapshots')) self.btnSnapshots.triggered.connect(self.btnSnapshotsClicked) filesLayout.addWidget(self.filesViewToolbar) #menubar self.menuSnapshot = self.menuBar().addMenu(_('Snapshot')) self.menuSnapshot.addAction(self.btnTakeSnapshot) self.menuSnapshot.addAction(self.btnUpdateSnapshots) self.menuSnapshot.addAction(self.btnNameSnapshot) self.menuSnapshot.addAction(self.btnRemoveSnapshot) self.menuSnapshot.addSeparator() self.menuSnapshot.addAction(self.btnSettings) self.menuSnapshot.addSeparator() self.menuSnapshot.addAction(self.btnShutdown) self.menuSnapshot.addAction(self.btnQuit) self.menuView = self.menuBar().addMenu(_('View')) self.menuView.addAction(self.btnFolderUp) self.menuView.addAction(self.btnShowHiddenFiles) self.menuView.addSeparator() self.menuView.addAction(self.btnSnapshotLogView) self.menuView.addAction(self.btnLastLogView) self.menuView.addSeparator() self.menuView.addAction(self.btnSnapshots) self.menuRestore = self.menuBar().addMenu(_('Restore')) self.menuRestore.addAction(self.btnRestore) self.menuRestore.addAction(self.btnRestoreTo) self.menuRestore.addSeparator() self.menuRestore.addAction(self.btnRestoreParent) self.menuRestore.addAction(self.btnRestoreParentTo) self.menuHelp = self.menuBar().addMenu(_('Help')) self.menuHelp.addAction(self.btnHelp) self.menuHelp.addAction(self.btnHelpConfig) self.menuHelp.addSeparator() self.menuHelp.addAction(self.btnWebsite) self.menuHelp.addAction(self.btnChangelog) self.menuHelp.addAction(self.btnFaq) self.menuHelp.addAction(self.btnAskQuestion) self.menuHelp.addAction(self.btnReportBug) self.menuHelp.addSeparator() self.menuHelp.addAction(self.btnAbout) #shortcuts without buttons self.shortcutPreviousFolder = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Left), self) self.shortcutPreviousFolder.activated.connect(self.btnFolderHistoryPreviousClicked) self.shortcutNextFolder = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Right), self) self.shortcutNextFolder.activated.connect(self.btnFolderHistoryNextClicked) self.shortcutOpenFolder = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Down), self) self.shortcutOpenFolder.activated.connect(self.btnOpenCurrentItemClicked) #mouse button navigation self.mouseButtonEventFilter = ExtraMouseButtonEventFilter(self) self.setMouseButtonNavigation() #second spliter self.secondSplitter = QSplitter(self) self.secondSplitter.setOrientation(Qt.Horizontal) self.secondSplitter.setContentsMargins(0, 0, 0, 0) filesLayout.addWidget(self.secondSplitter) #places self.places = QTreeWidget(self) self.places.setRootIsDecorated(False) self.places.setEditTriggers(QAbstractItemView.NoEditTriggers) self.places.setHeaderLabel(_('Shortcuts')) self.places.header().setSectionsClickable(True) self.places.header().setSortIndicatorShown(True) self.places.header().setSectionHidden(1, True) self.places.header().setSortIndicator(int(self.config.profileIntValue('qt.places.SortColumn', 1)), int(self.config.profileIntValue('qt.places.SortOrder', Qt.AscendingOrder))) self.placesSortLoop = {self.config.currentProfile(): False} self.secondSplitter.addWidget(self.places) self.places.header().sortIndicatorChanged.connect(self.sortPlaces) #files view stacked layout widget = QWidget(self) self.stackFilesView = QStackedLayout(widget) self.secondSplitter.addWidget(widget) #folder don't exist label self.lblFolderDontExists = QLabel(_('This folder doesn\'t exist\nin the current selected snapshot!'), self) qttools.setFontBold(self.lblFolderDontExists) self.lblFolderDontExists.setFrameShadow(QFrame.Sunken) self.lblFolderDontExists.setFrameShape(QFrame.Panel) self.lblFolderDontExists.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.stackFilesView.addWidget(self.lblFolderDontExists) #list files view self.filesView = QTreeView(self) self.stackFilesView.addWidget(self.filesView) self.filesView.setRootIsDecorated(False) self.filesView.setAlternatingRowColors(True) self.filesView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.filesView.setItemsExpandable(False) self.filesView.setDragEnabled(False) self.filesView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.filesView.header().setSectionsClickable(True) self.filesView.header().setSectionsMovable(False) self.filesView.header().setSortIndicatorShown(True) self.filesViewModel = QFileSystemModel(self) self.filesViewModel.setRootPath(QDir().rootPath()) self.filesViewModel.setReadOnly(True) self.filesViewModel.setFilter(QDir.AllDirs | QDir.AllEntries | QDir.NoDotAndDotDot | QDir.Hidden) self.filesViewProxyModel = QSortFilterProxyModel(self) self.filesViewProxyModel.setDynamicSortFilter(True) self.filesViewProxyModel.setSourceModel(self.filesViewModel) self.filesView.setModel(self.filesViewProxyModel) self.filesViewDelegate = QStyledItemDelegate(self) self.filesView.setItemDelegate(self.filesViewDelegate) sortColumn = self.config.intValue('qt.main_window.files_view.sort.column', 0) sortOrder = self.config.boolValue('qt.main_window.files_view.sort.ascending', True) if sortOrder: sortOrder = Qt.AscendingOrder else: sortOrder = Qt.DescendingOrder self.filesView.header().setSortIndicator(sortColumn, sortOrder) self.filesViewModel.sort(self.filesView.header().sortIndicatorSection(), self.filesView.header().sortIndicatorOrder()) self.filesView.header().sortIndicatorChanged.connect(self.filesViewModel.sort) self.stackFilesView.setCurrentWidget(self.filesView) # self.setCentralWidget(self.mainSplitter) #context menu self.filesView.setContextMenuPolicy(Qt.CustomContextMenu) self.filesView.customContextMenuRequested.connect(self.contextMenuClicked) self.contextMenu = QMenu(self) self.contextMenu.addAction(self.btnRestore) self.contextMenu.addAction(self.btnRestoreTo) self.contextMenu.addAction(self.btnSnapshots) self.contextMenu.addSeparator() self.btnAddInclude = self.contextMenu.addAction(icon.ADD, _('Add to Include')) self.btnAddExclude = self.contextMenu.addAction(icon.ADD, _('Add to Exclude')) self.btnAddInclude.triggered.connect(self.btnAddIncludeClicked) self.btnAddExclude.triggered.connect(self.btnAddExcludeClicked) self.contextMenu.addSeparator() self.contextMenu.addAction(self.btnShowHiddenFiles) #ProgressBar layoutWidget = QWidget() layout = QVBoxLayout(layoutWidget) layout.setContentsMargins(0, 0, 0, 0) layoutWidget.setContentsMargins(0, 0, 0, 0) layoutWidget.setLayout(layout) self.progressBar = QProgressBar(self) self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.progressBar.setValue(0) self.progressBar.setTextVisible(False) self.progressBar.setContentsMargins(0, 0, 0, 0) self.progressBar.setFixedHeight(5) self.progressBar.setVisible(False) self.progressBarDummy = QWidget() self.progressBarDummy.setContentsMargins(0, 0, 0, 0) self.progressBarDummy.setFixedHeight(5) self.status = QLabel(self) self.status.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.status) layout.addWidget(self.progressBar) layout.addWidget(self.progressBarDummy) self.statusBar().addWidget(layoutWidget, 100) self.status.setText(_('Done')) self.snapshotsList = [] self.sid = snapshots.RootSnapshot(self.config) self.path = self.config.profileStrValue('qt.last_path', self.config.strValue('qt.last_path', '/')) self.editCurrentPath.setText(self.path) self.path_history = tools.PathHistory(self.path) #restore size and position x = self.config.intValue('qt.main_window.x', -1) y = self.config.intValue('qt.main_window.y', -1) if x >= 0 and y >= 0: self.move(x, y) w = self.config.intValue('qt.main_window.width', 800) h = self.config.intValue('qt.main_window.height', 500) self.resize(w, h) mainSplitterLeftWidth = self.config.intValue('qt.main_window.main_splitter_left_w', 150) mainSplitterRightWidth = self.config.intValue('qt.main_window.main_splitter_right_w', 450) sizes = [mainSplitterLeftWidth, mainSplitterRightWidth] self.mainSplitter.setSizes(sizes) secondSplitterLeftWidth = self.config.intValue('qt.main_window.second_splitter_left_w', 150) secondSplitterRightWidth = self.config.intValue('qt.main_window.second_splitter_right_w', 300) sizes = [secondSplitterLeftWidth, secondSplitterRightWidth] self.secondSplitter.setSizes(sizes) filesViewColumnNameWidth = self.config.intValue('qt.main_window.files_view.name_width', -1) filesViewColumnSizeWidth = self.config.intValue('qt.main_window.files_view.size_width', -1) filesViewColumnDateWidth = self.config.intValue('qt.main_window.files_view.date_width', -1) if filesViewColumnNameWidth > 0 and filesViewColumnSizeWidth > 0 and filesViewColumnDateWidth > 0: self.filesView.header().resizeSection(0, filesViewColumnNameWidth) self.filesView.header().resizeSection(1, filesViewColumnSizeWidth) self.filesView.header().resizeSection(2, filesViewColumnDateWidth) #force settingdialog if it is not configured if not config.isConfigured(): message = _('%(appName)s is not configured. Would you like ' 'to restore a previous configuration?' % {'appName': self.config.APP_NAME}) if QMessageBox.Yes == messagebox.warningYesNo(self, message): settingsdialog.RestoreConfigDialog(self).exec_() settingsdialog.SettingsDialog(self).exec_() if not config.isConfigured(): return profile_id = config.currentProfile() #mount try: mnt = mount.Mount(cfg = self.config, profile_id = profile_id, parent = self) hash_id = mnt.mount() except MountException as ex: messagebox.critical(self, str(ex)) else: self.config.setCurrentHashId(hash_id) if not config.canBackup(profile_id): messagebox.critical(self, _('Can\'t find snapshots folder.\nIf it is on a removable drive please plug it and then press OK')) self.filesViewProxyModel.layoutChanged.connect(self.dirListerCompleted) #populate lists self.updateProfiles() self.comboProfiles.currentIndexChanged.connect(self.comboProfileChanged) self.filesView.setFocus() self.updateSnapshotActions() #signals self.timeLine.itemSelectionChanged.connect(self.timeLineChanged) self.places.currentItemChanged.connect(self.placesChanged) self.filesView.activated.connect(self.filesViewItemActivated) self.forceWaitLockCounter = 0 self.timerRaiseApplication = QTimer(self) self.timerRaiseApplication.setInterval(1000) self.timerRaiseApplication.setSingleShot(False) self.timerRaiseApplication.timeout.connect(self.raiseApplication) self.timerRaiseApplication.start() self.timerUpdateTakeSnapshot = QTimer(self) self.timerUpdateTakeSnapshot.setInterval(1000) self.timerUpdateTakeSnapshot.setSingleShot(False) self.timerUpdateTakeSnapshot.timeout.connect(self.updateTakeSnapshot) self.timerUpdateTakeSnapshot.start() SetupCron(self).start() def closeEvent(self, event): if self.shutdown.askBeforeQuit(): if QMessageBox.Yes != messagebox.warningYesNo(self, _('If you close this window Back In Time will not be able to shutdown your system when the snapshot has finished.\nDo you really want to close?')): return event.ignore() self.config.setStrValue('qt.last_path', self.path) self.config.setProfileStrValue('qt.last_path', self.path) self.config.setProfileIntValue('qt.places.SortColumn', self.places.header().sortIndicatorSection()) self.config.setProfileIntValue('qt.places.SortOrder', self.places.header().sortIndicatorOrder()) self.config.setIntValue('qt.main_window.x', self.x()) self.config.setIntValue('qt.main_window.y', self.y()) self.config.setIntValue('qt.main_window.width', self.width()) self.config.setIntValue('qt.main_window.height', self.height()) sizes = self.mainSplitter.sizes() self.config.setIntValue('qt.main_window.main_splitter_left_w', sizes[0]) self.config.setIntValue('qt.main_window.main_splitter_right_w', sizes[1]) sizes = self.secondSplitter.sizes() self.config.setIntValue('qt.main_window.second_splitter_left_w', sizes[0]) self.config.setIntValue('qt.main_window.second_splitter_right_w', sizes[1]) self.config.setIntValue('qt.main_window.files_view.name_width', self.filesView.header().sectionSize(0)) self.config.setIntValue('qt.main_window.files_view.size_width', self.filesView.header().sectionSize(1)) self.config.setIntValue('qt.main_window.files_view.date_width', self.filesView.header().sectionSize(2)) self.config.setBoolValue('qt.show_hidden_files', self.showHiddenFiles) self.config.setIntValue('qt.main_window.files_view.sort.column', self.filesView.header().sortIndicatorSection()) self.config.setBoolValue('qt.main_window.files_view.sort.ascending', self.filesView.header().sortIndicatorOrder() == Qt.AscendingOrder) self.filesViewModel.deleteLater() #umount try: mnt = mount.Mount(cfg = self.config, parent = self) mnt.umount(self.config.current_hash_id) except MountException as ex: messagebox.critical(self, str(ex)) self.config.save() # cleanup temporary local copies of files which were opened in GUI for d in self.tmpDirs: d.cleanup() event.accept() def updateProfiles(self): if self.disableProfileChanged: return self.disableProfileChanged = True self.comboProfiles.clear() profiles = self.config.profilesSortedByName() for profile_id in profiles: self.comboProfiles.addProfileID(profile_id) if profile_id == self.config.currentProfile(): self.comboProfiles.setCurrentProfileID(profile_id) self.comboProfilesAction.setVisible(len(profiles) > 1) self.updateProfile() self.disableProfileChanged = False def updateProfile(self): self.updateTimeLine() self.updatePlaces() self.updateFilesView(0) def comboProfileChanged(self, index): if self.disableProfileChanged: return profile_id = self.comboProfiles.currentProfileID() if not profile_id: return old_profile_id = self.config.currentProfile() if profile_id != old_profile_id: self.remount(profile_id, old_profile_id) self.config.setCurrentProfile(profile_id) self.config.setProfileIntValue('qt.places.SortColumn', self.places.header().sortIndicatorSection(), old_profile_id) self.config.setProfileIntValue('qt.places.SortOrder', self.places.header().sortIndicatorOrder(), old_profile_id) self.placesSortLoop[old_profile_id] = False self.places.header().setSortIndicator(int(self.config.profileIntValue('qt.places.SortColumn', 1, profile_id)), int(self.config.profileIntValue('qt.places.SortOrder', Qt.AscendingOrder, profile_id))) self.config.setProfileStrValue('qt.last_path', self.path, old_profile_id) path = self.config.profileStrValue('qt.last_path', self.path, profile_id) if not path == self.path: self.path = path self.path_history.reset(self.path) self.editCurrentPath.setText(self.path) self.updateProfile() def remount(self, new_profile_id, old_profile_id): try: mnt = mount.Mount(cfg = self.config, profile_id = old_profile_id, parent = self) hash_id = mnt.remount(new_profile_id) except MountException as ex: messagebox.critical(self, str(ex)) else: self.config.setCurrentHashId(hash_id) def raiseApplication(self): raiseCmd = self.appInstance.raiseCommand() if raiseCmd is None: return logger.debug("Raise cmd: %s" %raiseCmd, self) self.qapp.alert(self) def updateTakeSnapshot(self, force_wait_lock = False): if force_wait_lock: self.forceWaitLockCounter = 10 busy = self.snapshots.busy() if busy: self.forceWaitLockCounter = 0 paused = tools.processPaused(self.snapshots.pid()) else: paused = False if self.forceWaitLockCounter > 0: self.forceWaitLockCounter = self.forceWaitLockCounter - 1 fake_busy = busy or self.forceWaitLockCounter > 0 message = _('Working:') takeSnapshotMessage = self.snapshots.takeSnapshotMessage() if fake_busy: if takeSnapshotMessage is None: takeSnapshotMessage = (0, '...') elif takeSnapshotMessage is None: takeSnapshotMessage = self.lastTakeSnapshotMessage if takeSnapshotMessage is None: takeSnapshotMessage = (0, _('Done')) force_update = False if fake_busy: if self.btnTakeSnapshot.isEnabled(): self.btnTakeSnapshot.setEnabled(False) if not self.btnStopTakeSnapshot.isVisible(): for btn in (self.btnPauseTakeSnapshot, self.btnResumeTakeSnapshot, self.btnStopTakeSnapshot): btn.setEnabled(True) self.btnTakeSnapshot.setVisible(False) self.btnPauseTakeSnapshot.setVisible(not paused) self.btnResumeTakeSnapshot.setVisible(paused) self.btnStopTakeSnapshot.setVisible(True) elif not self.btnTakeSnapshot.isEnabled(): force_update = True self.btnTakeSnapshot.setEnabled(True) self.btnTakeSnapshot.setVisible(True) for btn in (self.btnPauseTakeSnapshot, self.btnResumeTakeSnapshot, self.btnStopTakeSnapshot): btn.setVisible(False) #TODO: check if there is a more elegant way than always get a new snapshot list which is very expensive (time) snapshotsList = snapshots.listSnapshots(self.config) if snapshotsList != self.snapshotsList: self.snapshotsList = snapshotsList self.updateTimeLine(False) takeSnapshotMessage = (0, _('Done')) else: if takeSnapshotMessage[0] == 0: takeSnapshotMessage = (0, _('Done, no backup needed')) self.shutdown.shutdown() if takeSnapshotMessage != self.lastTakeSnapshotMessage or force_update: self.lastTakeSnapshotMessage = takeSnapshotMessage if fake_busy: message = _('Working:') + ' ' + self.lastTakeSnapshotMessage[1].replace('\n', ' ') elif takeSnapshotMessage[0] == 0: message = self.lastTakeSnapshotMessage[1].replace('\n', ' ') else: message = _('Error:') + ' ' + self.lastTakeSnapshotMessage[1].replace('\n', ' ') self.status.setText(message) pg = progress.ProgressFile(self.config) if pg.fileReadable(): self.progressBar.setVisible(True) self.progressBarDummy.setVisible(False) pg.load() self.progressBar.setValue(pg.intValue('percent')) message = ' | '.join(self.getProgressBarFormat(pg, message)) self.status.setText(message) else: self.progressBar.setVisible(False) self.progressBarDummy.setVisible(True) #if not fake_busy: # self.lastTakeSnapshotMessage = None def getProgressBarFormat(self, pg, message): d = (('sent', _('Sent:')), \ ('speed', _('Speed:')),\ ('eta', _('ETA:'))) yield '{}%'.format(pg.intValue('percent')) for key, txt in d: value = pg.strValue(key, '') if not value: continue yield txt + ' ' + value yield message def placesChanged(self, item, previous): if item is None: return path = str(item.data(0, Qt.UserRole)) if not path: return if path == self.path: return self.path = path self.path_history.append(path) self.updateFilesView(3) def addPlace(self, name, path, icon): item = QTreeWidgetItem() item.setText(0, name) if icon: item.setIcon(0, QIcon.fromTheme(icon)) item.setData(0, Qt.UserRole, path) if not path: item.setFont(0, qttools.fontBold(item.font(0))) item.setFlags(Qt.ItemIsEnabled) item.setBackground(0, QColor(196, 196, 196)) item.setForeground(0, QColor(60, 60, 60)) self.places.addTopLevelItem(item) if path == self.path: self.places.setCurrentItem(item) return item def updatePlaces(self): self.places.clear() self.addPlace(_('Global'), '', '') self.addPlace(_('Root'), '/', 'computer') self.addPlace(_('Home'), os.path.expanduser('~'), 'user-home') #add backup folders include_folders = self.config.include() if include_folders: folders = [] for item in include_folders: if item[1] == 0: folders.append(item[0]) if folders: sortColumn = self.places.header().sortIndicatorSection() sortOrder = self.places.header().sortIndicatorOrder() if not sortColumn: folders.sort(key = lambda v: (v.upper(), v[0].islower()), reverse = sortOrder) self.addPlace(_('Backup folders'), '', '') for folder in folders: self.addPlace(folder, folder, 'document-save') def sortPlaces(self, newColumn, newOrder, force = False): profile_id = self.config.currentProfile() if newColumn == 0 and newOrder == Qt.AscendingOrder: if profile_id in self.placesSortLoop and self.placesSortLoop[profile_id]: newColumn, newOrder = 1, Qt.AscendingOrder self.places.header().setSortIndicator(newColumn, newOrder) self.placesSortLoop[profile_id] = False else: self.placesSortLoop[profile_id] = True self.updatePlaces() def updateSnapshotActions(self, item = None): enabled = False if item is None: item = self.timeLine.currentItem() if not item is None: if not item.snapshotID().isRoot: enabled = True #update remove/name snapshot buttons self.btnNameSnapshot.setEnabled(enabled) self.btnRemoveSnapshot.setEnabled(enabled) self.btnSnapshotLogView.setEnabled(enabled) def timeLineChanged(self): item = self.timeLine.currentItem() self.updateSnapshotActions(item) if item is None: return sid = item.snapshotID() if not sid or sid == self.sid: return self.sid = sid self.updateFilesView(2) def updateTimeLine(self, refreshSnapshotsList = True): self.timeLine.clear() self.timeLine.addRoot(snapshots.RootSnapshot(self.config)) if refreshSnapshotsList: self.snapshotsList = [] thread = FillTimeLineThread(self) thread.addSnapshot.connect(self.timeLine.addSnapshot) thread.finished.connect(self.timeLine.checkSelection) thread.start() else: for sid in self.snapshotsList: item = self.timeLine.addSnapshot(sid) self.timeLine.checkSelection() def btnTakeSnapshotClicked(self): backintime.takeSnapshotAsync(self.config) self.updateTakeSnapshot(True) def btnTakeSnapshotChecksumClicked(self): backintime.takeSnapshotAsync(self.config, checksum = True) self.updateTakeSnapshot(True) def btnStopTakeSnapshotClicked(self): os.kill(self.snapshots.pid(), signal.SIGKILL) self.btnStopTakeSnapshot.setEnabled(False) self.btnPauseTakeSnapshot.setEnabled(False) self.btnResumeTakeSnapshot.setEnabled(False) self.snapshots.setTakeSnapshotMessage(0, 'Snapshot terminated') def btnUpdateSnapshotsClicked(self): self.updateTimeLine() self.updateFilesView(2) def btnNameSnapshotClicked(self): item = self.timeLine.currentItem() if item is None: return sid = item.snapshotID() if sid.isRoot: return name = sid.name new_name, accept = QInputDialog.getText(self, _('Snapshot Name'), '', text = name) if not accept: return new_name = new_name.strip() if name == new_name: return sid.name = new_name item.updateText() def btnLastLogViewClicked (self): with self.suspendMouseButtonNavigation(): logviewdialog.LogViewDialog(self).show() def btnSnapshotLogViewClicked (self): item = self.timeLine.currentItem() if item is None: return sid = item.snapshotID() if sid.isRoot: return with self.suspendMouseButtonNavigation(): dlg = logviewdialog.LogViewDialog(self, sid) dlg.show() if sid != dlg.sid: self.timeLine.setCurrentSnapshotID(dlg.sid) def btnRemoveSnapshotClicked (self): def hideItem(item): try: item.setHidden(True) except RuntimeError: #item has been deleted #probably because user pressed refresh pass items = [item for item in self.timeLine.selectedItems() if not isinstance(item, snapshots.RootSnapshot)] if not items: return if QMessageBox.Yes != messagebox.warningYesNo(self, \ _('Are you sure you want to remove the snapshot:\n%s') \ %'\n'.join([item.snapshotID().displayName for item in items])): return for item in items: item.setDisabled(True) if item is self.timeLine.currentItem(): self.timeLine.selectRootItem() thread = RemoveSnapshotThread(self, items) thread.refreshSnapshotList.connect(self.updateTimeLine) thread.hideTimelineItem.connect(hideItem) thread.start() def btnSettingsClicked(self): with self.suspendMouseButtonNavigation(): settingsdialog.SettingsDialog(self).show() def btnShutdownToggled(self, checked): self.shutdown.activate_shutdown = checked def contextMenuClicked(self, point): self.contextMenu.exec_(self.filesView.mapToGlobal(point)) def btnAboutClicked(self): with self.suspendMouseButtonNavigation(): dlg = About(self) dlg.exec_() def btnHelpClicked(self): self.openManPage('backintime') def btnHelpConfigClicked(self): self.openManPage('backintime-config') def btnWebsiteClicked(self): self.openUrl('https://github.com/bit-team/backintime') def btnChangelogClicked(self): def aHref(m): if m.group(0).count('@'): return '<a href="mailto:%(url)s">%(url)s</a>' % {'url': m.group(0)} else: return '<a href="%(url)s">%(url)s</a>' % {'url': m.group(0)} def aHref_lp(m): return '<a href="https://bugs.launchpad.net/backintime/+bug/%(id)s">%(txt)s</a>' % {'txt': m.group(0), 'id': m.group(1)} msg = self.config.changelog() msg = re.sub(r'https?://[^) \n]*', aHref, msg) msg = re.sub(r'(?:LP:|bug) ?#?(\d+)', aHref_lp, msg) msg = re.sub(r'\n', '<br>', msg) messagebox.showInfo(self, _('Changelog'), msg) def btnFaqClicked(self): self.openUrl('https://github.com/bit-team/backintime/wiki/FAQ') def btnAskQuestionClicked(self): self.openUrl('https://github.com/bit-team/backintime/issues') def btnReportBugClicked(self): self.openUrl('https://github.com/bit-team/backintime/issues/new') def openUrl(self, url): return QDesktopServices.openUrl(QUrl(url)) def openManPage(self, man_page): if not tools.checkCommand('man'): messagebox.critical(self, "Couldn't find 'man' to show the help page. Please install 'man'") return env = os.environ env['MANWIDTH'] = '80' proc = subprocess.Popen(['man', man_page], stdout = subprocess.PIPE, universal_newlines = True, env = env) out, err = proc.communicate() messagebox.showInfo(self, 'Manual Page {}'.format(man_page), out) def btnShowHiddenFilesToggled(self, checked): self.showHiddenFiles = checked self.updateFilesView(1) def backupOnRestore(self): cb = QCheckBox(_("Backup local files before overwriting or\nremoving with trailing '%(suffix)s'.") % {'suffix': self.snapshots.backupSuffix()}) cb.setChecked(self.config.backupOnRestore()) cb.setToolTip(_("Newer versions of files will be " "renamed with trailing '%(suffix)s' " "before restoring.\n" "If you don't need them anymore " "you can remove them with '%(cmd)s'") %{'suffix': self.snapshots.backupSuffix(), 'cmd': 'find ./ -name "*%s" -delete' % self.snapshots.backupSuffix() }) return {'widget': cb, 'retFunc': cb.isChecked, 'id': 'backup'} def restoreOnlyNew(self): cb = QCheckBox(_('Only restore files which do not exist or\n' +\ 'are newer than those in destination.\n' +\ 'Using "rsync --update" option.')) cb.setToolTip("""From 'man rsync': This forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. (If an existing destination file has a modification time equal to the source file’s, it will be updated if the sizes are different.) Note that this does not affect the copying of dirs, symlinks, or other special files. Also, a difference of file format between the sender and receiver is always considered to be important enough for an update, no matter what date is on the objects. In other words, if the source has a directory where the destination has a file, the transfer would occur regardless of the timestamps. This option is a transfer rule, not an exclude, so it doesn’t affect the data that goes into the file-lists, and thus it doesn’t affect deletions. It just limits the files that the receiver requests to be transferred.""") return {'widget': cb, 'retFunc': cb.isChecked, 'id': 'only_new'} def listRestorePaths(self, paths): fileList = QListWidget() fileList.addItems(paths) fileList.setSelectionMode(QAbstractItemView.NoSelection) return {'widget': fileList, 'retFunc': None} def deleteOnRestore(self): cb = QCheckBox(_('Remove newer files in original folder')) cb.setToolTip(_('Restore selected files or folders ' 'to the original destination and\n' 'delete files/folders which are ' 'not in the snapshot.\n' 'This will delete files/folders which where ' 'excluded during taking the snapshot!\n' 'Be extremely careful!!!')) return {'widget': cb, 'retFunc': cb.isChecked, 'id': 'delete'} def confirmRestore(self, paths, restoreTo = None): if restoreTo: msg = _("Do you really want to restore this files(s)\ninto new folder '%(path)s':") \ %{'path': restoreTo} else: msg = _('Do you really want to restore this files(s):') confirm, opt = messagebox.warningYesNoOptions(self, msg, (self.listRestorePaths(paths), self.backupOnRestore(), self.restoreOnlyNew(), self.deleteOnRestore())) return (confirm, opt) def confirmDelete(self, warnRoot = False, restoreTo = None): if restoreTo: msg = _("Are you sure you want to remove all newer files " "in '%(path)s'?") %{'path': restoreTo} else: msg = _('Are you sure you want to remove all newer files in your ' 'original folder?') if warnRoot: msg += '\n\n' msg += _('WARNING: deleting files in filesystem root could break your whole system!!!') return QMessageBox.Yes == messagebox.warningYesNo(self, msg) def restoreThis(self): if self.sid.isRoot: return paths = [f for f, idx in self.multiFileSelected(fullPath = True)] with self.suspendMouseButtonNavigation(): confirm, opt = self.confirmRestore(paths) if not confirm: return if opt['delete'] and not self.confirmDelete(warnRoot = '/' in paths): return rd = RestoreDialog(self, self.sid, paths, **opt) rd.exec() def restoreThisTo(self): if self.sid.isRoot: return paths = [f for f, idx in self.multiFileSelected(fullPath = True)] with self.suspendMouseButtonNavigation(): restoreTo = qttools.getExistingDirectory(self, _('Restore to ...')) if not restoreTo: return restoreTo = self.config.preparePath(restoreTo) confirm, opt = self.confirmRestore(paths, restoreTo) if not confirm: return if opt['delete'] and not self.confirmDelete(warnRoot = '/' in paths, restoreTo = restoreTo): return rd = RestoreDialog(self, self.sid, paths, restoreTo, **opt) rd.exec() def restoreParent(self): if self.sid.isRoot: return with self.suspendMouseButtonNavigation(): confirm, opt = self.confirmRestore((self.path,)) if not confirm: return if opt['delete'] and not self.confirmDelete(warnRoot = self.path == '/'): return rd = RestoreDialog(self, self.sid, self.path, **opt) rd.exec() def restoreParentTo(self): if self.sid.isRoot: return with self.suspendMouseButtonNavigation(): restoreTo = qttools.getExistingDirectory(self, _('Restore to ...')) if not restoreTo: return restoreTo = self.config.preparePath(restoreTo) confirm, opt = self.confirmRestore((self.path,), restoreTo) if not confirm: return if opt['delete'] and not self.confirmDelete(warnRoot = self.path == '/', restoreTo = restoreTo): return rd = RestoreDialog(self, self.sid, self.path, restoreTo, **opt) rd.exec() def btnSnapshotsClicked(self): path, idx = self.fileSelected(fullPath = True) with self.suspendMouseButtonNavigation(): dlg = snapshotsdialog.SnapshotsDialog(self, self.sid, path) if QDialog.Accepted == dlg.exec_(): if dlg.sid != self.sid: self.timeLine.setCurrentSnapshotID(dlg.sid) def btnFolderUpClicked(self): if len(self.path) <= 1: return path = os.path.dirname(self.path) if self.path == path: return self.path = path self.path_history.append(self.path) self.updateFilesView(0) def btnFolderHistoryPreviousClicked(self): path = self.path_history.previous() full_path = self.sid.pathBackup(path) if os.path.isdir(full_path) and self.sid.canOpenPath(path): self.path = path self.updateFilesView(0) def btnFolderHistoryNextClicked(self): path = self.path_history.next() full_path = self.sid.pathBackup(path) if os.path.isdir(full_path) and self.sid.canOpenPath(path): self.path = path self.updateFilesView(0) def btnOpenCurrentItemClicked(self): path, idx = self.fileSelected() if not path: return self.openPath(path) def btnAddIncludeClicked(self): paths = [f for f, idx in self.multiFileSelected(fullPath = True)] include = self.config.include() updatePlaces = False for item in paths: if os.path.isdir(item): include.append((item, 0)) updatePlaces = True else: include.append((item, 1)) self.config.setInclude(include) if updatePlaces: self.updatePlaces() def btnAddExcludeClicked(self): paths = [f for f, idx in self.multiFileSelected(fullPath = True)] exclude = self.config.exclude() exclude.extend(paths) self.config.setExclude(exclude) def filesViewItemActivated(self, model_index): if self.qapp.keyboardModifiers() and Qt.ControlModifier: return if model_index is None: return rel_path = str(self.filesViewProxyModel.data(model_index)) if not rel_path: return self.openPath(rel_path) def tmpCopy(self, full_path, sid = None): """ Create a temporary local copy of the file ``full_path`` and add the temp folder to ``self.tmpDirs`` which will remove them on exit. Args: full_path (str): path to original file sid (snapshots.SID): snapshot ID used as temp folder suffix Returns: str: temporary path to file """ if sid: sid = '_' + sid.sid d = TemporaryDirectory(suffix = sid) tmp_file = os.path.join(d.name, os.path.basename(full_path)) if os.path.isdir(full_path): shutil.copytree(full_path, tmp_file) else: shutil.copy(full_path, d.name) self.tmpDirs.append(d) return tmp_file def openPath(self, rel_path): rel_path = os.path.join(self.path, rel_path) full_path = self.sid.pathBackup(rel_path) if os.path.exists(full_path) and self.sid.canOpenPath(rel_path): if os.path.isdir(full_path): self.path = rel_path self.path_history.append(rel_path) self.updateFilesView(0) else: # prevent backup data from being accidentally overwritten # by create a temporary local copy and only open that one if not isinstance(self.sid, snapshots.RootSnapshot): full_path = self.tmpCopy(full_path, self.sid) self.run = QDesktopServices.openUrl(QUrl('file://' + full_path)) @pyqtSlot(int) def updateFilesView(self, changed_from, selected_file = None, show_snapshots = False): #0 - files view change directory, 1 - files view, 2 - time_line, 3 - places if 0 == changed_from or 3 == changed_from: selected_file = '' if 0 == changed_from: #update places self.places.setCurrentItem(None) for place_index in range(self.places.topLevelItemCount()): item = self.places.topLevelItem(place_index) if self.path == str(item.data(0, Qt.UserRole)): self.places.setCurrentItem(item) break tooltip = '' text = '' if self.sid.isRoot: text = _('Now') tooltip = _('View the current disk content') else: name = self.sid.displayName text = _('Snapshot: %s') % name tooltip = _('View the snapshot made at %s') % name self.filesWidget.setTitle(text) self.filesWidget.setToolTip(tooltip) #try to keep old selected file if selected_file is None: selected_file, idx = self.fileSelected() self.selected_file = selected_file #update files view full_path = self.sid.pathBackup(self.path) if os.path.isdir(full_path): if self.showHiddenFiles: self.filesViewProxyModel.setFilterRegExp(r'') else: self.filesViewProxyModel.setFilterRegExp(r'^[^\.]') model_index = self.filesViewModel.setRootPath(full_path) proxy_model_index = self.filesViewProxyModel.mapFromSource(model_index) self.filesView.setRootIndex(proxy_model_index) self.filesViewToolbar.setEnabled(False) self.stackFilesView.setCurrentWidget(self.filesView) #TODO: find a signal for this self.dirListerCompleted() else: self.btnRestoreMenu.setEnabled(False) self.menuRestore.setEnabled(False) self.btnRestore.setEnabled(False) self.btnRestoreTo.setEnabled(False) self.btnSnapshots.setEnabled(False) self.stackFilesView.setCurrentWidget(self.lblFolderDontExists) #show current path self.editCurrentPath.setText(self.path) self.btnRestoreParent.setText(_("Restore '%s'") % self.path) self.btnRestoreParentTo.setText(_("Restore '%s' to ...") % self.path) #update folder_up button state self.btnFolderUp.setEnabled(len(self.path) > 1) def dirListerCompleted(self): has_files = (self.filesViewProxyModel.rowCount(self.filesView.rootIndex()) > 0) #update restore button state enable = not self.sid.isRoot and has_files self.btnRestoreMenu.setEnabled(enable) self.menuRestore.setEnabled(enable) self.btnRestore.setEnabled(enable) self.btnRestoreTo.setEnabled(enable) #update snapshots button state self.btnSnapshots.setEnabled(has_files) #enable files toolbar self.filesViewToolbar.setEnabled(True) #select selected_file found = False if self.selected_file: index = self.filesView.indexAt(QPoint(0,0)) if not index.isValid(): return while index.isValid(): file_name = (str(self.filesViewProxyModel.data(index))) if file_name == self.selected_file: #TODO: doesn't work reliable self.filesView.setCurrentIndex(index) found = True break index = self.filesView.indexBelow(index) self.selected_file = '' if not found and has_files: self.filesView.setCurrentIndex(self.filesViewProxyModel.index(0, 0)) def fileSelected(self, fullPath = False): idx = qttools.indexFirstColumn(self.filesView.currentIndex()) selected_file = str(self.filesViewProxyModel.data(idx)) if selected_file == '/': #nothing is selected selected_file = '' idx = self.filesViewProxyModel.mapFromSource(self.filesViewModel.index(self.path, 0)) if fullPath: selected_file = os.path.join(self.path, selected_file) return(selected_file, idx) def multiFileSelected(self, fullPath = False): count = 0 for idx in self.filesView.selectedIndexes(): if idx.column() > 0: continue selected_file = str(self.filesViewProxyModel.data(idx)) if selected_file == '/': continue count += 1 if fullPath: selected_file = os.path.join(self.path, selected_file) yield (selected_file, idx) if not count: #nothing is selected idx = self.filesViewProxyModel.mapFromSource(self.filesViewModel.index(self.path, 0)) if fullPath: selected_file = self.path else: selected_file = '' yield (selected_file, idx) def setMouseButtonNavigation(self): self.qapp.installEventFilter(self.mouseButtonEventFilter) @contextmanager def suspendMouseButtonNavigation(self): self.qapp.removeEventFilter(self.mouseButtonEventFilter) yield self.setMouseButtonNavigation() class About(QDialog): def __init__(self, parent = None): super(About, self).__init__(parent) self.parent = parent self.config = parent.config import icon self.setWindowTitle(_('About') + ' ' + self.config.APP_NAME) logo = QLabel('Icon') logo.setPixmap(icon.BIT_LOGO.pixmap(QSize(48, 48))) version = self.config.VERSION ref, hashid = tools.gitRevisionAndHash() git_version = '' if ref: git_version = " git branch '{}' hash '{}'".format(ref, hashid) name = QLabel('<h1>' + self.config.APP_NAME + ' ' + version + '</h1>' + git_version) name.setAlignment(Qt.AlignLeft | Qt.AlignTop) homepage = QLabel(self.mkurl('<https://github.com/bit-team/backintime>')) homepage.setTextInteractionFlags(Qt.LinksAccessibleByMouse) homepage.setOpenExternalLinks(True) bit_copyright = QLabel(self.config.COPYRIGHT + '\n') vlayout = QVBoxLayout(self) hlayout = QHBoxLayout() hlayout.addWidget(logo) hlayout.addWidget(name) hlayout.addStretch() vlayout.addLayout(hlayout) vlayout.addWidget(homepage) vlayout.addWidget(bit_copyright) buttonBoxLeft = QDialogButtonBox(self) btn_authors = buttonBoxLeft.addButton(_('Authors'), QDialogButtonBox.ActionRole) btn_translations = buttonBoxLeft.addButton(_('Translations'), QDialogButtonBox.ActionRole) btn_license = buttonBoxLeft.addButton(_('License'), QDialogButtonBox.ActionRole) buttonBoxRight = QDialogButtonBox(QDialogButtonBox.Ok) hlayout = QHBoxLayout() hlayout.addWidget(buttonBoxLeft) hlayout.addWidget(buttonBoxRight) vlayout.addLayout(hlayout) btn_authors.clicked.connect(self.authors) btn_translations.clicked.connect(self.translations) btn_license.clicked.connect(self.license) buttonBoxRight.accepted.connect(self.accept) def authors(self): return messagebox.showInfo(self, _('Authors'), self.mkurl(self.config.authors())) def translations(self): return messagebox.showInfo(self, _('Translations'), self.mkurl(self.config.translations())) def license(self): return messagebox.showInfo(self, _('License'), self.config.license()) def mkurl(self, msg): msg = re.sub(r'<(.*?)>', self.aHref, msg) msg = re.sub(r'\n', '<br>', msg) return msg def aHref(self, m): if m.group(1).count('@'): return '<a href="mailto:%(url)s">%(url)s</a>' % {'url': m.group(1)} else: return '<a href="%(url)s">%(url)s</a>' % {'url': m.group(1)} class ExtraMouseButtonEventFilter(QObject): """ globally catch mouse buttons 4 and 5 (mostly used as back and forward) and assign it to browse in file history. When updating to Qt5 use Qt.BackButton and Qt.ForwardButton instead. """ def __init__(self, mainWindow): self.mainWindow = mainWindow super(ExtraMouseButtonEventFilter, self).__init__() def eventFilter(self, receiver, event): if event.type() == QEvent.MouseButtonPress and event.button() in (Qt.XButton1, Qt.XButton2): if event.button() == Qt.XButton1: self.mainWindow.btnFolderHistoryPreviousClicked() if event.button() == Qt.XButton2: self.mainWindow.btnFolderHistoryNextClicked() return True else: return super(ExtraMouseButtonEventFilter, self).eventFilter(receiver, event) class RemoveSnapshotThread(QThread): """ remove snapshots in background thread so GUI will not freeze """ refreshSnapshotList = pyqtSignal() hideTimelineItem = pyqtSignal(qttools.SnapshotItem) def __init__(self, parent, items): self.config = parent.config self.snapshots = parent.snapshots self.items = items super(RemoveSnapshotThread, self).__init__(parent) def run(self): last_snapshot = snapshots.lastSnapshot(self.config) renew_last_snapshot = False #inhibit suspend/hibernate during delete self.config.inhibitCookie = tools.inhibitSuspend(toplevel_xid = self.config.xWindowId, reason = 'deleting snapshots') for item, sid in [(x, x.snapshotID()) for x in self.items]: self.snapshots.remove(sid) self.hideTimelineItem.emit(item) if sid == last_snapshot: renew_last_snapshot = True self.refreshSnapshotList.emit() #set correct last snapshot again if renew_last_snapshot: self.snapshots.createLastSnapshotSymlink(snapshots.lastSnapshot(self.config)) #release inhibit suspend if self.config.inhibitCookie: self.config.inhibitCookie = tools.unInhibitSuspend(*self.config.inhibitCookie) class FillTimeLineThread(QThread): """ add snapshot IDs to timeline in background """ addSnapshot = pyqtSignal(snapshots.SID) def __init__(self, parent): self.parent = parent self.config = parent.config super(FillTimeLineThread, self).__init__(parent) def run(self): for sid in snapshots.iterSnapshots(self.config): self.addSnapshot.emit(sid) self.parent.snapshotsList.append(sid) self.parent.snapshotsList.sort() class SetupCron(QThread): """ Check crontab entries on startup. """ def __init__(self, parent): self.config = parent.config super(SetupCron, self).__init__(parent) def run(self): self.config.setupCron() def debugTrace(): """ Set a tracepoint in the Python debugger that works with Qt """ from pdb import set_trace pyqtRemoveInputHook() set_trace() if __name__ == '__main__': cfg = backintime.startApp('backintime-qt') raiseCmd = '' if len(sys.argv) > 1: raiseCmd = '\n'.join(sys.argv[1 :]) appInstance = guiapplicationinstance.GUIApplicationInstance(cfg.appInstanceFile(), raiseCmd) cfg.PLUGIN_MANAGER.load(cfg = cfg) cfg.PLUGIN_MANAGER.appStart() logger.openlog() qapp = qttools.createQApplication(cfg.APP_NAME) translator = qttools.translator() qapp.installTranslator(translator) mainWindow = MainWindow(cfg, appInstance, qapp) if cfg.isConfigured(): cfg.xWindowId = mainWindow.winId() mainWindow.show() qapp.exec_() logger.closelog() cfg.PLUGIN_MANAGER.appExit() appInstance.exitApplication()
gpl-2.0
-2,769,852,633,538,680,300
39.092146
211
0.630381
false
swharden/SWHLab
doc/uses/EPSCs-and-IPSCs/variance method/2016-12-17 02 graphTime2.py
1
4977
import os import sys sys.path.append("../../../../") import swhlab import matplotlib.pyplot as plt import matplotlib.mlab as mlab import numpy as np class ABF2(swhlab.ABF): def phasicTonic(self,m1=None,m2=None,chunkMs=50,quietPercentile=10, histResolution=.5,plotToo=False): """ let's keep the chunkMs as high as we reasonably can. 50ms is good. Things get flakey at lower numbers like 10ms. IMPORTANT! for this to work, prevent 0s from averaging in, so keep bin sizes well above the data resolution. """ # prepare sectioning values to be used later m1=0 if m1 is None else m1*self.pointsPerSec m2=len(abf.sweepY) if m2 is None else m2*self.pointsPerSec m1,m2=int(m1),int(m2) # prepare histogram values to be used later padding=200 # pA or mV of maximum expected deviation chunkPoints=int(chunkMs*self.pointsPerMs) histBins=int((padding*2)/histResolution) # center the data at 0 using peak histogram, not the mean Y=self.sweepY[m1:m2] hist,bins=np.histogram(Y,bins=2*padding) Yoffset=bins[np.where(hist==max(hist))[0][0]] Y=Y-Yoffset # we don't have to, but PDF math is easier # calculate all histogram nChunks=int(len(Y)/chunkPoints) hist,bins=np.histogram(Y,bins=histBins,range=(-padding,padding)) hist=hist/len(Y) # count as a fraction of total Xs=bins[1:] # get baseline data from chunks with smallest variance chunks=np.reshape(Y[:nChunks*chunkPoints],(nChunks,chunkPoints)) variances=np.var(chunks,axis=1) percentiles=np.empty(len(variances)) for i,variance in enumerate(variances): percentiles[i]=sorted(variances).index(variance)/len(variances)*100 blData=chunks[np.where(percentiles<=quietPercentile)[0]].flatten() # generate the standard curve and pull it to the histogram height sigma=np.sqrt(np.var(blData)) center=np.average(blData)+histResolution/2 blCurve=mlab.normpdf(Xs,center,sigma) blCurve=blCurve*max(hist)/max(blCurve) # determine the phasic current by subtracting-out the baseline #diff=hist-blCurve diff=hist IGNORE_DISTANCE=5 # KEEP THIS FIXED, NOT A FUNCTION OF VARIANCE ignrCenter=len(Xs)/2 ignrPad=IGNORE_DISTANCE/histResolution ignr1,ignt2=int(ignrCenter-ignrPad),int(ignrCenter+ignrPad) diff[ignr1:ignt2]=0 # optionally graph all this if plotToo: plt.figure(figsize=(15,5)) plt.plot(Y) plt.figure(figsize=(7,7)) ax1=plt.subplot(211) plt.title(abf.ID+" phasic analysis") plt.ylabel("fraction") plt.plot(Xs,hist,'-',alpha=.8,color='b',lw=3) plt.plot(Xs,blCurve,lw=3,alpha=.5,color='r') plt.margins(0,.1) plt.subplot(212,sharex=ax1) plt.title("baseline subtracted") plt.ylabel("fraction") plt.xlabel("data points (%s)"%abf.units) plt.plot(Xs,diff,'-',alpha=.8,color='b',lw=3) plt.axhline(0,lw=3,alpha=.5,color='r') plt.axvline(0,lw=3,alpha=.5,color='k') plt.margins(0,.1) plt.axis([-50,50,None,None]) plt.tight_layout() plt.show() print(np.sum(np.split(diff,2),1)) return diff/len(Y)*abf.pointsPerSec # charge/sec if __name__=="__main__": #abfPath=r"X:\Data\2P01\2016\2016-09-01 PIR TGOT" abfPath=r"C:\Users\scott\Documents\important\demodata" abf=ABF2(os.path.join(abfPath,"16d16007.abf")) histPoints=len(abf.phasicTonic(.75)) nSweeps=25 plt.figure(figsize=(10,5)) plt.grid() for title,sweep1 in [["baseline",200],["baseline",240],["baseline",350]]: hists=np.zeros((nSweeps,histPoints)) for i in range(nSweeps): sweep=sweep1+i abf.setsweep(sweep) hists[i]=abf.phasicTonic(.75) AV=np.average(hists,axis=0) plt.plot(AV,lw=5,alpha=.5,label=title) plt.legend() # for sweep in abf.setsweeps(): # phasic=abf.phasicTonic(.75) # neg[sweep],pos[sweep]=np.sum(np.split(phasic,2),1) # # plt.plot(pos,'.',color='b',alpha=.5) # plt.plot(swhlab.common.lowpass(pos),'-',color='b',alpha=.5,lw=5,label="upward") # plt.plot(neg,'.',color='r',alpha=.5) # plt.plot(swhlab.common.lowpass(neg),'-',color='r',alpha=.5,lw=5,label="downward") # for sweep in abf.comment_sweeps: # plt.axvline(sweep,lw=5,alpha=.5,color='g',ls='--') # plt.axhline(0,color='k',lw=3,alpha=.5) plt.xlabel("sweep number") plt.ylabel("ms * pA / sec") # plt.legend(loc='upper left',shadow=True) plt.show() print("DONE")
mit
254,409,926,683,854,400
37.589147
86
0.594334
false
rhyolight/nupic.son
app/soc/modules/gsoc/logic/proposal.py
1
10718
# Copyright 2011 the Melange 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. """GSoC logic for proposals.""" from google.appengine.ext import db from google.appengine.ext import ndb from melange.utils import time as time_utils from soc.logic import timeline as timeline_logic from soc.views.helper import request_data from soc.modules.gsoc.models import project as project_model from soc.modules.gsoc.models import proposal as proposal_model def getProposalsToBeAcceptedForOrg(organization, step_size=25): """Returns all proposals which will be accepted into the program for the specified organization. Args: organization: Organization entity. step_size: optional parameter to specify the amount of Student Proposals that should be retrieved per roundtrip to the datastore Returns: List with all GSoCProposal which will be accepted into the program """ # check if there are already slots taken by this org query = proposal_model.GSoCProposal.all() query.filter('org', organization.key.to_old_key()) query.filter('status', proposal_model.STATUS_ACCEPTED) slots_left_to_assign = max(0, organization.slot_allocation - query.count()) if slots_left_to_assign == 0: # no slots left so return nothing return [] query = proposal_model.GSoCProposal.all() query.filter('org', organization.key.to_old_key()) query.filter('status', 'pending') query.filter('accept_as_project', True) query.filter('has_mentor', True) query.order('-score') # We are not putting this into the filter because order and != do not mix # in GAE. proposals = query.fetch(slots_left_to_assign) offset = slots_left_to_assign # retrieve as many additional proposals as needed in case the top # N do not have a mentor assigned while len(proposals) < slots_left_to_assign: new_proposals = query.fetch(step_size, offset=offset) if not new_proposals: # we ran out of proposals` break proposals += new_proposals offset += step_size # cut off any superfluous proposals return proposals[:slots_left_to_assign] def getProposalsQuery(keys_only=False, ancestor=None, **properties): """Returns the Appengine proposal_model.GSoCProposal query object for the given set of properties. Args: ancestor: The student for whom the proposals must be fetched. properties: keyword arguments containing the properties for which the query must be constructed. """ query = db.Query(proposal_model.GSoCProposal, keys_only=keys_only) if ancestor: query.ancestor(ancestor) for k, v in properties.items(): query.filter(k, v) return query def hasMentorProposalAssigned(profile, org_key=None): """Checks whether the specified profile has a proposal assigned. It also accepts an optional argument to pass a specific organization to which the proposal should belong. Please note that this function executes a non-ancestor query, so it cannot be safely used within transactions. Args: profile: the specified GSoCProfile entity or its db.Key org_key: optional organization key Returns: True, if the profile has at least one proposal assigned; False otherwise. """ query = proposal_model.GSoCProposal.all(keys_only=True) query.filter('mentor', profile.key.to_old_key()) if org_key: query.filter('org', org_key.to_old_key()) return query.count() > 0 def canSubmitProposal(profile, program, timeline): """Tells whether the specified student can submit a proposal for the specified program. Args: profile: Profile entity. program: program entity timeline: timeline entity for the program Returns: True if a new proposal may be submitted; False otherwise """ # check if given timeline corresponds to the given program if not timeline_logic.isTimelineForProgram(timeline.key(), program.key()): raise ValueError('The specified timeline (key_name: %s) is ' 'not related to program (key_name: %s).' % ( timeline.key().name(), program.key().name())) # check the student application period is open timeline_helper = request_data.TimelineHelper(timeline, None) if not timeline_helper.studentSignup(): return False # check if the student has not reached the limit of apps per program if profile.student_data.number_of_proposals >= program.apps_tasks_limit: return False return True def canProposalBeWithdrawn(proposal): """Tells whether the specified proposal can be withdrawn. Args: proposal: proposal entity Returns: True, if the proposal can be withdrawn; False otherwise """ # only pending proposals can be withdrawn # TODO(daniel): discuss with the team what to do with 'ignored' proposals # TODO(daniel): discuss with the team if it should be possible to withdraw # proposals after student application period is over. No? return proposal.status == proposal_model.STATUS_PENDING def canProposalBeResubmitted(proposal, profile, program, timeline): """Tells whether the specified proposal can be resubmitted by the specified student for the given program. Args: proposal: Proposal entity. profile: Profile entity. program: Program entity. timeline: Timeline entity for the program. Returns: True, if the proposal can be resubmitted; False otherwise """ # check if given timeline corresponds to the given program if not timeline_logic.isTimelineForProgram(timeline.key(), program.key()): raise ValueError('The specified timeline (key_name: %s) is ' 'not related to program (key_name: %s).' % ( timeline.key().name(), program.key().name())) if time_utils.isAfter(timeline.accepted_students_announced_deadline): # students have been accepted / rejected return False elif proposal.status != proposal_model.STATUS_WITHDRAWN: # only withdrawn proposals can be resubmitted return False elif profile.student_data.number_of_proposals >= program.apps_tasks_limit: # student has not reached the limit of proposals per program return False else: return True def withdrawProposal(proposal, profile): """Withdraws proposal for the specified student profile. Args: proposal: Proposal entity. profile: Profile entity. Returns: True, if the proposal is withdrawn upon returning from this function; False otherwise """ if not canProposalBeWithdrawn(proposal): # check if the proposal is already withdrawn return proposal.status == proposal_model.STATUS_WITHDRAWN proposal.status = proposal_model.STATUS_WITHDRAWN profile.student_data.number_of_proposals -= 1 # student info and proposal are in the same entity group db.put(proposal) # TODO(daniel): it should be persisted along with proposal profile.put() return True def resubmitProposal(proposal, profile, program, timeline): """Resubmits (changes status from 'withdrawn' to 'pending') the specified proposal for the specified student and program. Args: proposal: proposal entity profile: Profile entity of the student to whom the proposal belongs. program: program entity timeline: timeline entity for the program Returns: True, if the proposal is effectively resubmitted (i.e. its status is pending) after this function; False otherwise """ # check if given timeline corresponds to the given program if not timeline_logic.isTimelineForProgram(timeline.key(), program.key()): raise ValueError('The specified timeline (key_name: %s) is ' 'not related to program (key_name: %s).' % ( timeline.key().name(), program.key().name())) if not canProposalBeResubmitted( proposal, profile, program, timeline): # check if the proposal is not already pending return proposal.status == proposal_model.STATUS_PENDING proposal.status = proposal_model.STATUS_PENDING profile.student_data.number_of_proposals += 1 # TODO(daniel): it should be persisted along with proposal proposal.put() profile.put() return True def acceptProposal(proposal): """Accepts the specified proposal as a project and creates a new project entity if one has not been created so far. Args: proposal: proposal entity Returns: project entity created for the specified proposal """ profile_key = proposal.parent_key() # check if a project for the proposal has already been created query = project_model.GSoCProject.all() query.ancestor(profile_key) current_projects = query.fetch(1000) for current_project in current_projects: proposal_key = project_model.GSoCProject.proposal.get_value_for_datastore( current_project) # if a project exists, return it rather than create a new one if proposal_key == proposal.key(): return current_project org_key = proposal_model.GSoCProposal.org.get_value_for_datastore(proposal) program_key = proposal_model.GSoCProposal.program.get_value_for_datastore( proposal) mentor_key = proposal_model.GSoCProposal.mentor.get_value_for_datastore( proposal) if not mentor_key: raise ValueError('The proposal for profile %s with id %s has no ' 'mentor specified' % (proposal.parent_key().name, proposal.key().id())) # create new project entity properties = { 'abstract': proposal.abstract, 'mentors': [mentor_key], 'org': org_key, 'proposal': proposal, 'program': program_key, 'title': proposal.title, } project = project_model.GSoCProject(parent=profile_key, **properties) # get student and update its related properties profile = ndb.Key.from_old_key(profile_key).get() profile.student_data.number_of_projects += 1 profile.student_data.project_for_orgs.append(ndb.Key.from_old_key(org_key)) profile.student_data.project_for_orgs = list( set(profile.student_data.project_for_orgs)) profile.put() # update proposal's status proposal.status = proposal_model.STATUS_ACCEPTED db.put([proposal, project]) return project def rejectProposal(proposal): """Rejects the specified proposal. Args: proposal: proposal entity """ # update proposal's status proposal.status = proposal_model.STATUS_REJECTED proposal.put()
apache-2.0
-2,249,792,019,297,273,300
31.283133
79
0.726721
false
ericmjl/bokeh
tests/unit/bokeh/plotting/test_graph.py
1
7793
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import pytest ; pytest #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # External imports import networkx as nx import numpy as np from numpy.testing import assert_allclose # Module under test import bokeh.plotting.graph as bpg # isort:skip #----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def test_from_networkx_method() -> None: G=nx.Graph() G.add_nodes_from([0,1,2,3]) G.add_edges_from([[0,1], [0,2], [2,3]]) renderer = bpg.from_networkx(G, nx.circular_layout) assert renderer.node_renderer.data_source.data["index"] == [0,1,2,3] assert renderer.edge_renderer.data_source.data["start"] == [0,0,2] assert renderer.edge_renderer.data_source.data["end"] == [1,2,3] gl = renderer.layout_provider.graph_layout assert set(gl.keys()) == set([0,1,2,3]) assert_allclose(gl[0], np.array([1., 0.]), atol=1e-7) def test_from_networkx_method_with_kwargs() -> None: G=nx.Graph() G.add_nodes_from([0,1,2,3]) G.add_edges_from([[0,1], [0,2], [2,3]]) renderer = bpg.from_networkx(G, nx.circular_layout, scale=2) gl = renderer.layout_provider.graph_layout assert set(gl.keys()) == set([0,1,2,3]) assert_allclose(gl[0], np.array([2., 0.]), atol=1e-7) def test_from_networkx_with_scalar_attributes() -> None: G = nx.Graph() G.add_nodes_from([(0, {"attr_1": "a", "attr_2": 10}), (1, {"attr_1": "b"}), (2, {"attr_1": "c", "attr_2": 30})]) G.add_edges_from([(0, 1, {"attr_1": "A"}), (0, 2, {"attr_1": "B", "attr_2": 10})]) renderer = bpg.from_networkx(G, nx.circular_layout) assert renderer.node_renderer.data_source.data["index"] == [0, 1, 2] assert renderer.node_renderer.data_source.data["attr_1"] == ["a", "b", "c"] assert renderer.node_renderer.data_source.data["attr_2"] == [10, None, 30] assert renderer.edge_renderer.data_source.data["start"] == [0, 0] assert renderer.edge_renderer.data_source.data["end"] == [1, 2] assert renderer.edge_renderer.data_source.data["attr_1"] == ["A", "B"] assert renderer.edge_renderer.data_source.data["attr_2"] == [None, 10] @pytest.mark.parametrize('typ', [list, tuple]) def test_from_networkx_with_sequence_attributes(typ) -> None: G = nx.Graph() G.add_nodes_from([(0, {"attr_1": typ([1, 2]), "attr_2": 10}), (1, {}), (2, {"attr_1": typ([3]), "attr_2": 30})]) G.add_edges_from([(0, 1, {"attr_1": typ([1, 11])}), (0, 2, {"attr_1": typ([2, 22]), "attr_2": 10})]) renderer = bpg.from_networkx(G, nx.circular_layout) assert renderer.node_renderer.data_source.data["index"] == [0, 1, 2] assert renderer.node_renderer.data_source.data["attr_1"] == [[1, 2], [], [3]] assert renderer.node_renderer.data_source.data["attr_2"] == [10, None, 30] assert renderer.edge_renderer.data_source.data["start"] == [0, 0] assert renderer.edge_renderer.data_source.data["end"] == [1, 2] assert renderer.edge_renderer.data_source.data["attr_1"] == [[1, 11], [2, 22]] assert renderer.edge_renderer.data_source.data["attr_2"] == [None, 10] def test_from_networkx_errors_with_mixed_attributes() -> None: G = nx.Graph() G.add_nodes_from([(0, {"attr_1": [1, 2], "attr_2": 10}), (1, {}), (2, {"attr_1": 3, "attr_2": 30})]) with pytest.raises(ValueError): bpg.from_networkx(G, nx.circular_layout) G = nx.Graph() G.add_edges_from([(0, 1, {"attr_1": [1, 11]}), (0, 2, {"attr_1": 2, "attr_2": 10})]) with pytest.raises(ValueError): bpg.from_networkx(G, nx.circular_layout) def test_from_networkx_with_bad_attributes() -> None: G = nx.Graph() G.add_nodes_from([(0, {"index": "a", "attr_1": 10}), (1, {"index": "b", "attr_1": 20})]) G.add_edges_from([[0, 1]]) with pytest.warns(UserWarning): renderer = bpg.from_networkx(G, nx.circular_layout) assert renderer.node_renderer.data_source.data["index"] == [0, 1] assert renderer.node_renderer.data_source.data["attr_1"] == [10, 20] G = nx.Graph() G.add_nodes_from([0, 1]) G.add_edges_from([(0, 1, {"start": "A", "attr_1": 10})]) with pytest.warns(UserWarning): renderer = bpg.from_networkx(G, nx.circular_layout) assert renderer.edge_renderer.data_source.data["start"] == [0] assert renderer.edge_renderer.data_source.data["end"] == [1] assert renderer.edge_renderer.data_source.data["attr_1"] == [10] G = nx.Graph() G.add_nodes_from([0, 1]) G.add_edges_from([(0, 1, {"end": "A", "attr_1": 10})]) with pytest.warns(UserWarning): renderer = bpg.from_networkx(G, nx.circular_layout) assert renderer.edge_renderer.data_source.data["start"] == [0] assert renderer.edge_renderer.data_source.data["end"] == [1] assert renderer.edge_renderer.data_source.data["attr_1"] == [10] def test_from_networkx_fixed_layout() -> None: G = nx.Graph() G.add_nodes_from([0, 1, 2]) G.add_edges_from([[0, 1], [0, 2]]) fixed_layout = {0: [0, 1], 1: [-1, 0], 2: [1, 0]} renderer = bpg.from_networkx(G, fixed_layout) assert renderer.node_renderer.data_source.data["index"] == [0, 1, 2] assert renderer.edge_renderer.data_source.data["start"] == [0, 0] assert renderer.edge_renderer.data_source.data["end"] == [1, 2] gl = renderer.layout_provider.graph_layout assert set(gl.keys()) == set([0, 1, 2]) assert renderer.layout_provider.graph_layout[0] == fixed_layout[0] assert renderer.layout_provider.graph_layout[1] == fixed_layout[1] assert renderer.layout_provider.graph_layout[2] == fixed_layout[2] def test_from_networkx_with_missing_layout() -> None: G = nx.Graph() G.add_nodes_from([0, 1, 2]) G.add_edges_from([[0, 1], [0, 2]]) missing_fixed_layout = {0: [0, 1], 1: [-1, 0]} with pytest.warns(UserWarning): renderer = bpg.from_networkx(G, missing_fixed_layout) gl = renderer.layout_provider.graph_layout assert set(gl.keys()) == set([0, 1]) assert renderer.layout_provider.graph_layout[0] == missing_fixed_layout[0] assert renderer.layout_provider.graph_layout[1] == missing_fixed_layout[1] #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
bsd-3-clause
5,915,552,054,748,063,000
40.232804
82
0.493135
false
saeki-masaki/cinder
cinder/api/contrib/consistencygroups.py
1
15052
# Copyright (C) 2012 - 2014 EMC Corporation. # 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. """The consistencygroups api.""" from oslo_log import log as logging from oslo_utils import strutils import webob from webob import exc from cinder.api import common from cinder.api import extensions from cinder.api.openstack import wsgi from cinder.api.views import consistencygroups as consistencygroup_views from cinder.api import xmlutil from cinder import consistencygroup as consistencygroupAPI from cinder import exception from cinder.i18n import _, _LI from cinder import utils LOG = logging.getLogger(__name__) def make_consistencygroup(elem): elem.set('id') elem.set('status') elem.set('availability_zone') elem.set('created_at') elem.set('name') elem.set('description') def make_consistencygroup_from_src(elem): elem.set('id') elem.set('status') elem.set('created_at') elem.set('name') elem.set('description') elem.set('cgsnapshot_id') class ConsistencyGroupTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('consistencygroup', selector='consistencygroup') make_consistencygroup(root) alias = Consistencygroups.alias namespace = Consistencygroups.namespace return xmlutil.MasterTemplate(root, 1, nsmap={alias: namespace}) class ConsistencyGroupsTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('consistencygroups') elem = xmlutil.SubTemplateElement(root, 'consistencygroup', selector='consistencygroups') make_consistencygroup(elem) alias = Consistencygroups.alias namespace = Consistencygroups.namespace return xmlutil.MasterTemplate(root, 1, nsmap={alias: namespace}) class ConsistencyGroupFromSrcTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('consistencygroup-from-src', selector='consistencygroup-from-src') make_consistencygroup_from_src(root) alias = Consistencygroups.alias namespace = Consistencygroups.namespace return xmlutil.MasterTemplate(root, 1, nsmap={alias: namespace}) class CreateDeserializer(wsgi.MetadataXMLDeserializer): def default(self, string): dom = utils.safe_minidom_parse_string(string) consistencygroup = self._extract_consistencygroup(dom) return {'body': {'consistencygroup': consistencygroup}} def _extract_consistencygroup(self, node): consistencygroup = {} consistencygroup_node = self.find_first_child_named( node, 'consistencygroup') attributes = ['name', 'description'] for attr in attributes: if consistencygroup_node.getAttribute(attr): consistencygroup[attr] = consistencygroup_node.\ getAttribute(attr) return consistencygroup class CreateFromSrcDeserializer(wsgi.MetadataXMLDeserializer): def default(self, string): dom = utils.safe_minidom_parse_string(string) consistencygroup = self._extract_consistencygroup(dom) retval = {'body': {'consistencygroup-from-src': consistencygroup}} return retval def _extract_consistencygroup(self, node): consistencygroup = {} consistencygroup_node = self.find_first_child_named( node, 'consistencygroup-from-src') attributes = ['cgsnapshot', 'name', 'description'] for attr in attributes: if consistencygroup_node.getAttribute(attr): consistencygroup[attr] = ( consistencygroup_node.getAttribute(attr)) return consistencygroup class ConsistencyGroupsController(wsgi.Controller): """The ConsistencyGroups API controller for the OpenStack API.""" _view_builder_class = consistencygroup_views.ViewBuilder def __init__(self): self.consistencygroup_api = consistencygroupAPI.API() super(ConsistencyGroupsController, self).__init__() @wsgi.serializers(xml=ConsistencyGroupTemplate) def show(self, req, id): """Return data about the given consistency group.""" LOG.debug('show called for member %s', id) context = req.environ['cinder.context'] try: consistencygroup = self.consistencygroup_api.get( context, group_id=id) except exception.ConsistencyGroupNotFound as error: raise exc.HTTPNotFound(explanation=error.msg) return self._view_builder.detail(req, consistencygroup) def delete(self, req, id, body): """Delete a consistency group.""" LOG.debug('delete called for member %s', id) context = req.environ['cinder.context'] force = False if body: if not self.is_valid_body(body, 'consistencygroup'): msg = _("Missing required element 'consistencygroup' in " "request body.") raise exc.HTTPBadRequest(explanation=msg) cg_body = body['consistencygroup'] try: force = strutils.bool_from_string(cg_body.get('force', False), strict=True) except ValueError: msg = _("Invalid value '%s' for force.") % force raise exc.HTTPBadRequest(explanation=msg) LOG.info(_LI('Delete consistency group with id: %s'), id, context=context) try: group = self.consistencygroup_api.get(context, id) self.consistencygroup_api.delete(context, group, force) except exception.ConsistencyGroupNotFound: msg = _("Consistency group %s could not be found.") % id raise exc.HTTPNotFound(explanation=msg) except exception.InvalidConsistencyGroup as error: raise exc.HTTPBadRequest(explanation=error.msg) return webob.Response(status_int=202) @wsgi.serializers(xml=ConsistencyGroupsTemplate) def index(self, req): """Returns a summary list of consistency groups.""" return self._get_consistencygroups(req, is_detail=False) @wsgi.serializers(xml=ConsistencyGroupsTemplate) def detail(self, req): """Returns a detailed list of consistency groups.""" return self._get_consistencygroups(req, is_detail=True) def _get_consistencygroups(self, req, is_detail): """Returns a list of consistency groups through view builder.""" context = req.environ['cinder.context'] consistencygroups = self.consistencygroup_api.get_all(context) limited_list = common.limited(consistencygroups, req) if is_detail: consistencygroups = self._view_builder.detail_list(req, limited_list) else: consistencygroups = self._view_builder.summary_list(req, limited_list) return consistencygroups @wsgi.response(202) @wsgi.serializers(xml=ConsistencyGroupTemplate) @wsgi.deserializers(xml=CreateDeserializer) def create(self, req, body): """Create a new consistency group.""" LOG.debug('Creating new consistency group %s', body) if not self.is_valid_body(body, 'consistencygroup'): raise exc.HTTPBadRequest() context = req.environ['cinder.context'] try: consistencygroup = body['consistencygroup'] except KeyError: msg = _("Incorrect request body format") raise exc.HTTPBadRequest(explanation=msg) name = consistencygroup.get('name', None) description = consistencygroup.get('description', None) volume_types = consistencygroup.get('volume_types', None) if not volume_types: msg = _("volume_types must be provided to create " "consistency group %(name)s.") % {'name': name} raise exc.HTTPBadRequest(explanation=msg) availability_zone = consistencygroup.get('availability_zone', None) LOG.info(_LI("Creating consistency group %(name)s."), {'name': name}, context=context) try: new_consistencygroup = self.consistencygroup_api.create( context, name, description, volume_types, availability_zone=availability_zone) except exception.InvalidConsistencyGroup as error: raise exc.HTTPBadRequest(explanation=error.msg) except exception.InvalidVolumeType as error: raise exc.HTTPBadRequest(explanation=error.msg) except exception.ConsistencyGroupNotFound as error: raise exc.HTTPNotFound(explanation=error.msg) retval = self._view_builder.summary( req, dict(new_consistencygroup)) return retval @wsgi.response(202) @wsgi.serializers(xml=ConsistencyGroupFromSrcTemplate) @wsgi.deserializers(xml=CreateFromSrcDeserializer) def create_from_src(self, req, body): """Create a new consistency group from a source. The source can be a snapshot. It could be extended in the future to support other sources. Note that this does not require volume_types as the "create" API above. """ LOG.debug('Creating new consistency group %s.', body) if not self.is_valid_body(body, 'consistencygroup-from-src'): raise exc.HTTPBadRequest() context = req.environ['cinder.context'] try: consistencygroup = body['consistencygroup-from-src'] except KeyError: msg = _("Incorrect request body format.") raise exc.HTTPBadRequest(explanation=msg) name = consistencygroup.get('name', None) description = consistencygroup.get('description', None) cgsnapshot_id = consistencygroup.get('cgsnapshot_id', None) if not cgsnapshot_id: msg = _("Cgsnapshot id must be provided to create " "consistency group %(name)s from source.") % {'name': name} raise exc.HTTPBadRequest(explanation=msg) LOG.info(_LI("Creating consistency group %(name)s from cgsnapshot " "%(snap)s."), {'name': name, 'snap': cgsnapshot_id}, context=context) try: new_consistencygroup = self.consistencygroup_api.create_from_src( context, name, description, cgsnapshot_id) except exception.InvalidConsistencyGroup as error: raise exc.HTTPBadRequest(explanation=error.msg) except exception.CgSnapshotNotFound as error: raise exc.HTTPBadRequest(explanation=error.msg) except exception.ConsistencyGroupNotFound as error: raise exc.HTTPNotFound(explanation=error.msg) except exception.CinderException as error: raise exc.HTTPBadRequest(explanation=error.msg) retval = self._view_builder.summary( req, dict(new_consistencygroup)) return retval @wsgi.serializers(xml=ConsistencyGroupTemplate) def update(self, req, id, body): """Update the consistency group. Expected format of the input parameter 'body': { "consistencygroup": { "name": "my_cg", "description": "My consistency group", "add_volumes": "volume-uuid-1,volume-uuid-2,..." "remove_volumes": "volume-uuid-8,volume-uuid-9,..." } } """ LOG.debug('Update called for consistency group %s.', id) if not body: msg = _("Missing request body.") raise exc.HTTPBadRequest(explanation=msg) if not self.is_valid_body(body, 'consistencygroup'): msg = _("Incorrect request body format.") raise exc.HTTPBadRequest(explanation=msg) context = req.environ['cinder.context'] consistencygroup = body.get('consistencygroup', None) name = consistencygroup.get('name', None) description = consistencygroup.get('description', None) add_volumes = consistencygroup.get('add_volumes', None) remove_volumes = consistencygroup.get('remove_volumes', None) if (not name and not description and not add_volumes and not remove_volumes): msg = _("Name, description, add_volumes, and remove_volumes " "can not be all empty in the request body.") raise exc.HTTPBadRequest(explanation=msg) LOG.info(_LI("Updating consistency group %(id)s with name %(name)s " "description: %(description)s add_volumes: " "%(add_volumes)s remove_volumes: %(remove_volumes)s."), {'id': id, 'name': name, 'description': description, 'add_volumes': add_volumes, 'remove_volumes': remove_volumes}, context=context) try: group = self.consistencygroup_api.get(context, id) self.consistencygroup_api.update( context, group, name, description, add_volumes, remove_volumes) except exception.ConsistencyGroupNotFound: msg = _("Consistency group %s could not be found.") % id raise exc.HTTPNotFound(explanation=msg) except exception.InvalidConsistencyGroup as error: raise exc.HTTPBadRequest(explanation=error.msg) return webob.Response(status_int=202) class Consistencygroups(extensions.ExtensionDescriptor): """consistency groups support.""" name = 'Consistencygroups' alias = 'consistencygroups' namespace = 'http://docs.openstack.org/volume/ext/consistencygroups/api/v1' updated = '2014-08-18T00:00:00+00:00' def get_resources(self): resources = [] res = extensions.ResourceExtension( Consistencygroups.alias, ConsistencyGroupsController(), collection_actions={'detail': 'GET', 'create_from_src': 'POST'}, member_actions={'delete': 'POST', 'update': 'PUT'}) resources.append(res) return resources
apache-2.0
-6,583,478,272,288,918,000
38.506562
79
0.628289
false
bgarrels/sky
sky/legacy/indexer2.py
2
12219
import numpy as np import os import justext from bs4 import BeautifulSoup import re import codecs import lxml import sys if True: try: from urllib import urlopen except: from urllib.request import urlopen sys.path.append('/Users/pascal/Dropbox/watsonTestSuite/') from htmlTree import * collectionName = 'OneMediq' PATH = '/Users/pascal/Dropbox/watsonTestSuite/collections/' + collectionName + '/' OUT_PATH = '/Users/pascal/Dropbox/watsonTestSuite/collections/' + collectionName + '-snippets/' if not os.path.exists(OUT_PATH): os.makedirs(OUT_PATH) class CrawledDocs(): def __init__(self, inp, maxN=10000000): if isinstance(inp, str): if os.path.isdir(inp): self.readfiles(inp, maxN) else: self.readweb(inp) else: self.readweb(inp) def readfiles(self, PATH, maxN): soups = [] htmls = [] lxmls = [] file_names = [] num = 0 for root, dirs, files in os.walk(PATH): for name in files: if num >= maxN: break if ("DS" not in name) and ('links.txt' not in name): num += 1 with open(root + "/" + name, encoding='latin-1') as page: html = page.read() soup = BeautifulSoup(html).html htmls.append(html) lxmls.append(lxml.html.fromstring(html)) soups.append(soup) file_names.append(name) self.soups = soups self.lxmls = lxmls self.htmls = htmls self.file_names = file_names def readweb(self, inp): if isinstance(inp, str): htmls = [urlopen(inp).read()] self.file_names = [inp] elif isinstance(inp, list): self.htmls = [urlopen(url).read() for url in inp] self.lxmls = [lxml.html.fromstring(x) for x in self.htmls] self.soups = [BeautifulSoup(x) for x in self.htmls] self.file_names = inp class IndexImportant(): def __init__(self, crawledDocs): self.cD = crawledDocs def textGather(self, soupChildren, sofar=None, level=0): if sofar is None: sofar = [] container = [] for x in soupChildren: if hasattr(x, "text"): sofar.append([x, x.text]) try: container.extend([y for y in x.children]) except: pass if container == []: return(sofar) return(self.textGather(container, sofar, level+1)) def textGatherLXML(self, soupChildren, sofar=None, level=0): if sofar is None: sofar = [] container = [] for x in soupChildren: try: children = x.getchildren() except: children = [] if children: container.extend([y for y in children]) try: sofar.append([x, x.text_content()]) except: sofar.append([x, '']) if container == []: return(sofar) return(self.textGatherLXML(container, sofar, level+1)) def filterUniques(self, seq): seen = set() seen_add = seen.add seq = [(x[0], re.sub("\s+", " ", x[1]).strip()) for x in seq] return([ x for x in seq if not (x[1] in seen or seen_add(x[1]))]) def trainer(self, trees, n_max = 20): ress = [] if 'bs4' in trees[0].__module__: for tree in trees[:n_max]: ress.append(self.filterUniques(self.textGather(tree))) else: for tree in trees[:n_max]: ress.append(self.filterUniques(self.textGatherLXML(tree))) trained = [] for x in ress[0]: if all([x[1] in [z[1] for z in y] for y in ress[1:]]): trained.append(x[1]) return(trained) def tester(self, tree, trained): result = [] if 'bs4' in tree.__module__ : unis = self.filterUniques(self.textGather(tree)) else: unis = self.filterUniques(self.textGatherLXML(tree)) for x in unis: if x[1] not in trained: result.append(x) return(result) def removeJavascript(self, ts): result = [] java_script_blacklist = ['\$([^)]+).', 'var [^ ]+ [^;]+;'] for x in ts: if 'document' not in x[1]: if "();" not in x[1]: if all([not re.search(y, x[1]) for y in java_script_blacklist]): result.append(x) return(result) def pruner(self, ts, pruning, remove_javascript=True, printText=True): # remove javascript if remove_javascript: ts = self.removeJavascript(ts) # prune if pruning: leftover = [] done = [] for x in ts: notinit = True for y in ts: if (x[1] in y[1]) & (y[1] != x[1]): notinit = False break if notinit: leftover.append(x) ts = leftover if printText: if 'bs4' in ts[0][0].__module__: return([x[0].text for x in ts]) else: return([x[0].text_content() for x in ts]) return(ts) def prepare(self, trees, pruning=True, remove_javascript=True, printText=True, train_n_max = 20): tr = self.trainer(trees, train_n_max) results = [] for tree in trees: ts = self.tester(tree, tr) results.append(self.pruner(ts, pruning, remove_javascript, printText)) self.results = results def write_results(self, OUT_PATH): for x, y in zip(self.results, self.cD.file_names): with codecs.open(OUT_PATH + y + ".txt", 'w', 'utf-8-sig') as f: f.write("\n\n\n".join(x)) def getsubidx(self, list1, list2): l1, l2 = len(list1), len(list2) for i in range(l1-l2): if list1[i:i+l2] == list2: return(i) def pinpoint(self, lxmls, which): #res = self.prepare(lxmls[:20], True, printText=False) res = self.results whole = lxmlTree(lxmls[which], True, False) abc = 'abcdefghijklmnopqrstuvwxyz' * 100 for num, annot in enumerate(res[which]): wholeE = ['+' + ''.join(x.strip().split('+')[1:]) for x in whole.split('\n') if x.strip()] part = lxmlTree(annot[0], True, False) partE = ['+' + ''.join(x.strip().split('+')[1:]) for x in part.split('\n')[1:] if x.strip()] ind = max(2, self.getsubidx(wholeE, partE) - 2) tmp = whole.split('\n') match_len = len(partE) for i in range(len(tmp)): if i > ind and i < ind + match_len + 2: tmp[i] += ' -(' + str(abc[num]) + ')-' whole = "\n".join(tmp) print(whole) cD = CrawledDocs(PATH, 100) a = IndexImportant(cD) a.prepare(cD.lxmls, True, printText=False) a.pinpoint(cD.lxmls, 1) a.prepare(cD.lxmls, True, printText=True) #a.write_results(OUT_PATH) # res = self.prepare(lxmls[:20], True, printText=False) cD.htmls = [x for i,x in enumerate(cD.htmls) if i in ok] cD.lxmls = [x for i,x in enumerate(cD.lxmls) if i in ok] cD.file_names = [x for i,x in enumerate(cD.file_names) if i in ok] #pinpoint(cD.lxmls, 0) # a = IndexImportant(cD) # a.prepare(a.cD.lxmls, printText=False) # a.write_results(OUT_PATH) # pinpoint(a.cD.lxmls, 0) # def get_xpath(res): # things = [] # for x in res: # things.append([(y[0].name, y[0].attrs) for y in x]) # uniques = [] # for x in things[0]: # if all([x in y for y in things]): # uniques.append(x) # for y in things: # if x not in y: # print y # return uniques # def get_xpaths(soups): # res = prepare(soups, True, printText=False) # xpaths = get_xpath(res) # allnths = [] # for i in range(len(soups)): # nths = [] # for xpath, r in zip(xpaths, res[i]): # for num, y in enumerate(soups[i].findAll(xpath)): # if y == r[0]: # nths.append(num) # allnths.append(nths) # return allnths # verified = [] # for num, i in enumerate(allnths[0]): # if all([x[num] == i for x in allnths]): # verified.append(num) # verified_xpaths = [x for num,x in enumerate(xpaths) if num in verified] # nths = [x for num,x in enumerate(allnths[0]) if num in verified] # print len(xpaths), len(nths) # print verified_xpaths, nths # return [soups[0].findAll(x)[y] for x,y in zip(verified_xpaths, nths)] # test = get_xpaths(soups) # pinpoint(lxmls, 0) # lxmlTree(lxmls[0], namedAttrs=[]) # lxmlTree(res[0][1][0]) def textGather(soupChildren, sofar=None, level=0): if sofar is None: sofar = [] container = [] for x in soupChildren: if hasattr(x, "text"): sofar.append([x, x.text, level]) try: container.extend([y for y in x.children]) except: pass if container == []: return(sofar) return(textGather(container, sofar, level+1)) urls = ['http://www.nieuwsdumper.nl/nieuws', 'http://www.nieuwsdumper.nl/faq', 'http://www.nieuwsdumper.nl/contact', 'http://www.nieuwsdumper.nl/nieuws/1599/doosan-dl420-3-voor-de-rivierendriesprong-papendrecht-bv.html', 'http://www.nieuwsdumper.nl/nieuws/1596/takeuchi-cabrio-voor-van-der-kooij-maasland.html', 'http://www.nieuwsdumper.nl/nieuws/1588/de-vries-neemt-terex-tc35-in-gebruik.html'] htmls = [urllib.request.urlopen(url) for url in urls] soups = [BeautifulSoup(html) for html in htmls] def taglevels(soup): return [(x[0].name, x[2]) for x in textGather(soup)] def matchpercent(soup1, soup2, method): counted_items = {} for item in method(soup1): counted_items[item] = counted_items.get(item, 0) + 1 counted_items2 = {} for item in method(soup2): counted_items2[item] = counted_items2.get(item, 0) + 1 total = sum(counted_items.values()) + sum(counted_items2.values()) matched = 0 for x in counted_items: if x in counted_items2: matched += counted_items[x] for x in counted_items2: if x in counted_items2: matched += counted_items2[x] return matched, total, matched/total def keyattr_levels(soup): combined = [] for x in textGather(soup): for y in x[0].attrs: combined.append((y, x[2])) return combined def attr_levels(soup): combined = [] for x in textGather(soup): for y in x[0].attrs: combined.append((y, x[0].attrs[y], x[2])) return combined attr_levels(soups[0]) res = [] for x in soups: tmp = [] for y in soups: tmp.append(round(matchpercent(x,y,keyattr_levels)[2],3)) res.append(tmp) res = np.array(res) res2 = [] for x in soups: tmp = [] for y in soups: tmp.append(round(matchpercent(x,y,taglevels)[2],3)) res2.append(tmp) res3 = [] for x in soups: tmp = [] for y in soups: tmp.append(round(matchpercent(x,y,attr_levels)[2],3)) res3.append(tmp) res3 = np.array(res3) np.round(hmean((res,res2,res3)),2) filenames = [] for root, dirs, files in os.walk('/Users/pascal/bert-google-places-cache/webpage/', topdown=False): for name in files: filenames.append(os.path.join(root, name)) filenames = [x for x in filenames if '.nl' in x] from sklearn.cluster import SpectralClustering as sc sc(3,affinity='precomputed').fit_predict(hmean((res,res2,res3)))
bsd-3-clause
8,000,339,173,575,418,000
30.330769
116
0.528767
false
freeslugs/eventum
app/routes/admin/auth.py
1
8194
""" .. module:: auth :synopsis: All routes on the ``auth`` Blueprint. .. moduleauthor:: Dan Schlosser <[email protected]> """ import string import random import httplib2 from app import app from app.lib.networking import json_response from app.models import User, Whitelist from app.forms import CreateProfileForm from apiclient.discovery import build from flask import Blueprint, render_template, request, \ flash, session, g, redirect, url_for from oauth2client.client import (FlowExchangeError, flow_from_clientsecrets, AccessTokenCredentials) auth = Blueprint('auth', __name__) gplus_service = build('plus', 'v1') @auth.route('/login', methods=['GET']) def login(): """If the user is not logged in, display an option to log in. On click, make a request to Google to authenticate. If they are logged in, redirect. **Route:** ``/admin/login`` **Methods:** ``GET`` """ if g.user is not None and 'gplus_id' in session: # use code=303 to avoid POSTing to the next page. return redirect(url_for('admin.index'), code=303) load_csrf_token_into_session() args_next = request.args.get('next') next = args_next if args_next else request.url_root return render_template('admin/auth/login.html', client_id=app.config["GOOGLE_CLIENT_ID"], state=session['state'], # reauthorize=True, next=next) WHITELIST_CODE = 1 @auth.route('/store-token', methods=['POST']) def store_token(): """Do the oauth flow for Google plus sign in, storing the access token in the session, and redircting to create an account if appropriate. Because this method will be called from a ``$.ajax()`` request in JavaScript, we can't return ``redirect()``, so instead this method returns the URL that the user should be redirected to, and the redirect happens in html: .. code:: javascript success: function(response) { window.location.href = response; } **Route:** ``/admin/store-token`` **Methods:** ``POST`` """ if request.args.get('state', '') != session.get('state'): return json_response('Invalid state parameter.', 401) del session['state'] code = request.data try: # Upgrade the authorization code into a credentials object oauth_flow = flow_from_clientsecrets( 'config/client_secrets.json', scope='') oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError: return json_response('Failed to upgrade the authorization code.', 401) gplus_id = credentials.id_token['sub'] # Store the access token in the session for later use. session['credentials'] = credentials.access_token session['gplus_id'] = gplus_id if User.objects(gplus_id=gplus_id).count() == 0: # A new user model must be made # Get the user's name and email to populate the form http = httplib2.Http() http = credentials.authorize(http) people_document = gplus_service.people().get( userId='me').execute(http=http) # The user must be whitelisted in order to create an account. email = people_document['emails'][0]['value'] if Whitelist.objects(email=email).count() != 1: return json_response({ 'code': WHITELIST_CODE, 'title': 'User has not been whitelisted.', 'email': email }, 401) return json_response(url_for( '.create_profile', next=request.args.get('next'), name=people_document['displayName'], email=email, image_url=people_document['image']['url']), 200) user = User.objects().get(gplus_id=gplus_id) user.register_login() user.save() # The user already exists. Redirect to the next url or # the root of the application ('/') if request.args.get('next'): return json_response(request.args.get('next'), 200) return json_response(request.url_root, 200) @auth.route('/create-profile', methods=['GET', 'POST']) def create_profile(): """Create a profile (filling in the form with openid data), and register it in the database. **Route:** ``/admin/create-profile`` **Methods:** ``GET, POST`` """ if g.user is not None and 'gplus_id' in session: # use code=303 to avoid POSTing to the next page. return redirect(url_for('admin.index'), code=303) form = CreateProfileForm(request.form, name=request.args['name'], email=request.args['email'], next=request.args['next']) if form.validate_on_submit(): if User.objects(email=form.email.data).count() != 0: # A user with this email already exists. Override it. user = User.objects.get(email=form.email.data) user.openid = session['openid'] user.name = form.name.data flash('Account with this email already exists. Overridden.') user.register_login() user.save() else: # Retreive their user type from the whitelist then remove them. wl = Whitelist.objects().get(email=form.email.data) user_type = wl.user_type wl.redeemed = True wl.save() # Create a brand new user user = User(email=form.email.data, name=form.name.data, gplus_id=session['gplus_id'], user_type=user_type, image_url=request.args.get('image_url')) flash('Account created successfully.') user.register_login() user.save() # redirect to the next url or the root of the application ('/') if form.next.data: # use code=303 to avoid POSTing to the next page. return redirect(form.next.data, code=303) # use code=303 to avoid POSTing to the next page. return redirect('/', code=303) return render_template('admin/auth/create_profile.html', image_url=request.args.get('image_url'), form=form) @auth.route('/logout', methods=['GET']) def logout(): """Logs out the current user. **Route:** ``/admin/logout`` **Methods:** ``GET`` """ session.pop('gplus_id', None) g.user = None return redirect(url_for('client.index')) def load_csrf_token_into_session(): """Create a unique session cross-site request forgery (CSRF) token and load it into the session for later verification. """ state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32)) session['state'] = state @auth.route('/disconnect', methods=['GET', 'POST']) def disconnect(): """Revoke current user's token and reset their session. **Route:** ``/admin/disconnect`` **Methods:** ``GET, POST`` """ # Only disconnect a connected user. credentials = AccessTokenCredentials( session.get('credentials'), request.headers.get('User-Agent')) if credentials is None: return json_response('Current user not connected.', 401) # Execute HTTP GET request to revoke current token. access_token = credentials.access_token url = ('https://accounts.google.com/o/oauth2/revoke?token={}' .format(str(access_token))) h = httplib2.Http() result = h.request(url, 'GET')[0] session.pop('gplus_id', None) g.user = None if result['status'] == '200': # Reset the user's session. del session['credentials'] # use code=303 to avoid POSTing to the next page. return redirect(url_for('.login'), code=303) else: # For whatever reason, the given token was invalid. return json_response('Failed to revoke token for given user.', 400)
mit
264,916,467,931,780,160
33.57384
78
0.594703
false
ricardodeazambuja/BrianConnectUDP
examples/InputNeuronGroup_multiple_inputs_2.py
1
1910
''' Example of a spike generator (only outputs spikes) In this example spikes are generated and sent through UDP packages. At the end of the simulation a raster plot of the spikes is created. ''' from brian import * import numpy from brian_multiprocess_udp import BrianConnectUDP number_of_neurons_total = 60 number_of_neurons_spiking = 30 def main_NeuronGroup(input_Neuron_Group, simulation_clock): print "main_NeuronGroup!" #DEBUG! simclock = simulation_clock delta_t=5 random_list=numpy.random.randint(number_of_neurons_total,size=number_of_neurons_spiking) random_list.sort() spiketimes = [(i, delta_t*ms) for i in random_list] SpikesOut = SpikeGeneratorGroup(number_of_neurons_total, spiketimes, period=300*ms, clock=simclock) # the maximum clock of the input spikes is limited here (period) MSpkOut=SpikeMonitor(SpikesOut) # Spikes sent by UDP return ([SpikesOut],[],[MSpkOut]) def post_simulation_function(input_NG, simulation_NG, simulation_SYN, simulation_MN): """ input_NG: the neuron group that receives the input spikes simulation_NG: the neuron groups list passed to the system by the user function (main_NeuronGroup) simulation_SYN: the synapses list passed to the system by the user function (main_NeuronGroup) simulation_MN: the monitors list passed to the system by the user function (main_NeuronGroup) This way it is possible to plot, save or do whatever you want with these objects after the end of the simulation! """ figure() raster_plot(simulation_MN[0]) title("Spikes Sent by UDP") show(block=True) if __name__=="__main__": my_simulation = BrianConnectUDP(main_NeuronGroup, NumOfNeuronsOutput=number_of_neurons_total, post_simulation_function=post_simulation_function, output_addresses=[("127.0.0.1", 16161)], simclock_dt=5, TotalSimulationTime=10000, brian_address=0)
cc0-1.0
6,487,044,346,386,210,000
35.730769
168
0.733508
false
jaredly/pyjamas
library/pyjamas/dnd/DragHandlerAdapter.py
1
1031
""" * Copyright 2007 Fred Sauer * * 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. """ """* * Convenience class for anonymous inner classes not wishing to define all * methods required by the {@link DragHandler} interface. """ class DragHandlerAdapter implements DragHandler: def onDragEnd(self, event): def onDragStart(self, event): void onPreviewDragEnd(DragEndEvent event) throws VetoDragException { void onPreviewDragStart(DragStartEvent event) throws VetoDragException {
apache-2.0
-1,788,174,401,895,654,700
26.864865
79
0.732299
false
our-city-app/oca-backend
src/solutions/common/migrations/update_city_app_locations.py
1
1337
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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. # # @@license_version:1.7@@ from solutions.common.models.news import CityAppLocations, Street from rogerthat.bizz.job import run_job def job(): run_job(list_city_app_locations, [], update_city_app_location, []) def list_city_app_locations(): return CityAppLocations.query() def update_city_app_location(location_key): # Remove duplicate streets location = location_key.get() for locality in location.localities: street_tuples = {(street.name, street.id) for street in locality.streets} locality.streets = [Street(name=street_name, id=street_id) for (street_name, street_id) in sorted(street_tuples, key=lambda (name, _): name.upper())] location.put()
apache-2.0
685,562,577,361,089,500
35.135135
118
0.712042
false
mifit/miexpert
mi_convertlib_ui.py
1
2010
import sys, os, os.path, getopt, subprocess, pickle from PyQt4 import QtCore, QtGui, uic def Usage(): print "Usage: %s [options]" % sys.argv[0] print "Options are:" print " -w, --workdir=DIR working dir to use" print " -r, --refprogram=PROG shelx (default), cns, or cnx" print "" print " -?, --help for this help message" print "" def start(): config = {} settings = QtCore.QSettings("MIFit", "MIExpert") appSettings = settings.value("convertlib").toString() if not appSettings.isEmpty(): config = pickle.loads(str(appSettings)) if config.has_key('workdir'): workingdir = config['workdir'] else: workingdir = os.getcwd() refprogram = None optlist, args = getopt.getopt(sys.argv[1:], 'r:?', [ 'refprogram=', 'help' ]) for opt in optlist: arg = opt[0] if arg == '-?' or arg == '--help': Usage() exit(-1) elif arg == '-r' or arg =='--refprogram': refprogram = opt[1] if refprogram is None: print "--refprogram must be specified" Usage() exit(-1) filename = QtGui.QFileDialog.getOpenFileName(None, "Choose a CIF file", workingdir, "CIF Files (*.cif);;All files (*.*)"); dir = QtCore.QDir.toNativeSeparators(QtCore.QFileInfo(filename).absolutePath()) filename = QtCore.QDir.toNativeSeparators(filename) config['workdir'] = str(dir) settings.setValue("convertlib", pickle.dumps(config)) miexpert = os.path.join(os.path.dirname(sys.argv[0]), "MIExpert.py") convertArgs = [ sys.executable, miexpert, "convertlib" ] convertArgs += [ "--workdir=" + str(dir) ] convertArgs += [ "--refprogram=" + refprogram ] convertArgs += [ "--cif=" + str(filename) ] result = subprocess.call(convertArgs) exit(result) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) QtCore.QTimer.singleShot(500, start), sys.exit(app.exec_())
gpl-3.0
1,804,050,816,562,054,400
30.904762
83
0.591542
false
SacNaturalFoods/django-pm
helpdesk/migrations/0004_auto__add_timeentry__add_field_ticket_estimate.py
1
20252
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'TimeEntry' db.create_table('helpdesk_timeentry', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('date_start', self.gf('django.db.models.fields.DateTimeField')()), ('date_end', self.gf('django.db.models.fields.DateTimeField')()), ('ticket', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['helpdesk.Ticket'])), ('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), )) db.send_create_signal('helpdesk', ['TimeEntry']) # Adding field 'Ticket.estimate' db.add_column('helpdesk_ticket', 'estimate', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=5, decimal_places=2, blank=True), keep_default=False) def backwards(self, orm): # Deleting model 'TimeEntry' db.delete_table('helpdesk_timeentry') # Deleting field 'Ticket.estimate' db.delete_column('helpdesk_ticket', 'estimate') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'helpdesk.attachment': { 'Meta': {'ordering': "['filename']", 'object_name': 'Attachment'}, 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), 'filename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'followup': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.FollowUp']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'mime_type': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'size': ('django.db.models.fields.IntegerField', [], {}) }, 'helpdesk.customfield': { 'Meta': {'object_name': 'CustomField'}, 'data_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'decimal_places': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'empty_selection_list': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'help_text': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': "'30'"}), 'list_values': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'max_length': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'ordering': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'staff_only': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) }, 'helpdesk.emailtemplate': { 'Meta': {'ordering': "['template_name', 'locale']", 'object_name': 'EmailTemplate'}, 'heading': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'html': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'locale': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'plain_text': ('django.db.models.fields.TextField', [], {}), 'subject': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'template_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'helpdesk.escalationexclusion': { 'Meta': {'object_name': 'EscalationExclusion'}, 'date': ('django.db.models.fields.DateField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'queues': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['helpdesk.Queue']", 'null': 'True', 'blank': 'True'}) }, 'helpdesk.followup': { 'Meta': {'ordering': "['date']", 'object_name': 'FollowUp'}, 'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 7, 2, 0, 0)'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_status': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'ticket': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.Ticket']"}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'helpdesk.ignoreemail': { 'Meta': {'object_name': 'IgnoreEmail'}, 'date': ('django.db.models.fields.DateField', [], {'blank': 'True'}), 'email_address': ('django.db.models.fields.CharField', [], {'max_length': '150'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keep_in_mailbox': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'queues': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['helpdesk.Queue']", 'null': 'True', 'blank': 'True'}) }, 'helpdesk.kbcategory': { 'Meta': {'ordering': "['title']", 'object_name': 'KBCategory'}, 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'helpdesk.kbitem': { 'Meta': {'ordering': "['title']", 'object_name': 'KBItem'}, 'answer': ('django.db.models.fields.TextField', [], {}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.KBCategory']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'blank': 'True'}), 'question': ('django.db.models.fields.TextField', [], {}), 'recommendations': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'votes': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'helpdesk.milestone': { 'Meta': {'object_name': 'Milestone'}, 'due_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'queue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.Queue']"}) }, 'helpdesk.presetreply': { 'Meta': {'ordering': "['name']", 'object_name': 'PreSetReply'}, 'body': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'queues': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['helpdesk.Queue']", 'null': 'True', 'blank': 'True'}) }, 'helpdesk.queue': { 'Meta': {'ordering': "('title',)", 'object_name': 'Queue'}, 'allow_email_submission': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'allow_public_submission': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'email_address': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'email_box_host': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'email_box_imap_folder': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'email_box_interval': ('django.db.models.fields.IntegerField', [], {'default': "'5'", 'null': 'True', 'blank': 'True'}), 'email_box_last_check': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'email_box_pass': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'email_box_port': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'email_box_ssl': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'email_box_type': ('django.db.models.fields.CharField', [], {'max_length': '5', 'null': 'True', 'blank': 'True'}), 'email_box_user': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'escalate_days': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'locale': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'new_ticket_cc': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'updated_ticket_cc': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'helpdesk.savedsearch': { 'Meta': {'ordering': "['order']", 'object_name': 'SavedSearch'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'query': ('django.db.models.fields.TextField', [], {}), 'shared': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'sticky': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'helpdesk.ticket': { 'Meta': {'object_name': 'Ticket'}, 'assigned_to': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'assigned_to'", 'null': 'True', 'to': "orm['auth.User']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'due_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'estimate': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '5', 'decimal_places': '2', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_escalation': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'milestone': ('smart_selects.db_fields.ChainedForeignKey', [], {'to': "orm['helpdesk.Milestone']", 'null': 'True', 'blank': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'blank': 'True'}), 'on_hold': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'priority': ('django.db.models.fields.IntegerField', [], {'default': '3', 'blank': '3'}), 'queue': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.Queue']"}), 'resolution': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '1'}), 'submitter_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'tags': ('tagging_autocomplete_tagit.models.TagAutocompleteTagItField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'helpdesk.ticketcc': { 'Meta': {'object_name': 'TicketCC'}, 'can_update': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'can_view': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ticket': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.Ticket']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'helpdesk.ticketchange': { 'Meta': {'object_name': 'TicketChange'}, 'field': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'followup': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.FollowUp']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'old_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, 'helpdesk.ticketcustomfieldvalue': { 'Meta': {'unique_together': "(('ticket', 'field'),)", 'object_name': 'TicketCustomFieldValue'}, 'field': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.CustomField']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ticket': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.Ticket']"}), 'value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, 'helpdesk.ticketdependency': { 'Meta': {'unique_together': "(('ticket', 'depends_on'),)", 'object_name': 'TicketDependency'}, 'depends_on': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'depends_on'", 'to': "orm['helpdesk.Ticket']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ticket': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'ticketdependency'", 'to': "orm['helpdesk.Ticket']"}) }, 'helpdesk.timeentry': { 'Meta': {'object_name': 'TimeEntry'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_end': ('django.db.models.fields.DateTimeField', [], {}), 'date_start': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ticket': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['helpdesk.Ticket']"}) }, 'helpdesk.usersettings': { 'Meta': {'object_name': 'UserSettings'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'settings_pickled': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) } } complete_apps = ['helpdesk']
agpl-3.0
-5,653,047,034,389,954,000
75.139098
182
0.543946
false
cjayb/mne-python
mne/utils/mixin.py
1
18553
# -*- coding: utf-8 -*- """Some utility functions.""" # Authors: Alexandre Gramfort <[email protected]> # # License: BSD (3-clause) from collections import OrderedDict from copy import deepcopy import logging import json import numpy as np from .check import _check_pandas_installed, _check_preload, _validate_type from ._logging import warn, verbose from .numerics import object_size, object_hash logger = logging.getLogger('mne') # one selection here used across mne-python logger.propagate = False # don't propagate (in case of multiple imports) class SizeMixin(object): """Estimate MNE object sizes.""" def __eq__(self, other): """Compare self to other. Parameters ---------- other : object The object to compare to. Returns ------- eq : bool True if the two objects are equal. """ return isinstance(other, type(self)) and hash(self) == hash(other) @property def _size(self): """Estimate the object size.""" try: size = object_size(self.info) except Exception: warn('Could not get size for self.info') return -1 if hasattr(self, 'data'): size += object_size(self.data) elif hasattr(self, '_data'): size += object_size(self._data) return size def __hash__(self): """Hash the object. Returns ------- hash : int The hash """ from ..evoked import Evoked from ..epochs import BaseEpochs from ..io.base import BaseRaw if isinstance(self, Evoked): return object_hash(dict(info=self.info, data=self.data)) elif isinstance(self, (BaseEpochs, BaseRaw)): _check_preload(self, "Hashing ") return object_hash(dict(info=self.info, data=self._data)) else: raise RuntimeError('Hashing unknown object type: %s' % type(self)) class GetEpochsMixin(object): """Class to add epoch selection and metadata to certain classes.""" def __getitem__(self, item): """Return an Epochs object with a copied subset of epochs. Parameters ---------- item : slice, array-like, str, or list See below for use cases. Returns ------- epochs : instance of Epochs See below for use cases. Notes ----- Epochs can be accessed as ``epochs[...]`` in several ways: 1. ``epochs[idx]``: Return ``Epochs`` object with a subset of epochs (supports single index and python-style slicing). 2. ``epochs['name']``: Return ``Epochs`` object with a copy of the subset of epochs corresponding to an experimental condition as specified by 'name'. If conditions are tagged by names separated by '/' (e.g. 'audio/left', 'audio/right'), and 'name' is not in itself an event key, this selects every event whose condition contains the 'name' tag (e.g., 'left' matches 'audio/left' and 'visual/left'; but not 'audio_left'). Note that tags selection is insensitive to order: tags like 'auditory/left' and 'left/auditory' will be treated the same way when accessed. 3. ``epochs[['name_1', 'name_2', ... ]]``: Return ``Epochs`` object with a copy of the subset of epochs corresponding to multiple experimental conditions as specified by ``'name_1', 'name_2', ...`` . If conditions are separated by '/', selects every item containing every list tag (e.g. ['audio', 'left'] selects 'audio/left' and 'audio/center/left', but not 'audio/right'). 4. ``epochs['pandas query']``: Return ``Epochs`` object with a copy of the subset of epochs (and matching metadata) that match ``pandas query`` called with ``self.metadata.eval``, e.g.:: epochs["col_a > 2 and col_b == 'foo'"] This is only called if Pandas is installed and ``self.metadata`` is a :class:`pandas.DataFrame`. .. versionadded:: 0.16 """ return self._getitem(item) def _item_to_select(self, item): if isinstance(item, str): item = [item] # Convert string to indices if isinstance(item, (list, tuple)) and len(item) > 0 and \ isinstance(item[0], str): select = self._keys_to_idx(item) elif isinstance(item, slice): select = item else: select = np.atleast_1d(item) if len(select) == 0: select = np.array([], int) return select def _getitem(self, item, reason='IGNORED', copy=True, drop_event_id=True, select_data=True, return_indices=False): """ Select epochs from current object. Parameters ---------- item: slice, array-like, str, or list see `__getitem__` for details. reason: str entry in `drop_log` for unselected epochs copy: bool return a copy of the current object drop_event_id: bool remove non-existing event-ids after selection select_data: bool apply selection to data (use `select_data=False` if subclasses do not have a valid `_data` field, or data has already been subselected) return_indices: bool return the indices of selected epochs from the original object in addition to the new `Epochs` objects Returns ------- `Epochs` or tuple(Epochs, np.ndarray) if `return_indices` is True subset of epochs (and optionally array with kept epoch indices) """ data = self._data del self._data inst = self.copy() if copy else self self._data = inst._data = data del self select = inst._item_to_select(item) has_selection = hasattr(inst, 'selection') if has_selection: key_selection = inst.selection[select] drop_log = list(inst.drop_log) if reason is not None: for k in np.setdiff1d(inst.selection, key_selection): drop_log[k] = (reason,) inst.drop_log = tuple(drop_log) inst.selection = key_selection del drop_log inst.events = np.atleast_2d(inst.events[select]) if inst.metadata is not None: pd = _check_pandas_installed(strict=False) if pd: metadata = inst.metadata.iloc[select] if has_selection: metadata.index = inst.selection else: metadata = np.array(inst.metadata, 'object')[select].tolist() # will reset the index for us GetEpochsMixin.metadata.fset(inst, metadata, verbose=False) if inst.preload and select_data: # ensure that each Epochs instance owns its own data so we can # resize later if necessary inst._data = np.require(inst._data[select], requirements=['O']) if drop_event_id: # update event id to reflect new content of inst inst.event_id = {k: v for k, v in inst.event_id.items() if v in inst.events[:, 2]} if return_indices: return inst, select else: return inst def _keys_to_idx(self, keys): """Find entries in event dict.""" keys = keys if isinstance(keys, (list, tuple)) else [keys] try: # Assume it's a condition name return np.where(np.any( np.array([self.events[:, 2] == self.event_id[k] for k in _hid_match(self.event_id, keys)]), axis=0))[0] except KeyError as err: # Could we in principle use metadata with these Epochs and keys? if (len(keys) != 1 or self.metadata is None): # If not, raise original error raise msg = str(err.args[0]) # message for KeyError pd = _check_pandas_installed(strict=False) # See if the query can be done if pd: md = self.metadata if hasattr(self, '_metadata') else None self._check_metadata(metadata=md) try: # Try metadata mask = self.metadata.eval(keys[0], engine='python').values except Exception as exp: msg += (' The epochs.metadata Pandas query did not ' 'yield any results: %s' % (exp.args[0],)) else: return np.where(mask)[0] else: # If not, warn this might be a problem msg += (' The epochs.metadata Pandas query could not ' 'be performed, consider installing Pandas.') raise KeyError(msg) def __len__(self): """Return the number of epochs. Returns ------- n_epochs : int The number of remaining epochs. Notes ----- This function only works if bad epochs have been dropped. Examples -------- This can be used as:: >>> epochs.drop_bad() # doctest: +SKIP >>> len(epochs) # doctest: +SKIP 43 >>> len(epochs.events) # doctest: +SKIP 43 """ from ..epochs import BaseEpochs if isinstance(self, BaseEpochs) and not self._bad_dropped: raise RuntimeError('Since bad epochs have not been dropped, the ' 'length of the Epochs is not known. Load the ' 'Epochs with preload=True, or call ' 'Epochs.drop_bad(). To find the number ' 'of events in the Epochs, use ' 'len(Epochs.events).') return len(self.events) def __iter__(self): """Facilitate iteration over epochs. This method resets the object iteration state to the first epoch. Notes ----- This enables the use of this Python pattern:: >>> for epoch in epochs: # doctest: +SKIP >>> print(epoch) # doctest: +SKIP Where ``epoch`` is given by successive outputs of :meth:`mne.Epochs.next`. """ self._current = 0 return self def __next__(self, return_event_id=False): """Iterate over epoch data. Parameters ---------- return_event_id : bool If True, return both the epoch data and an event_id. Returns ------- epoch : array of shape (n_channels, n_times) The epoch data. event_id : int The event id. Only returned if ``return_event_id`` is ``True``. """ if self.preload: if self._current >= len(self._data): raise StopIteration # signal the end epoch = self._data[self._current] self._current += 1 else: is_good = False while not is_good: if self._current >= len(self.events): raise StopIteration # signal the end properly epoch_noproj = self._get_epoch_from_raw(self._current) epoch_noproj = self._detrend_offset_decim(epoch_noproj) epoch = self._project_epoch(epoch_noproj) self._current += 1 is_good, _ = self._is_good_epoch(epoch) # If delayed-ssp mode, pass 'virgin' data after rejection decision. if self._do_delayed_proj: epoch = epoch_noproj if not return_event_id: return epoch else: return epoch, self.events[self._current - 1][-1] next = __next__ # originally for Python2, now b/c public def _check_metadata(self, metadata=None, reset_index=False): """Check metadata consistency.""" # reset_index=False will not copy! if metadata is None: return else: pd = _check_pandas_installed(strict=False) if pd: _validate_type(metadata, types=pd.DataFrame, item_name='metadata') if len(metadata) != len(self.events): raise ValueError('metadata must have the same number of ' 'rows (%d) as events (%d)' % (len(metadata), len(self.events))) if reset_index: if hasattr(self, 'selection'): # makes a copy metadata = metadata.reset_index(drop=True) metadata.index = self.selection else: metadata = deepcopy(metadata) else: _validate_type(metadata, types=list, item_name='metadata') if reset_index: metadata = deepcopy(metadata) return metadata @property def metadata(self): """Get the metadata.""" return self._metadata @metadata.setter @verbose def metadata(self, metadata, verbose=None): metadata = self._check_metadata(metadata, reset_index=True) if metadata is not None: if _check_pandas_installed(strict=False): n_col = metadata.shape[1] else: n_col = len(metadata[0]) n_col = ' with %d columns' % n_col else: n_col = '' if hasattr(self, '_metadata') and self._metadata is not None: action = 'Removing' if metadata is None else 'Replacing' action += ' existing' else: action = 'Not setting' if metadata is None else 'Adding' logger.info('%s metadata%s' % (action, n_col)) self._metadata = metadata def _prepare_write_metadata(metadata): """Convert metadata to JSON for saving.""" if metadata is not None: if not isinstance(metadata, list): metadata = metadata.to_json(orient='records') else: # Pandas DataFrame metadata = json.dumps(metadata) assert isinstance(metadata, str) return metadata def _prepare_read_metadata(metadata): """Convert saved metadata back from JSON.""" if metadata is not None: pd = _check_pandas_installed(strict=False) # use json.loads because this preserves ordering # (which is necessary for round-trip equivalence) metadata = json.loads(metadata, object_pairs_hook=OrderedDict) assert isinstance(metadata, list) if pd: metadata = pd.DataFrame.from_records(metadata) assert isinstance(metadata, pd.DataFrame) return metadata def _hid_match(event_id, keys): """Match event IDs using HID selection. Parameters ---------- event_id : dict The event ID dictionary. keys : list | str The event ID or subset (for HID), or list of such items. Returns ------- use_keys : list The full keys that fit the selection criteria. """ # form the hierarchical event ID mapping use_keys = [] for key in keys: if not isinstance(key, str): raise KeyError('keys must be strings, got %s (%s)' % (type(key), key)) use_keys.extend(k for k in event_id.keys() if set(key.split('/')).issubset(k.split('/'))) if len(use_keys) == 0: raise KeyError('Event "{}" is not in Epochs. Event_ids must be one of ' '"{}"'.format(key, ', '.join(event_id.keys()))) use_keys = list(set(use_keys)) # deduplicate if necessary return use_keys class _FakeNoPandas(object): # noqa: D101 def __enter__(self): # noqa: D105 def _check(strict=True): if strict: raise RuntimeError('Pandas not installed') else: return False import mne self._old_check = _check_pandas_installed mne.epochs._check_pandas_installed = _check mne.utils.mixin._check_pandas_installed = _check def __exit__(self, *args): # noqa: D105 import mne mne.epochs._check_pandas_installed = self._old_check mne.utils.mixin._check_pandas_installed = self._old_check class ShiftTimeMixin(object): """Class for shift_time method (Epochs, Evoked, and DipoleFixed).""" def shift_time(self, tshift, relative=True): """Shift time scale in epoched or evoked data. Parameters ---------- tshift : float The (absolute or relative) time shift in seconds. If ``relative`` is True, positive tshift increases the time value associated with each sample, while negative tshift decreases it. relative : bool If True, increase or decrease time values by ``tshift`` seconds. Otherwise, shift the time values such that the time of the first sample equals ``tshift``. Returns ------- epochs : instance of Epochs The modified Epochs instance. Notes ----- This method allows you to shift the *time* values associated with each data sample by an arbitrary amount. It does *not* resample the signal or change the *data* values in any way. """ from ..epochs import BaseEpochs _check_preload(self, 'shift_time') start = tshift + (self.times[0] if relative else 0.) new_times = start + np.arange(len(self.times)) / self.info['sfreq'] if isinstance(self, BaseEpochs): self._set_times(new_times) else: self.times = new_times self._update_first_last() return self def _update_first_last(self): """Update self.first and self.last (sample indices).""" self.first = int(round(self.times[0] * self.info['sfreq'])) self.last = len(self.times) + self.first - 1
bsd-3-clause
-6,368,250,695,348,627,000
34.955426
79
0.541745
false
mytestcoin/mytestcoin
contrib/devtools/update-translations.py
1
6859
#!/usr/bin/python # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Run this script from the root of the repository to update all translations from transifex. It will do the following automatically: - fetch all translations using the tx tool - post-process them into valid and committable format - remove invalid control characters - remove location tags (makes diffs less noisy) TODO: - auto-add new translations to the build system according to the translation process ''' from __future__ import division, print_function import subprocess import re import sys import os import io import xml.etree.ElementTree as ET # Name of transifex tool TX = 'tx' # Name of source language file SOURCE_LANG = 'dash_en.ts' # Directory with locale files LOCALE_DIR = 'src/qt/locale' def check_at_repository_root(): if not os.path.exists('.git'): print('No .git directory found') print('Execute this script at the root of the repository', file=sys.stderr) exit(1) def fetch_all_translations(): if subprocess.call([TX, 'pull', '-f']): print('Error while fetching translations', file=sys.stderr) exit(1) def find_format_specifiers(s): '''Find all format specifiers in a string.''' pos = 0 specifiers = [] while True: percent = s.find('%', pos) if percent < 0: break try: specifiers.append(s[percent+1]) except: print('Failed to get specifier') pos = percent+2 return specifiers def split_format_specifiers(specifiers): '''Split format specifiers between numeric (Qt) and others (strprintf)''' numeric = [] other = [] for s in specifiers: if s in {'1','2','3','4','5','6','7','8','9'}: numeric.append(s) else: other.append(s) # numeric (Qt) can be present in any order, others (strprintf) must be in specified order return set(numeric),other def sanitize_string(s): '''Sanitize string for printing''' return s.replace('\n',' ') def check_format_specifiers(source, translation, errors): source_f = split_format_specifiers(find_format_specifiers(source)) # assert that no source messages contain both Qt and strprintf format specifiers # if this fails, go change the source as this is hacky and confusing! #assert(not(source_f[0] and source_f[1])) try: translation_f = split_format_specifiers(find_format_specifiers(translation)) except IndexError: errors.append("Parse error in translation '%s'" % sanitize_string(translation)) return False else: if source_f != translation_f: errors.append("Mismatch between '%s' and '%s'" % (sanitize_string(source), sanitize_string(translation))) return False return True def all_ts_files(suffix=''): for filename in os.listdir(LOCALE_DIR): # process only language files, and do not process source language if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix: continue if suffix: # remove provided suffix filename = filename[0:-len(suffix)] filepath = os.path.join(LOCALE_DIR, filename) yield(filename, filepath) FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]') def remove_invalid_characters(s): '''Remove invalid characters from translation string''' return FIX_RE.sub(b'', s) # Override cdata escape function to make our output match Qt's (optional, just for cleaner diffs for # comparison, disable by default) _orig_escape_cdata = None def escape_cdata(text): text = _orig_escape_cdata(text) text = text.replace("'", '&apos;') text = text.replace('"', '&quot;') return text def postprocess_translations(reduce_diff_hacks=False): print('Checking and postprocessing...') if reduce_diff_hacks: global _orig_escape_cdata _orig_escape_cdata = ET._escape_cdata ET._escape_cdata = escape_cdata for (filename,filepath) in all_ts_files(): os.rename(filepath, filepath+'.orig') have_errors = False for (filename,filepath) in all_ts_files('.orig'): # pre-fixups to cope with transifex output parser = ET.XMLParser(encoding='utf-8') # need to override encoding because 'utf8' is not understood only 'utf-8' with open(filepath + '.orig', 'rb') as f: data = f.read() # remove control characters; this must be done over the entire file otherwise the XML parser will fail data = remove_invalid_characters(data) tree = ET.parse(io.BytesIO(data), parser=parser) # iterate over all messages in file root = tree.getroot() for context in root.findall('context'): for message in context.findall('message'): numerus = message.get('numerus') == 'yes' source = message.find('source').text translation_node = message.find('translation') # pick all numerusforms if numerus: translations = [i.text for i in translation_node.findall('numerusform')] else: translations = [translation_node.text] for translation in translations: if translation is None: continue errors = [] valid = check_format_specifiers(source, translation, errors) for error in errors: print('%s: %s' % (filename, error)) if not valid: # set type to unfinished and clear string if invalid translation_node.clear() translation_node.set('type', 'unfinished') have_errors = True # Remove location tags for location in message.findall('location'): message.remove(location) # Remove entire message if it is an unfinished translation if translation_node.get('type') == 'unfinished': context.remove(message) # write fixed-up tree # if diff reduction requested, replace some XML to 'sanitize' to qt formatting if reduce_diff_hacks: out = io.BytesIO() tree.write(out, encoding='utf-8') out = out.getvalue() out = out.replace(b' />', b'/>') with open(filepath, 'wb') as f: f.write(out) else: tree.write(filepath, encoding='utf-8') return have_errors if __name__ == '__main__': check_at_repository_root() # fetch_all_translations() postprocess_translations()
mit
-4,654,621,701,439,158,000
35.291005
121
0.616125
false
CarterBain/AlephNull
setup.py
1
2483
#!/usr/bin/env python # # Copyright 2013 Quantopian, Inc. # # 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 sys from setuptools import setup, find_packages LONG_DESCRIPTION = None README_MARKDOWN = None with open('README.md') as markdown_source: README_MARKDOWN = markdown_source.read() if 'upload' in sys.argv: # Converts the README.md file to ReST, since PyPI uses ReST for formatting, # This allows to have one canonical README file, being the README.md # The conversion only needs to be done on upload. # Otherwise, the pandoc import and errors that are thrown when # pandoc are both overhead and a source of confusion for general # usage/installation. import pandoc pandoc.core.PANDOC_PATH = 'pandoc' doc = pandoc.Document() doc.markdown = README_MARKDOWN LONG_DESCRIPTION = doc.rst else: # If pandoc isn't installed, e.g. when downloading from pip, # just use the regular README. LONG_DESCRIPTION = README_MARKDOWN setup( name='alephnull', version='0.5.11.dev', description='A backtester for financial algorithms.', author='Quantopian Inc.', author_email='[email protected]', packages=find_packages(), long_description=LONG_DESCRIPTION, license='Apache 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Operating System :: OS Independent', 'Intended Audience :: Science/Research', 'Topic :: Office/Business :: Financial', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: System :: Distributed Computing', ], install_requires=[ 'iso8601', 'Logbook', 'pytz', 'requests', 'numpy', 'pandas' ], url="https://github.com/quantopian/zipline" )
apache-2.0
5,700,843,569,520,440,000
33.013699
79
0.677406
false
stackforge/python-openstacksdk
openstack/tests/functional/cloud/test_cluster_templates.py
1
4186
# 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. """ test_cluster_templates ---------------------------------- Functional tests for `openstack.cloud` cluster_template methods. """ import fixtures from testtools import content from openstack.tests.functional import base import subprocess class TestClusterTemplate(base.BaseFunctionalTest): def setUp(self): super(TestClusterTemplate, self).setUp() if not self.user_cloud.has_service( 'container-infrastructure-management' ): self.skipTest('Container service not supported by cloud') self.ct = None self.ssh_directory = self.useFixture(fixtures.TempDir()).path def test_cluster_templates(self): '''Test cluster_templates functionality''' name = 'fake-cluster_template' server_type = 'vm' public = False image_id = 'fedora-atomic-f23-dib' tls_disabled = False registry_enabled = False coe = 'kubernetes' keypair_id = 'testkey' self.addDetail('cluster_template', content.text_content(name)) self.addCleanup(self.cleanup, name) # generate a keypair to add to nova subprocess.call( ['ssh-keygen', '-t', 'rsa', '-N', '', '-f', '%s/id_rsa_sdk' % self.ssh_directory]) # add keypair to nova with open('%s/id_rsa_sdk.pub' % self.ssh_directory) as f: key_content = f.read() self.user_cloud.create_keypair('testkey', key_content) # Test we can create a cluster_template and we get it returned self.ct = self.user_cloud.create_cluster_template( name=name, image_id=image_id, keypair_id=keypair_id, coe=coe) self.assertEqual(self.ct['name'], name) self.assertEqual(self.ct['image_id'], image_id) self.assertEqual(self.ct['keypair_id'], keypair_id) self.assertEqual(self.ct['coe'], coe) self.assertEqual(self.ct['registry_enabled'], registry_enabled) self.assertEqual(self.ct['tls_disabled'], tls_disabled) self.assertEqual(self.ct['public'], public) self.assertEqual(self.ct['server_type'], server_type) # Test that we can list cluster_templates cluster_templates = self.user_cloud.list_cluster_templates() self.assertIsNotNone(cluster_templates) # Test we get the same cluster_template with the # get_cluster_template method cluster_template_get = self.user_cloud.get_cluster_template( self.ct['uuid']) self.assertEqual(cluster_template_get['uuid'], self.ct['uuid']) # Test the get method also works by name cluster_template_get = self.user_cloud.get_cluster_template(name) self.assertEqual(cluster_template_get['name'], self.ct['name']) # Test we can update a field on the cluster_template and only that # field is updated cluster_template_update = self.user_cloud.update_cluster_template( self.ct['uuid'], 'replace', tls_disabled=True) self.assertEqual( cluster_template_update['uuid'], self.ct['uuid']) self.assertTrue(cluster_template_update['tls_disabled']) # Test we can delete and get True returned cluster_template_delete = self.user_cloud.delete_cluster_template( self.ct['uuid']) self.assertTrue(cluster_template_delete) def cleanup(self, name): if self.ct: try: self.user_cloud.delete_cluster_template(self.ct['name']) except Exception: pass # delete keypair self.user_cloud.delete_keypair('testkey')
apache-2.0
-4,948,767,063,280,651,000
36.711712
75
0.640229
false
moneta-project/moneta-2.0.1.0
qa/rpc-tests/getchaintips.py
1
2116
#!/usr/bin/env python2 # Copyright (c) 2014 The Moneta Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Exercise the getchaintips API. We introduce a network split, work # on chains of different lengths, and join the network together again. # This gives us two tips, verify that it works. from test_framework import MonetaTestFramework from util import assert_equal class GetChainTipsTest (MonetaTestFramework): def run_test (self): MonetaTestFramework.run_test (self) tips = self.nodes[0].getchaintips () assert_equal (len (tips), 1) assert_equal (tips[0]['branchlen'], 0) assert_equal (tips[0]['height'], 200) assert_equal (tips[0]['status'], 'active') # Split the network and build two chains of different lengths. self.split_network () self.nodes[0].setgenerate (True, 10); self.nodes[2].setgenerate (True, 20); self.sync_all () tips = self.nodes[1].getchaintips () assert_equal (len (tips), 1) shortTip = tips[0] assert_equal (shortTip['branchlen'], 0) assert_equal (shortTip['height'], 210) assert_equal (tips[0]['status'], 'active') tips = self.nodes[3].getchaintips () assert_equal (len (tips), 1) longTip = tips[0] assert_equal (longTip['branchlen'], 0) assert_equal (longTip['height'], 220) assert_equal (tips[0]['status'], 'active') # Join the network halves and check that we now have two tips # (at least at the nodes that previously had the short chain). self.join_network () tips = self.nodes[0].getchaintips () assert_equal (len (tips), 2) assert_equal (tips[0], longTip) assert_equal (tips[1]['branchlen'], 10) assert_equal (tips[1]['status'], 'valid-fork') tips[1]['branchlen'] = 0 tips[1]['status'] = 'active' assert_equal (tips[1], shortTip) if __name__ == '__main__': GetChainTipsTest ().main ()
mit
-7,049,970,723,906,635,000
34.864407
70
0.622873
false
marcsans/cf-cold-start
src/ALS.py
1
14546
""" Alternating Least Square with lambda weighted regularization Zhou et al both explicit and implicit version (of Koren) are implemented code can be run in parallel in local with setting parallel = True """ import numpy as np from multiprocessing import Pool from scipy.sparse import diags, csr_matrix from utils import sparse_matrix import pandas as pd from copy import deepcopy def linear_transfo(R,alpha,intercept=True): if intercept: return 1+alpha*R else: return alpha*R def log_transfo(R,alpha,eps,intercept=True): if intercept: return 1+alpha*np.log(1+R/eps) else: return alpha*np.log(1+R/eps) class ALS(object): """ Parameters ========== d : int Number of latent factors. num_users, num_items : int number of users and items to dimension the matrix. lbda : float Regularization constant. lbda2 : float Regularization constant for improved model (not available for implicit for now). num_iters : int Number of iterations of alternating least squares. parallel : bool Should update be done in parallel (in local) seed : int if not None, fix the random seed reg: string what sould be the regularisation ? - if "weighted" the regularisation is weighted by the number of non empty value in each row and column - if None or "default" it will be classic l2 norm verbose : bool Should it be verbose ? """ def __init__(self,d,num_users,num_items,userCol,itemCol,ratingCol, lbda=0.8,lbda2=0.8,num_iters=20, parallel=False,seed=None,reg="weighted",verbose=False): self.d = d self.num_users = num_users self.num_items = num_items self.userCol = userCol self.itemCol = itemCol self.ratingCol = ratingCol self.names = [userCol,itemCol,ratingCol] self.lbda = lbda self.lbda2 = lbda2 self.num_iters = num_iters self.parallel = parallel self.seed = seed self.reg = reg if self.reg is None: self.reg = "default" self.verbose = verbose def init_factors(self,num_factors,assign_values=True): if assign_values: return self.d**-0.5*np.random.random_sample((num_factors,self.d)) return np.empty((num_factors,self.d)) def fit(self,train,U0=None,V0=None,beta_V=None): """ Learn factors from training set. User and item factors are fitted alternately. Parameters ========== train : dict keys contain col, row and val for column index, row index and value. U0, V0 : array-like initialization of the decomposition. If None, initiate with random values """ if self.seed is not None: np.random.seed(self.seed) if beta_V is None: beta_V = np.ones(self.num_items) self.train = sparse_matrix(train,n = self.num_users, p = self.num_items,names=self.names) self.U = U0 self.V = V0 if self.U is None: #self.U = self.init_factors(self.num_users,False) self.U = np.random.normal(size=(self.num_users,self.d)) if self.V is None: #self.V = self.init_factors(self.num_items) self.V = np.random.normal(size=(self.num_items,self.d)) for it in np.arange(self.num_iters): if self.parallel: pool = Pool() res = [pool.apply_async(self.parallel_update, (u,self.train,True)) for u in range(self.num_users)] self.U = np.array([r.get() for r in res]) pool = Pool() res = [pool.apply_async(self.parallel_update, (i,self.train,False)) for i in range(self.num_items)] self.V = np.array([r.get() for r in res]) else: for u in range(self.num_users): indices = self.train[u].nonzero()[1] if indices.size: R_u = self.train[u,indices] self.U[u,:] = self.update(indices,self.V,R_u.toarray().T) else: self.U[u,:] = np.zeros(self.d) for i in range(self.num_items): indices = self.train[:,i].nonzero()[0] if indices.size: R_i = self.train[indices,i] self.V[i,:] = self.update(indices,self.U,R_i.toarray().T[0]) else: self.V[i,:] = np.zeros(self.d) if self.verbose: print('end iteration',it+1) def fitTransductive(self,train, trans, C1, C2, U0=None,V0=None,beta_V=None): """ Learn factors from training set and transductive training set. User and item factors are fitted alternately. Parameters ========== train : dict keys contain col, row and val for column index, row index and value. trans : dict keys contain col, row and val for column index, row index and value. U0, V0 : array-like initialization of the decomposition. If None, initiate with random values """ if self.seed is not None: np.random.seed(self.seed) if beta_V is None: beta_V = np.ones(self.num_items) self.train = sparse_matrix(train,n = self.num_users, p = self.num_items,names=self.names) trans_mat = csr_matrix(trans) self.U = U0 self.V = V0 if self.U is None: #self.U = self.init_factors(self.num_users,False) self.U = np.random.normal(size=(self.num_users,self.d)) if self.V is None: #self.V = self.init_factors(self.num_items) self.V = np.random.normal(size=(self.num_items,self.d)) for it in np.arange(self.num_iters): for u in range(self.num_users): indices = self.train[u].nonzero()[1] indicesTrans = trans_mat[u].nonzero()[1] if indices.size: R_u = self.train[u,indices] R_uTrans = trans_mat[u,indicesTrans] self.U[u,:] = self.updateTransductive(indices, indicesTrans, C1, C2, self.V,R_u.toarray().T,R_uTrans.toarray().T) else: self.U[u,:] = np.zeros(self.d) for i in range(self.num_items): indices = self.train[:,i].nonzero()[0] indicesTrans = trans_mat[:,i].nonzero()[0] if indices.size: R_i = self.train[indices,i] R_iTrans = trans_mat[indicesTrans,i] self.V[i,:] = self.updateTransductive(indices, indicesTrans, C1, C2, self.U,R_i.toarray().T[0],R_iTrans.toarray().T[0]) else: self.V[i,:] = np.zeros(self.d) if self.verbose: print('end iteration',it+1) def updateTransductive(self,indices,indicesTrans, C1, C2, H,R,RTrans): """ Update latent factors for a single user or item. """ Hix = H[indices,:] HixTrans = H[indicesTrans,:] HH = Hix.T.dot(Hix) HHTrans = HixTrans.T.dot(HixTrans) M = C1 * HH + C2 * HHTrans + np.diag(self.lbda*len(R)*np.ones(self.d)) return np.linalg.solve(M,C1*Hix.T.dot(R)+C2*HixTrans.T.dot(RTrans)).reshape(self.d) def linear_transfo(self,R,intercept=True): if intercept: return 1+self.alpha*R else: return self.alpha*R def log_transfo(self,R,intercept=True): if intercept: return 1+self.alpha*np.log(1+R/self.eps) else: return self.alpha*np.log(1+R/self.eps) def fitImplicit(self,train,alpha=10.,c="linear",eps=1E-8,U0=None,V0=None): """ Learn factors from training set with the implicit formula of Koren "Collaborative Filtering for Implicit Feedback Datasets" User and item factors are fitted alternately. Parameters ========== train : dict keys contain col, row and val for column index, row index and value. alpha : float Confidence weight, confidence c = 1 + alpha*r where r is the observed "rating". c : string if c="linear", C = 1 + alpha*R if c="log", C = 1 + alpha*log(1 + R/eps) eps : float used only if c="log" U0, V0 : array-like initialization of the decomposition. If None, initiate with random values """ if self.seed is not None: np.random.seed(self.seed) # we define a global fonction transfo that is either linear_transfo # or log_transfo. This prevent to make the if else check for each # user and for each item at each iteration ! if c=="linear": self.transfo = self.linear_transfo elif c=="log": self.transfo = self.log_transfo self.alpha = alpha self.c = c self.eps = eps self.train = sparse_matrix(train,n = self.num_users, p = self.num_items,names=self.names) self.U = U0 self.V = V0 if self.U is None: #self.U = self.init_factors(self.num_users,False) self.U = np.random.normal(size=(self.num_users,self.d)) if self.V is None: #self.V = self.init_factors(self.num_items) self.V = np.random.normal(size=(self.num_items,self.d)) for it in np.arange(self.num_iters): if self.parallel: VV = self.V.T.dot(self.V) pool = Pool() res = [pool.apply_async(self.parallel_implicit_update, (u,VV,self.train,True)) for u in range(self.num_users)] self.U = np.array([r.get() for r in res]) UU = self.U.T.dot(self.U) pool = Pool() res = [pool.apply_async(self.parallel_implicit_update, (i,UU,self.train,False)) for i in range(self.num_items)] self.V = np.array([r.get() for r in res]) else: VV = self.V.T.dot(self.V) for u in range(self.num_users): # get (positive i.e. non-zero scored) items for user indices = self.train[u].nonzero()[1] if indices.size: R_u = self.train[u,indices] self.U[u,:] = self.implicit_update(indices,self.V,VV,R_u.toarray()[0]) else: self.U[u,:] = np.zeros(self.d) UU = self.U.T.dot(self.U) for i in range(self.num_items): indices = self.train[:,i].nonzero()[0] if indices.size: R_i = self.train[indices,i] self.V[i,:] = self.implicit_update(indices,self.U,UU,R_i.toarray().T[0]) else: self.V[i,:] = np.zeros(self.d) if self.verbose: print('end iteration',it+1) def parallel_update(self,ind,train,user=True): """ Update latent factors for a single user or item applied in parallel """ if user: indices = train[ind].nonzero()[1] Hix = self.V[indices,:] R_u = train[ind,indices] R = R_u.toarray().T else: indices = train[:,ind].nonzero()[0] Hix = self.U[indices,:] R_i = train[indices,ind] R = R_i.toarray().T[0] if len(indices)>0: HH = Hix.T.dot(Hix) if self.reg=="weighted": M = HH + np.diag(self.lbda*len(R)*np.ones(self.d)) elif self.reg=="default": M = HH + np.diag(self.lbda*np.ones(self.d)) return np.linalg.solve(M,Hix.T.dot(R)).reshape(self.d) else: return np.zeros(self.d) def update(self,indices,H,R): """ Update latent factors for a single user or item. """ Hix = H[indices,:] HH = Hix.T.dot(Hix) if self.reg=="weighted": M = HH + np.diag(self.lbda*len(R)*np.ones(self.d)) elif self.reg=="default": M = HH + np.diag(self.lbda*np.ones(self.d)) return np.linalg.solve(M,Hix.T.dot(R)).reshape(self.d) def parallel_implicit_update(self,ind,HH,train,user=True): """ Implicit update latent factors for a single user or item applied in parallel """ if user: indices = train[ind].nonzero()[1] Hix = self.V[indices,:] R_u = train[ind,indices] R = R_u.toarray().T else: indices = train[:,ind].nonzero()[0] Hix = self.U[indices,:] R_i = train[indices,ind] R = R_i.toarray().T[0] if len(indices)>0: C = diags(self.transfo(R,intercept=False),shape=(len(R),len(R))) if self.reg=="weighted": M = HH + Hix.T.dot(C).dot(Hix) + np.diag(self.lbda*len(R)*np.ones(self.d)) elif self.reg=="default": M = HH + Hix.T.dot(C).dot(Hix) + np.diag(self.lbda*np.ones(self.d)) C = diags(self.transfo(R),shape=(len(R),len(R))) return np.linalg.solve(M,(C.dot(Hix)).sum(axis=0).T).reshape(self.d) else: return np.zeros(self.d) def implicit_update(self,indices,H,HH,R): """ Implicit update latent factors for a single user or item. """ # manque R entre Hix.T.dot(Hix) Hix = csr_matrix(H[indices,:]) C = diags(self.transfo(R,intercept=False),shape=(len(R),len(R))) if self.reg=="weighted": M = HH + Hix.T.dot(C).dot(Hix) + np.diag(self.lbda*len(R)*np.ones(self.d)) elif self.reg=="default": M = HH + Hix.T.dot(C).dot(Hix) + np.diag(self.lbda*np.ones(self.d)) C = diags(self.transfo(R),shape=(len(R),len(R))) return np.linalg.solve(M,(C.dot(Hix)).sum(axis=0).T).reshape(self.d)
mit
1,536,631,358,738,374,000
38.313514
139
0.526262
false
JackyChou/SGRS
GeneralReport/models.py
1
7496
#coding:utf-8 import json from django.db import models from django.db import connections from django.core.exceptions import ValidationError from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import AbstractUser CONDITION_TYPES = [ 'choice', 'mchoice', 'text', 'date', 'datetime', ] # each CONDITION_TYPES allow operate CONDITION_TYPE_OPERATE_MAP = { 'choice' : ['=','like','~','in'], 'mchoice' : ['in',], 'text' : ['=','<','<=','>','>=','like','in'], 'date' : ['=','<','<=','>','>='], 'datetime': ['=','<','<=','>','>='], } def replace_invalid_quote(input_str): """ Replace single quote,chinese single quote,chinese double quote """ input_str = input_str.replace(u"‘","'") input_str = input_str.replace(u"’","'") input_str = input_str.replace(u"”",'"') input_str = input_str.replace(u"“",'"') return input_str class JsonField(models.TextField): __metaclass__ = models.SubfieldBase description = "JsonField" def to_python(self, value): v = models.TextField.to_python(self, value) try: return json.loads(v)['v'] except: pass return v def get_prep_value(self, value): return json.dumps({'v':value}) class SGRSUser(AbstractUser): class Meta: app_label = 'GeneralReport' db_table = 'sgrs_user' verbose_name_plural = verbose_name = _('SGRS User') def has_report_perm(self, perm): result = False if not self.is_anonymous(): check_perm = None usable_report_perm = self.get_all_report_permissions() if isinstance(perm, ReportPermission): check_perm = perm else: if ReportPermission.objects.filter(name=perm).exists(): check_perm = ReportPermission.objects.get(name=perm) if check_perm and (check_perm in usable_report_perm): result = True return result def get_all_roles(self): return SGRSRole.objects.filter( sgrsuserassignment__user=self).order_by('id') def get_all_report_permissions(self): return ReportPermission.objects.filter( sgrsrole__in=self.get_all_roles()).order_by('id') def get_all_report_combination_permissions(self): return ReportPermissionCombination.objects.filter( sgrsrole__in=self.get_all_roles()).order_by('id') class AbstractBaseModel(models.Model): touch_date = models.DateTimeField(editable=False, auto_now_add=True) create_date = models.DateTimeField(editable=False, auto_now=True) class Meta: abstract = True def save(self, *args, **kwargs): self.full_clean() super(AbstractBaseModel, self).save(*args, **kwargs) class ReportType(AbstractBaseModel): name = models.CharField(max_length=100, db_index=True) class Meta: app_label = 'GeneralReport' db_table = 'sgrs_report_type' ordering = ['name'] def __unicode__(self): return u"%s" % (self.name) class ReportPermission(AbstractBaseModel): name = models.CharField(max_length=100, db_index=True, unique=True) description = models.TextField(blank=True) report_type = models.ForeignKey(ReportType, blank=True, null=True) db_conf = models.CharField(blank=True, verbose_name=_(u"DB_name"), max_length=128, choices=settings.DB_FOR_CHOICES) SQL_conf = models.TextField(verbose_name=_(u"SQL conf")) filter_conf = JsonField() class Meta: app_label = 'GeneralReport' db_table = 'sgrs_report_permission' ordering = ['report_type__name', 'name'] def __unicode__(self): return u"%s | %s | %s" % ( unicode(self.report_type.name) if self.report_type else u"Unclassified", unicode(self.description), unicode(self.name) ) def clean(self): # check name import re pattern = '^[a-z][a-z\-]+[a-z]$' if re.match(pattern, self.name ) is None: raise ValidationError( "Only lowercase characters and \"-\" are allowed!") # check filter_conf self.filter_conf = replace_invalid_quote(self.filter_conf) try: tmp_filter_conf = json.loads(self.filter_conf) except: raise ValidationError(u"filter_conf is not a valid json") if not isinstance(tmp_filter_conf, dict): raise ValidationError(u"filter_conf must be dict") condition_keys = tmp_filter_conf.keys() for ckey in condition_keys: item_field = tmp_filter_conf[ckey].get('field',None) item_type = tmp_filter_conf[ckey].get('type',None) item_operate = tmp_filter_conf[ckey].get('operate',None) if item_type not in CONDITION_TYPES: raise ValidationError(u"%s is not a valid type, only support %s" %(item_type,CONDITION_TYPES)) if item_field is None or item_type is None or item_operate is None: raise ValidationError(u"Please supply %s's key:field / type / operate" % ckey) if item_operate not in CONDITION_TYPE_OPERATE_MAP[item_type]: raise ValidationError(u"%s only can use %s" %(item_type,CONDITION_TYPE_OPERATE_MAP[item_type])) # check db_conf whether in settings try: connections[self.db_conf] except: raise ValidationError(u"Database %s isn't configured" % self.db_conf) # check filter_conf matching SQL_conf? sql_condition_list = re.findall(r'{{(\S+)}}',self.SQL_conf) sql_condition_list = list(set(sql_condition_list)) sql_condition_list.sort() condition_keys.sort() if sql_condition_list != condition_keys: raise ValidationError(u"where clauses not match, filter_conf is %s, SQL_conf is %s"%(condition_keys,sql_condition_list)) class ReportPermissionCombination(AbstractBaseModel): name = models.CharField(max_length=100, db_index=True) description = models.TextField(blank=True) report_permissions = models.ManyToManyField(ReportPermission, blank=True) class Meta: app_label = 'GeneralReport' db_table = 'sgrs_report_permission_combination' ordering = ['id'] def __unicode__(self): return self.name class SGRSRole(AbstractBaseModel): name = models.CharField(max_length=255, db_index=True, unique=True) description = models.TextField(blank=True) can_download = models.BooleanField(default=True) report_permissions = models.ManyToManyField(ReportPermission, blank=True) report_permission_combinations = models.ManyToManyField(ReportPermissionCombination, blank=True) class Meta: app_label = 'GeneralReport' db_table = 'sgrs_role' ordering = ['name'] verbose_name_plural = verbose_name = _('SGRS Role') def __unicode__(self): return self.name class SGRSUserAssignment(AbstractBaseModel): user = models.OneToOneField(settings.AUTH_USER_MODEL, db_index=True) roles = models.ManyToManyField(SGRSRole) class Meta: app_label = 'GeneralReport' db_table = 'sgrs_user_assignment' ordering = ['user'] verbose_name_plural = verbose_name = _('SGRS User Assignment') def __unicode__(self): return u'%s Role Assignment' %self.user
gpl-2.0
-6,067,342,202,493,637,000
34.14554
132
0.623564
false
MagicUmom/pattern_recognition_project
circle.py
1
19680
# coding=<utf-8> import numpy as np import cv2 from matplotlib import pyplot as plt from matplotlib.widgets import Slider from numpy import * import copy import time import sys import math import operator import os pic_path = 'dataset/true/1.png' pic_dir = 'dataset/true_resize_rotate/' rect_scale = 5 rect_area = 0 rect_min_area = 0.0010 color_range = 20 hvs_luminance = 190 angle_limit = 8 top_ext_dist = 4 cluster_dist = 20 #--------------------------------------------------------- pic_width = 0 pic_height = 0 #--------------------------------------------------------- def CalculateOneLineAndOnePointMinDistance(a,b,c): u = np.array([b[0] - a[0], (pic_height-b[1]) - (pic_height-a[1])]) v = np.array([c[0] - a[0], (pic_height-c[1]) - (pic_height-a[1])]) if (linalg.norm(u) > 0): L = abs(cross(u, v) / linalg.norm(u)) else: L = int() return L def CalculateTwoPointDistance(src, dst): a = np.array(src) b = np.array(dst) return np.linalg.norm(b-a) def PointConvertDegree(center, point1): angle = math.degrees(math.atan2((pic_height-point1[1]) - (pic_height-center[1]), point1[0] - center[0])) if (angle < 0) : angle = 360 + angle return angle def DegreeCompare(angleRef, angleDst): result = angleDst - angleRef if result > 180: result = 180 - result if result < -180: result = result + 360 return result def DegreeMirror(angle): if angle > 180: angle += 180 if angle >= 360: angle -= 360 return angle def GetRectColor(img, rect): m1 = np.zeros(img.shape, np.uint8) cv2.drawContours(m1, rect, 0, (255, 255, 255), -1) m1 = cv2.cvtColor(m1, cv2.COLOR_BGR2GRAY) m2 = cv2.bitwise_and(img, img, mask=m1) hist0 = cv2.calcHist([m2], [0], None, [256], [0.0, 255.0]) hist1 = cv2.calcHist([m2], [1], None, [256], [0.0, 255.0]) hist2 = cv2.calcHist([m2], [2], None, [256], [0.0, 255.0]) hist0[0:10] = 0 hist1[0:10] = 0 hist2[0:10] = 0 maxidx0, maxval0 = max(enumerate(hist0), key=operator.itemgetter(1)) maxidx1, maxval1 = max(enumerate(hist1), key=operator.itemgetter(1)) maxidx2, maxval2 = max(enumerate(hist2), key=operator.itemgetter(1)) #return (maxidx0, maxidx1, maxidx2) return (maxval0, maxval1, maxval2) ''' def GetRectColorHsv(img): hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) hist0 = cv2.calcHist([hsv], [0], None, [180], [0, 180]) hist1 = cv2.calcHist([hsv], [1], None, [256], [0, 256]) hist2 = cv2.calcHist([hsv], [2], None, [256], [0, 256]) hist1[0:10] = 0 hist2[0:10] = 0 hist2[0:10] = 0 maxidx0, maxval0 = max(enumerate(hist0), key=operator.itemgetter(1)) maxidx1, maxval1 = max(enumerate(hist1), key=operator.itemgetter(1)) maxidx2, maxval2 = max(enumerate(hist2), key=operator.itemgetter(1)) return (maxidx0, maxidx1, maxidx2) ''' def drawPoint(img, point, size=1, color=(0, 0, 255)): cv2.circle(img, point, size, color, -1) def FindCluster(cluster, idx1, idx2, rectWH): ret_cluster = [] for i in range(0, cluster.__len__()): pos = cluster[i] if pos != cluster[idx1] and pos != cluster[idx2]: dist = CalculateOneLineAndOnePointMinDistance(cluster[idx1], cluster[idx2], pos) limitDist = (rectWH[i][0]/(pic_width/4)) if limitDist < cluster_dist: limitDist = cluster_dist angle = abs(DegreeCompare(rectWH[i][2], rectWH[idx1][2])) if dist < limitDist and angle < angle_limit: ret_cluster.append(i) return ret_cluster def CheckCluster(rectCenter, rectWH): maxNum = 0 max_pos = [] dst_pos = [] dst_rect = [] dst_idx = [] for pos1 in range(0, rectCenter.__len__()): for pos2 in range(0, rectCenter.__len__()): if pos1 != pos2: angle3 = abs(DegreeCompare(rectWH[pos1][2], rectWH[pos2][2])) if angle3 < angle_limit: tmp = FindCluster(rectCenter, pos1, pos2, rectWH) if tmp.__len__() > maxNum: maxNum = tmp.__len__() max_pos = [pos1, pos2, angle3] dst_rect = tmp dst_pos.append(rectCenter[max_pos[0]]) dst_idx.append(max_pos[0]) dst_pos.append(rectCenter[max_pos[1]]) dst_idx.append(max_pos[1]) for pos in dst_rect: dst_pos.append(rectCenter[pos]) dst_idx.append(pos) #drawPoint(image, dst_pos[0], 5, (0, 255, 0)) #cv2.drawContours(image, [rectPos[dst_idx[0]]], 0, (0, 0, 255), 1) #drawPoint(image, dst_pos[1], 5, (0, 0, 255)) #cv2.drawContours(image, [rectPos[dst_idx[1]]], 0, (0, 0, 255), 1) ''' for pos in dst_pos: drawPoint(img, pos, 5, (255, 0, 0)) drawPoint(img, dst_pos[0], 5, (0, 255, 0)) drawPoint(img, dst_pos[1], 5, (0, 0, 255)) for pos in dst_idx: print rectWH[pos][2] cv2.drawContours(img, [rectPos[pos]], 0, (0, 0, 255), 1) ''' return dst_idx def findFourSide(contour): param = 0.001 approx = [] while param < 1: epsilon = param * cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, epsilon, True) param += 0.001 if approx.__len__() == 4: break return approx def findBottomSide(rect, angle): boxRect = [] for pos in rect: boxRect.append(pos[0]) # bottomPos = boxRect[0] bottomIdx = 0 idxTmp = 0 for pos in boxRect: if pos[1] > bottomPos[1]: bottomIdx = idxTmp idxTmp += 1 # bottomIdxNext = bottomIdx + 1 if bottomIdxNext >= 4: bottomIdxNext = 0 # bottomIdxPrev = bottomIdx - 1 if bottomIdxPrev < 0: bottomIdxPrev = 3 # angle1 = PointConvertDegree(boxRect[bottomIdx], boxRect[bottomIdxNext]) angleCmp = abs(DegreeCompare(angle, DegreeMirror(angle1))) if angleCmp < 60: return [boxRect[bottomIdx], boxRect[bottomIdxPrev]] else: return [boxRect[bottomIdx], boxRect[bottomIdxNext]] def findTopSide(rect, angle): boxRect = [] for pos in rect: boxRect.append(pos[0]) # TopPos = boxRect[0] TopIdx = 0 idxTmp = 0 for pos in boxRect: if pos[1] < TopPos[1]: TopIdx = idxTmp idxTmp += 1 # TopIdxNext = TopIdx + 1 if TopIdxNext >= 4: TopIdxNext = 0 # TopIdxPrev = TopIdx - 1 if TopIdxPrev < 0: TopIdxPrev = 3 # angle1 = DegreeMirror(PointConvertDegree(boxRect[TopIdx], boxRect[TopIdxNext])) angleCmp = abs(DegreeCompare(angle, angle1)) if angleCmp < 60: return [boxRect[TopIdx], boxRect[TopIdxPrev]] else: return [boxRect[TopIdx], boxRect[TopIdxNext]] def rotatePoint(origin, point, angle): angle = math.radians(360 - angle) ox, oy = origin px, py = point qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy) qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy) return qx, qy ''' def checkTheSamePoint(src1, src2): if src1[0] == src2[0]: if src1[1] == src2[1]: return 1 return 0 def findNextPoint(pos1, pos2): idx = pos1 + 1 if idx > 3: idx = 0 if idx == pos2: idx = pos1 - 1 if idx < 0: idx = 3 return idx def fixTopSide(img, rect, bottom): boxRect = [] for pos in rect: boxRect.append(pos[0]) # for pos in range(0, 4): if checkTheSamePoint(boxRect[pos], bottom[0]) > 0: idx1 = pos for pos in range(0, 4): if checkTheSamePoint(boxRect[pos], bottom[1]) > 0: idx2 = pos # idx1_1 = findNextPoint(idx1, idx2) idx2_1 = findNextPoint(idx2, idx1) angle = DegreeMirror(PointConvertDegree(boxRect[idx1], boxRect[idx2])) l1 = CalculateTwoPointDistance(boxRect[idx1], boxRect[idx1_1]) l2 = CalculateTwoPointDistance(boxRect[idx2], boxRect[idx2_1]) print l1, l2 if l1 > l2: max_idx = idx1_1 else: max_idx = idx2_1 print l1, l2 PointA = boxRect[max_idx] origin = boxRect[max_idx] NewPointA = np.int0(rotatePoint(origin, PointA, angle)) print NewPointA drawPoint(img, tuple(boxRect[idx2]), 5, (0, 255, 255)) drawPoint(img, tuple(boxRect[idx2_1]), 5, (0, 255, 255)) ''' def findSide(contour, angle): approx = findFourSide(contour) if approx.__len__() != 4: return None sideAngle = angle bottom = np.array(findBottomSide(approx, sideAngle)) top = np.array(findTopSide(approx, sideAngle)) #angle1 = DegreeMirror(PointConvertDegree(top[0], top[1])) #angle2 = DegreeMirror(PointConvertDegree(bottom[0], bottom[1])) #print "diff:", abs(DegreeCompare(angle1, angle2)) #if abs(DegreeCompare(angle1, angle2)) > 5: # fixTopSide(img, approx, bottom) #cv2.drawContours(img, [approx], 0, (0, 0, 255), 1) #cv2.drawContours(img, [bottom], 0, (255, 0, 255), 2) #cv2.drawContours(img, [top], 0, (255, 0, 0), 2) #drawPoint(img, tuple(top[0]), 5, (0, 255, 0)) return [top, bottom] def fixPoint(pos): x = pos[0] y = pos[1] if x < 0: x = 0 if y < 0: y = 0 #if x > pic_width: # x = pic_width - 1 #if y > pic_height: # y = pic_height - 1 return [x, y] def getTopSideRect(pos): if pos[0][0] > pos[1][0]: pos1 = pos[1] pos2 = pos[0] else: pos1 = pos[0] pos2 = pos[1] angle = PointConvertDegree(pos1, pos2) dist = CalculateTwoPointDistance(pos1, pos2) if top_ext_dist > 0: addDist = dist / top_ext_dist else: addDist = 0 ''' posT1 = fixPoint(extendPoint(pos1[0], pos1[1], addDist, angle)) posT2 = fixPoint(extendPoint(pos1[0], pos1[1], addDist, angle - 180)) a1 = CalculateTwoPointDistance(posT1, pos2) a2 = CalculateTwoPointDistance(posT2, pos2) if a1 > a2: pos1 = posT1 else: pos1 = posT2 posT1 = fixPoint(extendPoint(pos2[0], pos2[1], addDist, angle)) posT2 = fixPoint(extendPoint(pos2[0], pos2[1], addDist, angle + 180)) a1 = CalculateTwoPointDistance(posT1, pos1) a2 = CalculateTwoPointDistance(posT2, pos1) if a1 > a2: pos2 = posT1 else: pos2 = posT2 ''' pos1 = fixPoint(extendPoint(pos1, addDist, angle - 180)) pos2 = fixPoint(extendPoint(pos2, addDist, angle)) #pos2 = fixPoint(extendPoint(pos2[0], pos2[1], dist / top_ext_dist, angle + 90)) # NewP1 = extendPoint(pos1, dist / 2, angle) NewPointA = np.int0(rotatePoint(pos1, NewP1, angle+90)) NewPointA = fixPoint(NewPointA) # NewP2 = extendPoint(pos2, dist / 2, angle) NewPointB = np.int0(rotatePoint(pos2, NewP2, angle+90)) NewPointB = fixPoint(NewPointB) # dst_rect = [] dst_rect.append(pos1) dst_rect.append(NewPointA) dst_rect.append(NewPointB) dst_rect.append(pos2) dst_rect = np.array(dst_rect) return dst_rect def getBopttomSideRect(pos): if pos[0][0] > pos[1][0]: pos1 = pos[1] pos2 = pos[0] else: pos1 = pos[0] pos2 = pos[1] angle = PointConvertDegree(pos1, pos2) dist = CalculateTwoPointDistance(pos1, pos2) # NewP1 = extendPoint(pos1, dist / 2, angle) NewPointA = np.int0(rotatePoint(pos1, NewP1, angle - 90)) NewPointA = fixPoint(NewPointA) # NewP2 = extendPoint(pos2, dist / 2, angle) NewPointB = np.int0(rotatePoint(pos2, NewP2, angle - 90)) NewPointB = fixPoint(NewPointB) # dst_rect = [] dst_rect.append(pos1) dst_rect.append(NewPointA) dst_rect.append(NewPointB) dst_rect.append(pos2) dst_rect = np.array(dst_rect) return dst_rect def extendPoint(pos, d, theta): theta_rad = pi/2 - radians(theta + 90) return np.int0([pos[0] + d*cos(theta_rad), pos[1] + d*sin(theta_rad)]) #--------------------------------------------------------- def FindZebraCrossing(filePath): srcImg = image = cv2.imread(filePath) #original pic_width = image.shape[1] pic_height = image.shape[0] rect_area = np.int((pic_width * pic_height * 1.0) * rect_min_area) # Color Filter hsv = cv2.cvtColor(srcImg, cv2.COLOR_BGR2HSV) #hsv low_color = np.array([0, 0, hvs_luminance]) # low_color = np.array([0, 0, 180]) upper_color = np.array([180, 43, 255]) mask = cv2.inRange(hsv, low_color, upper_color) res = cv2.bitwise_and(srcImg, srcImg, mask=mask) #filter image # Fix Image Color image = cv2.cvtColor(srcImg, cv2.COLOR_BGR2RGB) # canny img_gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY) canny_img = cv2.Canny(img_gray, 150, 220, apertureSize=3) #canny contours, hierarchy = cv2.findContours(canny_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # for CV2 print("Contours:{} ", len(contours)) print("\n\n\n***************************************************************************\n") area_pos = [] rect_pos = [] rect_center = [] rect_wh = [] for i in range(0, len(contours)): hull = cv2.convexHull(contours[i]) if len(hull) < 5: continue return None #--------------------------------------------------------- def main(): for im_name in os.listdir(pic_dir): # im = Image.open(pic_dir + image) print(im_name) srcImg = image = cv2.imread(pic_dir+im_name) pic_width = image.shape[1] pic_height = image.shape[0] rect_area = np.int((pic_width * pic_height * 1.0) * rect_min_area) # Color Filter hsv = cv2.cvtColor(srcImg, cv2.COLOR_BGR2HSV) low_color = np.array([0, 0, hvs_luminance]) #low_color = np.array([0, 0, 180]) upper_color = np.array([180, 43, 255]) mask = cv2.inRange(hsv, low_color, upper_color) res = cv2.bitwise_and(srcImg, srcImg, mask=mask) # Fix Image Color image = cv2.cvtColor(srcImg, cv2.COLOR_BGR2RGB) #canny img_gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY) canny_img = cv2.Canny(img_gray, 150, 220, apertureSize=3) _,contours, hierarchy = cv2.findContours(canny_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # for CV2 #印出輪廓數量 # print("Contours: ",len(contours)) # print("\n\n\n***************************************************************************\n") area_pos = [] rect_pos = [] rect_center = [] rect_wh = [] for i in range(0, len(contours)): hull = cv2.convexHull(contours[i]) if len(hull) < 5: continue # 計算重心 moments = cv2.moments(hull) m00 = moments['m00'] centroid_x, centroid_y = None, None if m00 != 0: centroid_x = int(moments['m10'] / m00) # Take X coordinate centroid_y = int(moments['m01'] / m00) # Take Y coordinate circle_pos = (centroid_x, centroid_y) if len(circle_pos) != 2: continue if (circle_pos[0] == None) or (circle_pos[1] == None): continue #print circle_pos #x, y, w, h = cv2.boundingRect(hull) #cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) rect = cv2.minAreaRect(hull) box = cv2.boxPoints(rect) box = np.int0(box) #cv2.drawContours(image, [box], 0, (0, 0, 255), 1) a1 = CalculateTwoPointDistance(box[0], box[1]) a2 = CalculateTwoPointDistance(box[1], box[2]) box_w = max(a1, a2) box_h = min(a1, a2) if box_h <= 0: continue box_scale = (box_w / box_h) box_area = (box_w * box_h) if box_w == a1: box_angle = PointConvertDegree(box[0], box[1]) else: box_angle = PointConvertDegree(box[1], box[2]) if box_scale > rect_scale and box_area > rect_area: box_color = GetRectColor(image, [box]) if box_color[0] > color_range and box_color[1] > color_range and box_color[2] > color_range: # cv2.drawContours(image, [box], 0, (0, 0, 255), 1) # drawPoint(image, circle_pos, 5, (255, 0, 0)) rect_pos.append(hull) rect_center.append(circle_pos) rect_wh.append([box_w, box_h, box_angle]) if not rect_pos: pass # exit() else : try : idx_pos = CheckCluster(rect_center, rect_wh) for idx in idx_pos: for pos in rect_pos[idx]: area_pos.append(pos) area_pos = np.array(area_pos) hull = cv2.convexHull(area_pos) rect = cv2.minAreaRect(area_pos) box = cv2.boxPoints(rect) box = np.int0(box) x, y, w, h = cv2.boundingRect(hull) print(x,y,w,h) im = image[y:y+h,x:x+w] cv2.imwrite('dataset/true_for_train/' + im_name ,im) except : print("**** except #2 **** \n") pass # cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 1) # cv2.drawContours(image, [hull], -1, (255, 0, 255), 1) # cv2.drawContours(image, [box], 0, (0, 0, 255), 1) #print hull #print rect_wh[idx_pos[0]][2], rect_wh[idx_pos[0]][0] #print rect_wh[idx_pos[1]][2], rect_wh[idx_pos[1]][0] # line_dir = PointConvertDegree(rect_center[idx_pos[0]], rect_center[idx_pos[1]]) # line_dir = DegreeMirror(line_dir) # # dst = findSide(hull, line_dir) # topRect = getTopSideRect(dst[0]) # bottomRect = getBopttomSideRect(dst[1]) # # # cv2.drawContours(image, [topRect], 0, (255, 0, 0), 2) #cv2.drawContours(image, [bottomRect], 0, (255, 0, 0), 2) # print ("Top", topRect) # print ("Bottom", bottomRect) #--------------------------------------------------------- # Escape Keyboard Event def press(event): if event.key == u'escape': plt.close() cv2.destroyAllWindows() # fig.canvas.mpl_connect('key_press_event', press) #顯示原圖 & output # plt.subplot(1, 2, 1), plt.imshow(image) # plt.title('Original'), plt.xticks([]), plt.yticks([]) # # #顯示canny圖 # plt.subplot(1, 2, 2), plt.imshow(canny_img, cmap = 'gray') # plt.title('Canny'), plt.xticks([]), plt.yticks([]) # # # image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # # plt.show() # # print("\n***************************************************************************") # print(" End") # print("***************************************************************************") if __name__ == '__main__': main()
mit
461,858,287,817,124,300
30.529801
109
0.52601
false
ywang007/odo
docs/source/conf.py
1
9105
# -*- coding: utf-8 -*- # # into documentation build configuration file, created by # sphinx-quickstart on Sat Dec 6 16:03:44 2015. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.extlinks'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'odo' copyright = u'2015, Continuum Analytics' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. from odo import __version__ as version # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'ododoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'odo.tex', u'odo Documentation', u'Matthew Rocklin', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'odo', u'odo Documentation', [u'Continuum Analytics'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'odo', u'odo Documentation', u'Continuum Analytics', 'odo', 'Data migrations', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'odo' epub_author = u'Matthew Rocklin' epub_publisher = u'Continuum Analytics' epub_copyright = u'2015, Continuum Analytics' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True extlinks = dict(issue=('https://github.com/ContinuumIO/odo/issues/%s', '#'))
bsd-3-clause
93,646,292,306,281,840
30.724739
80
0.70335
false
libavg/libavg
samples/videochooser.py
1
4046
#!/usr/bin/env python # -*- coding: utf-8 -*- # libavg - Media Playback Engine. # Copyright (C) 2010-2021 Ulrich von Zadow # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Current versions can be found at www.libavg.de import os, sys from libavg import avg, app, player, Point2D class VideoChooser(app.MainDiv): def onArgvParserCreated(self, parser): parser.set_usage("%prog <folder>") parser.add_option('--duration', '-d', dest='duration', default=2000, type='int', help='Fade duration') parser.add_option('--width', '-w', dest='thumbWidth', default=320, type='int', help='Thumbnail width') def onArgvParsed(self, options, args, parser): if len(args) != 1: parser.print_help() sys.exit(1) self.__folder = args[0] self.__duration = options.duration self.__thumbWidth = options.thumbWidth def onInit(self): player.showCursor(True) self.videoListNode = avg.DivNode(parent=self) self.videoNodes = [] fileNames = os.listdir(self.__folder) i = 0 for fileName in fileNames: try: videoNode = avg.VideoNode( pos=(i*(self.__thumbWidth+20), 0), href=self.__folder+'/'+fileName, loop=True, mipmap=True, enablesound=False, parent = self.videoListNode) videoNode.play() self.videoNodes.append(videoNode) size = videoNode.getMediaSize() height = (self.__thumbWidth*size.y)/size.x videoNode.size = (self.__thumbWidth, height) videoNode.subscribe(videoNode.CURSOR_DOWN, lambda event, videoNode=videoNode: self.chooseVideo(event, videoNode)) i += 1 except RuntimeError: pass self.subscribe(self.CURSOR_MOTION, self.onMouseMove) self.bigVideoNode = None def onMouseMove(self, event): windowWidth = player.getRootNode().width ratio = event.x/float(windowWidth) self.videoListNode.x = -(ratio*(self.getTotalWidth()-windowWidth)) def chooseVideo(self, event, videoNode): if self.bigVideoNode: self.removeBigVideo() destSize = videoNode.size*2 destPos = Point2D(720, 550)-destSize/2 absPos = videoNode.getAbsPos(Point2D(0,0)) frame = videoNode.getCurFrame() self.bigVideoNode = avg.VideoNode(href=videoNode.href, loop=True, sensitive=False, parent=self) self.bigVideoNode.play() self.bigVideoNode.seekToFrame(frame) avg.EaseInOutAnim(self.bigVideoNode, "pos", 1000, absPos, destPos, False, 300, 300).start() avg.EaseInOutAnim(self.bigVideoNode, "size", 1000, videoNode.size, destSize, False, 300, 300).start() def removeBigVideo(self): oldVideoNode = self.bigVideoNode avg.Anim.fadeOut(oldVideoNode, self.__duration, lambda: oldVideoNode.unlink(True)) def getTotalWidth(self): return (self.__thumbWidth+20)*len(self.videoNodes) app.App().run(VideoChooser(), app_resolution='1440x900', app_window_size='720x450')
lgpl-2.1
2,171,723,810,859,796,700
37.169811
90
0.613198
false
CiscoSystems/python-neutronclient
neutronclient/neutron/v2_0/lb/vip.py
1
3800
# Copyright 2013 Mirantis 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. # # @author: Ilya Shakhat, Mirantis Inc. # # vim: tabstop=4 shiftwidth=4 softtabstop=4 import logging from neutronclient.neutron import v2_0 as neutronV20 class ListVip(neutronV20.ListCommand): """List vips that belong to a given tenant.""" resource = 'vip' log = logging.getLogger(__name__ + '.ListVip') list_columns = ['id', 'name', 'algorithm', 'address', 'protocol', 'admin_state_up', 'status'] pagination_support = True sorting_support = True class ShowVip(neutronV20.ShowCommand): """Show information of a given vip.""" resource = 'vip' log = logging.getLogger(__name__ + '.ShowVip') class CreateVip(neutronV20.CreateCommand): """Create a vip.""" resource = 'vip' log = logging.getLogger(__name__ + '.CreateVip') def add_known_arguments(self, parser): parser.add_argument( 'pool_id', metavar='pool', help='Pool id or name this vip belongs to') parser.add_argument( '--address', help='IP address of the vip') parser.add_argument( '--admin-state-down', dest='admin_state', action='store_false', help='set admin state up to false') parser.add_argument( '--connection-limit', help='the maximum number of connections per second allowed for ' 'the vip') parser.add_argument( '--description', help='description of the vip') parser.add_argument( '--name', required=True, help='name of the vip') parser.add_argument( '--protocol-port', required=True, help='TCP port on which to listen for client traffic that is ' 'associated with the vip address') parser.add_argument( '--protocol', required=True, help='protocol for balancing') parser.add_argument( '--subnet-id', required=True, help='the subnet on which to allocate the vip address') def args2body(self, parsed_args): _pool_id = neutronV20.find_resourceid_by_name_or_id( self.get_client(), 'pool', parsed_args.pool_id) _subnet_id = neutronV20.find_resourceid_by_name_or_id( self.get_client(), 'subnet', parsed_args.subnet_id) body = { self.resource: { 'pool_id': _pool_id, 'admin_state_up': parsed_args.admin_state, 'subnet_id': _subnet_id, }, } neutronV20.update_dict(parsed_args, body[self.resource], ['address', 'connection_limit', 'description', 'name', 'protocol_port', 'protocol', 'tenant_id']) return body class UpdateVip(neutronV20.UpdateCommand): """Update a given vip.""" resource = 'vip' log = logging.getLogger(__name__ + '.UpdateVip') class DeleteVip(neutronV20.DeleteCommand): """Delete a given vip.""" resource = 'vip' log = logging.getLogger(__name__ + '.DeleteVip')
apache-2.0
-3,435,352,296,504,954,400
32.043478
78
0.581842
false
MCGallaspy/kolibri
kolibri/auth/migrations/0002_auto_20160318_0557.py
1
1291
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-03-18 05:57 from __future__ import unicode_literals import django.db.models.deletion import mptt.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('kolibriauth', '0001_initial'), ] operations = [ migrations.CreateModel( name='Membership', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('collection', mptt.fields.TreeForeignKey(on_delete=django.db.models.deletion.CASCADE, to='kolibriauth.Collection')), ('dataset', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='kolibriauth.FacilityDataset')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='kolibriauth.FacilityUser')), ], ), migrations.AlterField( model_name='role', name='kind', field=models.CharField(choices=[(b'admin', 'Admin'), (b'coach', 'Coach')], max_length=20), ), migrations.AlterUniqueTogether( name='membership', unique_together=set([('user', 'collection')]), ), ]
mit
1,152,220,117,495,291,100
35.885714
133
0.606507
false
wackerly/faucet
faucet/valve.py
1
64797
"""Implementation of Valve learning layer 2/3 switch.""" # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2015 Brad Cowie, Christopher Lorier and Joe Stringer. # Copyright (C) 2015 Research and Education Advanced Network New Zealand Ltd. # Copyright (C) 2015--2018 The Contributors # # 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 random from collections import defaultdict, deque from faucet import tfm_pipeline from faucet import valve_acl from faucet import valve_flood from faucet import valve_host from faucet import valve_of from faucet import valve_packet from faucet import valve_route from faucet import valve_util from faucet.port import STACK_STATE_INIT, STACK_STATE_UP, STACK_STATE_DOWN from faucet.vlan import NullVLAN class ValveLogger(object): """Logger for a Valve that adds DP ID.""" def __init__(self, logger, dp_id, dp_name): self.logger = logger self.dp_id = dp_id self.dp_name = dp_name def _dpid_prefix(self, log_msg): """Add DP ID prefix to log message.""" return ' '.join((valve_util.dpid_log(self.dp_id), self.dp_name, log_msg)) def debug(self, log_msg): """Log debug level message.""" self.logger.debug(self._dpid_prefix(log_msg)) def info(self, log_msg): """Log info level message.""" self.logger.info(self._dpid_prefix(log_msg)) def error(self, log_msg): """Log error level message.""" self.logger.error(self._dpid_prefix(log_msg)) def warning(self, log_msg): """Log warning level message.""" self.logger.warning(self._dpid_prefix(log_msg)) class Valve(object): """Generates the messages to configure a datapath as a l2 learning switch. Vendor specific implementations may require sending configuration flows. This can be achieved by inheriting from this class and overwriting the function switch_features. """ DEC_TTL = True USE_BARRIERS = True base_prom_labels = None recent_ofmsgs = deque(maxlen=32) # type: ignore logger = None ofchannel_logger = None host_manager = None flood_manager = None _route_manager_by_ipv = None _last_advertise_sec = None _port_highwater = {} # type: dict _last_update_metrics_sec = None _last_packet_in_sec = 0 _packet_in_count_sec = 0 def __init__(self, dp, logname, metrics, notifier): self.dp = dp self.logname = logname self.metrics = metrics self.notifier = notifier self.dp_init() def _skip_tables(self): tables = [] any_routing = False for route_manager in list(self._route_manager_by_ipv.values()): if route_manager.active: any_routing = True else: tables.append(route_manager.fib_table) if not any_routing: tables.append(self.dp.tables['vip']) return tables def _active_tables(self): return set(self.dp.all_valve_tables()) - set(self._skip_tables()) def close_logs(self): """Explicitly close any active loggers.""" if self.logger is not None: valve_util.close_logger(self.logger.logger) valve_util.close_logger(self.ofchannel_logger) def dp_init(self): """Initialize datapath state at connection/re/config time.""" self.close_logs() self.logger = ValveLogger( logging.getLogger(self.logname + '.valve'), self.dp.dp_id, self.dp.name) self.ofchannel_logger = None self.base_prom_labels = { 'dp_id': hex(self.dp.dp_id), 'dp_name': self.dp.name, } self._packet_in_count_sec = 0 self._last_packet_in_sec = 0 self._last_advertise_sec = 0 self._route_manager_by_ipv = {} self._route_manager_by_eth_type = {} self._port_highwater = {} for vlan_vid in list(self.dp.vlans.keys()): self._port_highwater[vlan_vid] = {} for port_number in list(self.dp.ports.keys()): self._port_highwater[vlan_vid][port_number] = 0 for fib_table, route_manager_class in ( (self.dp.tables['ipv4_fib'], valve_route.ValveIPv4RouteManager), (self.dp.tables['ipv6_fib'], valve_route.ValveIPv6RouteManager)): route_manager = route_manager_class( self.logger, self.dp.arp_neighbor_timeout, self.dp.max_hosts_per_resolve_cycle, self.dp.max_host_fib_retry_count, self.dp.max_resolve_backoff_time, self.dp.proactive_learn, self.DEC_TTL, fib_table, self.dp.tables['vip'], self.dp.tables['eth_src'], self.dp.tables['eth_dst'], self.dp.tables['flood'], self.dp.highest_priority, self.dp.routers, self.dp.group_table_routing, self.dp.groups) self._route_manager_by_ipv[route_manager.IPV] = route_manager for vlan in list(self.dp.vlans.values()): if vlan.faucet_vips_by_ipv(route_manager.IPV): route_manager.active = True for eth_type in route_manager.CONTROL_ETH_TYPES: self._route_manager_by_eth_type[eth_type] = route_manager if self.dp.stack: self.flood_manager = valve_flood.ValveFloodStackManager( self.dp.tables['flood'], self.dp.tables['eth_src'], self.dp.low_priority, self.dp.highest_priority, self.dp.group_table, self.dp.groups, self.dp.combinatorial_port_flood, self.dp.stack, self.dp.stack_ports, self.dp.shortest_path_to_root, self.dp.shortest_path_port) else: self.flood_manager = valve_flood.ValveFloodManager( self.dp.tables['flood'], self.dp.tables['eth_src'], self.dp.low_priority, self.dp.highest_priority, self.dp.group_table, self.dp.groups, self.dp.combinatorial_port_flood) if self.dp.use_idle_timeout: self.host_manager = valve_host.ValveHostFlowRemovedManager( self.logger, self.dp.ports, self.dp.vlans, self.dp.tables['eth_src'], self.dp.tables['eth_dst'], self.dp.timeout, self.dp.learn_jitter, self.dp.learn_ban_timeout, self.dp.low_priority, self.dp.highest_priority) else: self.host_manager = valve_host.ValveHostManager( self.logger, self.dp.ports, self.dp.vlans, self.dp.tables['eth_src'], self.dp.tables['eth_dst'], self.dp.timeout, self.dp.learn_jitter, self.dp.learn_ban_timeout, self.dp.low_priority, self.dp.highest_priority) def _notify(self, event_dict): """Send an event notification.""" self.notifier.notify(self.dp.dp_id, self.dp.name, event_dict) def switch_features(self, _msg): """Send configuration flows necessary for the switch implementation. Args: msg (OFPSwitchFeatures): msg sent from switch. Vendor specific configuration should be implemented here. """ return [ valve_of.faucet_config(), valve_of.faucet_async(notify_flow_removed=self.dp.use_idle_timeout), valve_of.desc_stats_request()] def ofchannel_log(self, ofmsgs): """Log OpenFlow messages in text format to debugging log.""" if self.dp is None: return if self.dp.ofchannel_log is None: return if self.ofchannel_logger is None: self.ofchannel_logger = valve_util.get_logger( self.dp.ofchannel_log, self.dp.ofchannel_log, logging.DEBUG, 0) log_prefix = '%u %s' % ( len(ofmsgs), valve_util.dpid_log(self.dp.dp_id)) for i, ofmsg in enumerate(ofmsgs, start=1): self.ofchannel_logger.debug( '%u/%s %s', i, log_prefix, ofmsg) def _delete_all_valve_flows(self): """Delete all flows from all FAUCET tables.""" ofmsgs = [] ofmsgs.extend(self.dp.wildcard_table.flowdel()) if self.dp.meters: ofmsgs.append(valve_of.meterdel()) if self.dp.group_table: ofmsgs.append(self.dp.groups.delete_all()) return ofmsgs def _delete_all_port_match_flows(self, port): """Delete all flows that match an input port from all FAUCET tables.""" ofmsgs = [] port_acl_table = self.dp.tables['port_acl'] for table in self.dp.in_port_tables(): if self.dp.dp_acls and table == port_acl_table: continue ofmsgs.extend(table.flowdel( match=table.match(in_port=port.number))) return ofmsgs def _add_default_drop_flows(self): """Add default drop rules on all FAUCET tables.""" eth_src_table = self.dp.tables['eth_src'] flood_table = self.dp.tables['flood'] # default drop on all tables. ofmsgs = [] for table in self._active_tables(): ofmsgs.append(table.flowdrop(priority=self.dp.lowest_priority)) # drop broadcast sources if self.dp.drop_broadcast_source_address: ofmsgs.append(eth_src_table.flowdrop( eth_src_table.match(eth_src=valve_of.mac.BROADCAST_STR), priority=self.dp.highest_priority)) # antispoof for FAUCET's MAC address # TODO: antispoof for controller IPs on this VLAN, too. if self.dp.drop_spoofed_faucet_mac: for vlan in list(self.dp.vlans.values()): ofmsgs.append(eth_src_table.flowdrop( eth_src_table.match(eth_src=vlan.faucet_mac), priority=self.dp.high_priority)) ofmsgs.append(flood_table.flowdrop( flood_table.match( eth_dst=valve_packet.CISCO_SPANNING_GROUP_ADDRESS), priority=self.dp.highest_priority)) ofmsgs.append(flood_table.flowdrop( flood_table.match( eth_dst=valve_packet.BRIDGE_GROUP_ADDRESS, eth_dst_mask=valve_packet.BRIDGE_GROUP_MASK), priority=self.dp.highest_priority)) return ofmsgs def _vlan_add_acl(self, vlan): ofmsgs = [] if vlan.acls_in: acl_table = self.dp.tables['vlan_acl'] acl_allow_inst = valve_of.goto_table(self.dp.tables['eth_src']) acl_force_port_vlan_inst = valve_of.goto_table(self.dp.tables['eth_dst']) ofmsgs = valve_acl.build_acl_ofmsgs( vlan.acls_in, acl_table, acl_allow_inst, acl_force_port_vlan_inst, self.dp.highest_priority, self.dp.meters, vlan.acls_in[0].exact_match, vlan_vid=vlan.vid) return ofmsgs def _add_vlan_flood_flow(self): """Add a flow to flood packets for unknown destinations.""" return [self.dp.tables['eth_dst'].flowmod( priority=self.dp.low_priority, inst=[valve_of.goto_table(self.dp.tables['flood'])])] def _add_packetin_meter(self): """Add rate limiting of packet in pps (not supported by many DPs).""" if self.dp.packetin_pps: return [ valve_of.controller_pps_meterdel(), valve_of.controller_pps_meteradd(pps=self.dp.packetin_pps)] return [] def _add_dp_acls(self): """Add dataplane ACLs, if any.""" ofmsgs = [] if self.dp.dp_acls: port_acl_table = self.dp.tables['port_acl'] acl_allow_inst = valve_of.goto_table(self.dp.tables['vlan']) acl_force_port_vlan_inst = valve_of.goto_table(self.dp.tables['eth_dst']) ofmsgs.extend(valve_acl.build_acl_ofmsgs( self.dp.dp_acls, port_acl_table, acl_allow_inst, acl_force_port_vlan_inst, self.dp.highest_priority, self.dp.meters, False)) # TODO: exact match support for DP ACLs. return ofmsgs def _add_non_local_vlan_destination_flow(self): """Add flow to handle packets not destined to a local VLAN.""" return [self.dp.tables['eth_src'].flowmod( priority=self.dp.lowest_priority, inst=[valve_of.goto_table(self.dp.tables['eth_dst'])])] def _add_default_flows(self): """Configure datapath with necessary default tables and rules.""" ofmsgs = [] ofmsgs.extend(self._delete_all_valve_flows()) ofmsgs.extend(self._add_packetin_meter()) if self.dp.meters: for meter in list(self.dp.meters.values()): ofmsgs.append(meter.entry_msg) ofmsgs.extend(self._add_default_drop_flows()) ofmsgs.extend(self._add_vlan_flood_flow()) ofmsgs.extend(self._add_dp_acls()) ofmsgs.extend(self._add_non_local_vlan_destination_flow()) return ofmsgs def _add_vlan(self, vlan): """Configure a VLAN.""" ofmsgs = [] self.logger.info('Configuring %s' % vlan) # add ACL rules ofmsgs.extend(self._vlan_add_acl(vlan)) # add controller IPs if configured. for ipv in vlan.ipvs(): route_manager = self._route_manager_by_ipv[ipv] ofmsgs.extend(self._add_faucet_vips( route_manager, vlan, vlan.faucet_vips_by_ipv(ipv))) # install eth_dst_table flood ofmsgs ofmsgs.extend(self.flood_manager.build_flood_rules(vlan)) # add learn rule for this VLAN. eth_src_table = self.dp.tables['eth_src'] ofmsgs.append(eth_src_table.flowcontroller( eth_src_table.match(vlan=vlan), priority=self.dp.low_priority, inst=[valve_of.goto_table(self.dp.tables['eth_dst'])])) return ofmsgs def _del_vlan(self, vlan): """Delete a configured VLAN.""" ofmsgs = [] for table in self.dp.vlan_match_tables(): ofmsgs.extend(table.flowdel(match=table.match(vlan=vlan))) self.logger.info('Delete VLAN %s' % vlan) return ofmsgs def _add_ports_and_vlans(self, discovered_up_port_nos): """Add all configured and discovered ports and VLANs.""" all_configured_port_nos = set() for port in self.dp.stack_ports: all_configured_port_nos.add(port.number) for port in self.dp.output_only_ports: all_configured_port_nos.add(port.number) ofmsgs = [] for vlan in list(self.dp.vlans.values()): vlan_ports = vlan.get_ports() if vlan_ports: for port in vlan_ports: all_configured_port_nos.add(port.number) ofmsgs.extend(self._add_vlan(vlan)) vlan.reset_caches() ports_status = defaultdict(bool) for port_no in discovered_up_port_nos: if port_no in all_configured_port_nos: ports_status[port_no] = True self._notify({'PORTS_STATUS': ports_status}) all_up_port_nos = set() for port_no in all_configured_port_nos: if ports_status[port_no]: self._set_port_status(port_no, True) all_up_port_nos.add(port_no) else: self._set_port_status(port_no, False) ofmsgs.extend( self.ports_add( all_up_port_nos, cold_start=True, log_msg='configured')) self.dp.dyn_up_ports = set(discovered_up_port_nos) return ofmsgs def ofdescstats_handler(self, body): """Handle OF DP description.""" self.metrics.of_dp_desc_stats.labels( # pylint: disable=no-member **dict(self.base_prom_labels, mfr_desc=valve_util.utf8_decode(body.mfr_desc), hw_desc=valve_util.utf8_decode(body.hw_desc), sw_desc=valve_util.utf8_decode(body.sw_desc), serial_num=valve_util.utf8_decode(body.serial_num), dp_desc=valve_util.utf8_decode(body.dp_desc))).set(self.dp.dp_id) def _set_port_status(self, port_no, port_status): """Set port operational status.""" port_labels = dict(self.base_prom_labels, port=port_no) self.metrics.port_status.labels( # pylint: disable=no-member **port_labels).set(port_status) if port_status: self.dp.dyn_up_ports.add(port_no) else: self.dp.dyn_up_ports -= set([port_no]) def port_status_handler(self, port_no, reason, state): """Return OpenFlow messages responding to port operational status change.""" def _decode_port_status(reason): """Humanize the port status reason code.""" port_status_codes = { valve_of.ofp.OFPPR_ADD: 'ADD', valve_of.ofp.OFPPR_DELETE: 'DELETE', valve_of.ofp.OFPPR_MODIFY: 'MODIFY' } return port_status_codes.get(reason, 'UNKNOWN') port_status = valve_of.port_status_from_state(state) self._notify( {'PORT_CHANGE': { 'port_no': port_no, 'reason': _decode_port_status(reason), 'state': state, 'status': port_status}}) ofmsgs = [] self._set_port_status(port_no, port_status) if not self.port_no_valid(port_no): return ofmsgs port = self.dp.ports[port_no] if not port.opstatus_reconf: return ofmsgs if reason == valve_of.ofp.OFPPR_ADD: ofmsgs = self.port_add(port_no) elif reason == valve_of.ofp.OFPPR_DELETE: ofmsgs = self.port_delete(port_no) elif reason == valve_of.ofp.OFPPR_MODIFY: ofmsgs.extend(self.port_delete(port_no)) if port_status: ofmsgs.extend(self.port_add(port_no)) else: self.logger.warning('Unhandled port status %s/state %s for %s' % ( reason, state, port)) return ofmsgs def advertise(self, now): """Called periodically to advertise services (eg. IPv6 RAs).""" ofmsgs = [] if (self.dp.advertise_interval and now - self._last_advertise_sec > self.dp.advertise_interval): for vlan in list(self.dp.vlans.values()): for route_manager in list(self._route_manager_by_ipv.values()): ofmsgs.extend(route_manager.advertise(vlan)) self._last_advertise_sec = now return ofmsgs def _send_lldp_beacon_on_port(self, port, now): chassis_id = str(self.dp.faucet_dp_mac) ttl = self.dp.lldp_beacon['send_interval'] * 3 lldp_beacon = port.lldp_beacon chassis_id = str(self.dp.faucet_dp_mac) org_tlvs = [ (tlv['oui'], tlv['subtype'], tlv['info']) for tlv in lldp_beacon['org_tlvs']] org_tlvs.extend(valve_packet.faucet_lldp_tlvs(self.dp)) org_tlvs.extend(valve_packet.faucet_lldp_stack_state_tlvs(self.dp, port)) system_name = lldp_beacon['system_name'] if not system_name: system_name = self.dp.lldp_beacon['system_name'] lldp_beacon_pkt = valve_packet.lldp_beacon( self.dp.faucet_dp_mac, chassis_id, port.number, ttl, org_tlvs=org_tlvs, system_name=system_name, port_descr=lldp_beacon['port_descr']) port.dyn_last_lldp_beacon_time = now return valve_of.packetout(port.number, lldp_beacon_pkt.data) def _lldp_beacon_ports(self, now): """Return list of ports to send LLDP packets; stacked ports always send LLDP.""" priority_ports = set([port for port in self.dp.stack_ports if port.running() and port.lldp_beacon_enabled()]) cutoff_beacon_time = now - self.dp.lldp_beacon['send_interval'] nonpriority_ports = set([ port for port in self.dp.lldp_beacon_ports if port.running() and ( port.dyn_last_lldp_beacon_time is None or port.dyn_last_lldp_beacon_time < cutoff_beacon_time)]) nonpriority_ports -= priority_ports send_ports = list(priority_ports) send_ports.extend(list(nonpriority_ports)[:self.dp.lldp_beacon['max_per_interval']]) random.shuffle(send_ports) return send_ports def send_lldp_beacons(self, now): """Called periodically to send LLDP beacon packets.""" # TODO: the beacon service is specifically NOT to support conventional R/STP. # It is intended to facilitate physical troubleshooting (e.g. # a standard cable tester can display OF port information). # It is used also by stacking to verify stacking links. # TODO: in the stacking case, provide an authentication scheme for the probes # so they cannot be forged. if not self.dp.lldp_beacon: return [] send_ports = self._lldp_beacon_ports(now) self.logger.debug('sending LLDP beacons on ports %s' % send_ports) ofmsgs = [self._send_lldp_beacon_on_port(port, now) for port in send_ports] return ofmsgs def _update_stack_link_state(self, port, now): if port.is_stack_admin_down(): return stack_probe_info = port.dyn_stack_probe_info last_seen_lldp_time = stack_probe_info.get('last_seen_lldp_time', None) if last_seen_lldp_time is None: return next_state = None remote_dp = port.stack['dp'] stack_correct = stack_probe_info['stack_correct'] remote_port_state = stack_probe_info['remote_port_state'] send_interval = remote_dp.lldp_beacon['send_interval'] num_lost_lldp = round((now - last_seen_lldp_time) / send_interval) if not stack_correct: if not port.is_stack_down(): next_state = port.stack_down self.logger.error('Stack %s DOWN, incorrect cabling' % port) elif num_lost_lldp > port.max_lldp_lost: if not port.is_stack_down(): next_state = port.stack_down self.logger.error( 'Stack %s DOWN, too many (%u) packets lost' % (port, num_lost_lldp)) elif port.is_stack_down() and not port.is_stack_init(): next_state = port.stack_init self.logger.info('Stack %s INIT' % port) elif (port.is_stack_init() and remote_port_state in set([STACK_STATE_UP, STACK_STATE_INIT])): next_state = port.stack_up self.logger.info('Stack %s UP' % port) elif port.is_stack_up() and remote_port_state == STACK_STATE_DOWN: next_state = port.stack_down self.logger.error('Stack %s DOWN, remote port is down' % port) if next_state is None: return next_state() port_labels = dict(self.base_prom_labels, port=port.number) self.metrics.port_stack_state.labels( # pylint: disable=no-member **port_labels).set(port.dyn_stack_current_state) port_stack_up = port.is_stack_up() self.flood_manager.update_stack_topo(port_stack_up, self.dp, port) def update_stack_link_states(self, now): """Called periodically to verify the state of stack ports.""" for port in self.dp.stack_ports: self._update_stack_link_state(port, now) def datapath_connect(self, now, discovered_up_ports): """Handle Ryu datapath connection event and provision pipeline. Args: now (float): current epoch time. discovered_up_ports (list): datapath port numbers that are up. Returns: list: OpenFlow messages to send to datapath. """ self.logger.info('Cold start configuring DP') self._notify( {'DP_CHANGE': { 'reason': 'cold_start'}}) ofmsgs = [] ofmsgs.extend(self._add_default_flows()) ofmsgs.extend(self._add_ports_and_vlans(discovered_up_ports)) self.dp.dyn_last_coldstart_time = now self.dp.running = True self.metrics.of_dp_connections.labels( # pylint: disable=no-member **self.base_prom_labels).inc() self.metrics.dp_status.labels( # pylint: disable=no-member **self.base_prom_labels).set(1) return ofmsgs def datapath_disconnect(self): """Handle Ryu datapath disconnection event.""" self.logger.warning('datapath down') self._notify( {'DP_CHANGE': { 'reason': 'disconnect'}}) self.dp.running = False self.metrics.of_dp_disconnections.labels( # pylint: disable=no-member **self.base_prom_labels).inc() self.metrics.dp_status.labels( # pylint: disable=no-member **self.base_prom_labels).set(0) def _port_add_acl(self, port, cold_start=False): ofmsgs = [] acl_table = self.dp.tables['port_acl'] in_port_match = acl_table.match(in_port=port.number) if cold_start: ofmsgs.extend(acl_table.flowdel(in_port_match)) acl_allow_inst = valve_of.goto_table(self.dp.tables['vlan']) acl_force_port_vlan_inst = valve_of.goto_table(self.dp.tables['eth_dst']) if port.acls_in: ofmsgs.extend(valve_acl.build_acl_ofmsgs( port.acls_in, acl_table, acl_allow_inst, acl_force_port_vlan_inst, self.dp.highest_priority, self.dp.meters, port.acls_in[0].exact_match, port_num=port.number)) else: ofmsgs.append(acl_table.flowmod( in_port_match, priority=self.dp.highest_priority, inst=[acl_allow_inst])) return ofmsgs def _port_add_vlan_rules(self, port, vlan_vid, vlan_inst): vlan_table = self.dp.tables['vlan'] ofmsgs = [] ofmsgs.append(vlan_table.flowmod( vlan_table.match(in_port=port.number, vlan=vlan_vid), priority=self.dp.low_priority, inst=vlan_inst)) return ofmsgs def _port_add_vlan_untagged(self, port, vlan, forwarding_table, mirror_act): push_vlan_act = mirror_act + valve_of.push_vlan_act(vlan.vid) push_vlan_inst = [ valve_of.apply_actions(push_vlan_act), valve_of.goto_table(forwarding_table) ] return self._port_add_vlan_rules(port, NullVLAN(), push_vlan_inst) def _port_add_vlan_tagged(self, port, vlan, forwarding_table, mirror_act): vlan_inst = [ valve_of.goto_table(forwarding_table) ] if mirror_act: vlan_inst = [valve_of.apply_actions(mirror_act)] + vlan_inst return self._port_add_vlan_rules(port, vlan, vlan_inst) def _find_forwarding_table(self, vlan): if vlan.acls_in: return self.dp.tables['vlan_acl'] return self.dp.tables['eth_src'] def _port_add_vlans(self, port, mirror_act): ofmsgs = [] for vlan in port.tagged_vlans: ofmsgs.extend(self._port_add_vlan_tagged( port, vlan, self._find_forwarding_table(vlan), mirror_act)) if port.native_vlan is not None: ofmsgs.extend(self._port_add_vlan_untagged( port, port.native_vlan, self._find_forwarding_table(port.native_vlan), mirror_act)) return ofmsgs def _port_delete_flows_state(self, port): """Delete flows/state for a port.""" ofmsgs = [] ofmsgs.extend(self._delete_all_port_match_flows(port)) ofmsgs.extend(self.dp.tables['eth_dst'].flowdel(out_port=port.number)) if port.permanent_learn: eth_src_table = self.dp.tables['eth_src'] for entry in port.hosts(): ofmsgs.extend(eth_src_table.flowdel( match=eth_src_table.match(eth_src=entry.eth_src))) for vlan in port.vlans(): vlan.clear_cache_hosts_on_port(port) return ofmsgs def ports_add(self, port_nums, cold_start=False, log_msg='up'): """Handle the addition of ports. Args: port_num (list): list of port numbers. cold_start (bool): True if configuring datapath from scratch. Returns: list: OpenFlow messages, if any. """ ofmsgs = [] vlans_with_ports_added = set() eth_src_table = self.dp.tables['eth_src'] vlan_table = self.dp.tables['vlan'] for port_num in port_nums: if port_num not in self.dp.ports: self.logger.info( 'Ignoring port:%u not present in configuration file' % port_num) continue port = self.dp.ports[port_num] port.dyn_phys_up = True self.logger.info('%s %s' % (port, log_msg)) if not port.running(): continue if port.output_only: ofmsgs.append(vlan_table.flowdrop( match=vlan_table.match(in_port=port_num), priority=self.dp.highest_priority)) continue if port.receive_lldp: ofmsgs.append(vlan_table.flowcontroller( match=vlan_table.match( in_port=port_num, eth_dst=valve_packet.LLDP_MAC_NEAREST_BRIDGE, eth_dst_mask=valve_packet.BRIDGE_GROUP_MASK, eth_type=valve_of.ether.ETH_TYPE_LLDP), priority=self.dp.highest_priority, max_len=128)) if port.lacp: ofmsgs.extend(self.lacp_down(port)) if port.override_output_port: ofmsgs.append(self.dp.tables['eth_src'].flowmod( match=self.dp.tables['eth_src'].match( in_port=port_num), priority=self.dp.low_priority + 1, inst=[valve_of.apply_actions([ valve_of.output_controller(), valve_of.output_port(port.override_output_port.number)])])) if not self.dp.dp_acls: acl_ofmsgs = self._port_add_acl(port) ofmsgs.extend(acl_ofmsgs) port_vlans = port.vlans() # If this is a stacking port, accept all VLANs (came from another FAUCET) if port.stack is not None: # Actual stack traffic will have VLAN tags. ofmsgs.append(vlan_table.flowdrop( match=vlan_table.match( in_port=port_num, vlan=NullVLAN()), priority=self.dp.low_priority+1)) ofmsgs.append(vlan_table.flowmod( match=vlan_table.match(in_port=port_num), priority=self.dp.low_priority, inst=[valve_of.goto_table(eth_src_table)])) port_vlans = list(self.dp.vlans.values()) else: mirror_act = port.mirror_actions() # Add port/to VLAN rules. ofmsgs.extend(self._port_add_vlans(port, mirror_act)) for vlan in port_vlans: vlans_with_ports_added.add(vlan) # Only update flooding rules if not cold starting. if not cold_start: for vlan in vlans_with_ports_added: ofmsgs.extend(self.flood_manager.build_flood_rules(vlan)) return ofmsgs def port_add(self, port_num): """Handle addition of a single port. Args: port_num (list): list of port numbers. Returns: list: OpenFlow messages, if any. """ return self.ports_add([port_num]) def ports_delete(self, port_nums, log_msg='down'): """Handle the deletion of ports. Args: port_nums (list): list of port numbers. Returns: list: OpenFlow messages, if any. """ ofmsgs = [] vlans_with_deleted_ports = set() for port_num in port_nums: if port_num not in self.dp.ports: continue port = self.dp.ports[port_num] port.dyn_phys_up = False self.logger.info('%s %s' % (port, log_msg)) if not port.output_only: if port.lacp: ofmsgs.extend(self.lacp_down(port)) else: ofmsgs.extend(self._port_delete_flows_state(port)) for vlan in port.vlans(): vlans_with_deleted_ports.add(vlan) for vlan in vlans_with_deleted_ports: ofmsgs.extend(self.flood_manager.build_flood_rules( vlan, modify=True)) return ofmsgs def port_delete(self, port_num): """Return flow messages that delete port from pipeline.""" return self.ports_delete([port_num]) def lacp_down(self, port): """Return OpenFlow messages when LACP is down on a port.""" port.dyn_lacp_up = 0 vlan_table = self.dp.tables['vlan'] ofmsgs = [] ofmsgs.extend(self._port_delete_flows_state(port)) ofmsgs.append(vlan_table.flowdrop( match=vlan_table.match(in_port=port.number), priority=self.dp.high_priority)) ofmsgs.append(vlan_table.flowcontroller( vlan_table.match( in_port=port.number, eth_type=valve_of.ether.ETH_TYPE_SLOW, eth_dst=valve_packet.SLOW_PROTOCOL_MULTICAST), priority=self.dp.highest_priority, max_len=128)) self.metrics.port_lacp_status.labels( # pylint: disable=no-member **dict(self.base_prom_labels, port=port.number)).set(0) return ofmsgs def lacp_up(self, port): """Return OpenFlow messages when LACP is up on a port.""" vlan_table = self.dp.tables['vlan'] ofmsgs = [] ofmsgs.extend(vlan_table.flowdel( match=vlan_table.match(in_port=port.number), priority=self.dp.high_priority, strict=True)) self.metrics.port_lacp_status.labels( # pylint: disable=no-member **dict(self.base_prom_labels, port=port.number)).set(1) return ofmsgs def lacp_handler(self, now, pkt_meta): """Handle a LACP packet. We are a currently a passive, non-aggregateable LACP partner. Args: now (float): current epoch time. pkt_meta (PacketMeta): packet for control plane. Returns: list: OpenFlow messages, if any. """ # TODO: ensure config consistent between LAG ports. ofmsgs = [] if (pkt_meta.eth_dst == valve_packet.SLOW_PROTOCOL_MULTICAST and pkt_meta.eth_type == valve_of.ether.ETH_TYPE_SLOW and pkt_meta.port.lacp): pkt_meta.reparse_all() lacp_pkt = valve_packet.parse_lacp_pkt(pkt_meta.pkt) if lacp_pkt: last_lacp_up = pkt_meta.port.dyn_lacp_up pkt_meta.port.dyn_last_lacp_pkt = lacp_pkt pkt_meta.port.dyn_lacp_up = lacp_pkt.actor_state_synchronization pkt_meta.port.dyn_lacp_updated_time = now if last_lacp_up != pkt_meta.port.dyn_lacp_up: self.logger.info('LACP state change from %s to %s on %s to %s LAG %u' % ( last_lacp_up, pkt_meta.port.dyn_lacp_up, pkt_meta.port, lacp_pkt.actor_system, pkt_meta.port.lacp)) if pkt_meta.port.dyn_lacp_up: ofmsgs.extend(self.lacp_up(pkt_meta.port)) pkt = valve_packet.lacp_reqreply( self.dp.faucet_dp_mac, self.dp.faucet_dp_mac, pkt_meta.port.lacp, pkt_meta.port.number, lacp_pkt.actor_system, lacp_pkt.actor_key, lacp_pkt.actor_port, lacp_pkt.actor_system_priority, lacp_pkt.actor_port_priority, lacp_pkt.actor_state_defaulted, lacp_pkt.actor_state_expired, lacp_pkt.actor_state_timeout, lacp_pkt.actor_state_collecting, lacp_pkt.actor_state_distributing, lacp_pkt.actor_state_aggregation, lacp_pkt.actor_state_synchronization, lacp_pkt.actor_state_activity) ofmsgs.append(valve_of.packetout(pkt_meta.port.number, pkt.data)) return ofmsgs @staticmethod def _get_tlvs_by_type(lldp_pkt, tlv_type): return [tlv for tlv in lldp_pkt.tlvs if tlv.tlv_type == tlv_type] @staticmethod def _tlvs_by_subtype(tlvs, subtype): return [tlv for tlv in tlvs if tlv.subtype == subtype] def _get_faucet_tlvs(self, lldp_pkt): return [tlv for tlv in self._get_tlvs_by_type( lldp_pkt, valve_packet.lldp.LLDP_TLV_ORGANIZATIONALLY_SPECIFIC) if tlv.oui == valve_packet.faucet_oui(self.dp.faucet_dp_mac)] def _parse_faucet_lldp(self, lldp_pkt): remote_dp_id = None remote_dp_name = None remote_port_id = None remote_port_state = None faucet_tlvs = self._get_faucet_tlvs(lldp_pkt) if faucet_tlvs: dp_id_tlvs = self._tlvs_by_subtype( faucet_tlvs, valve_packet.LLDP_FAUCET_DP_ID) dp_name_tlvs = self._get_tlvs_by_type( lldp_pkt, valve_packet.lldp.LLDP_TLV_SYSTEM_NAME) port_id_tlvs = self._get_tlvs_by_type( lldp_pkt, valve_packet.lldp.LLDP_TLV_PORT_ID) port_state_tlvs = self._tlvs_by_subtype( faucet_tlvs, valve_packet.LLDP_FAUCET_STACK_STATE) try: remote_dp_id = int(dp_id_tlvs[0].info) remote_port_id = int(port_id_tlvs[0].port_id) remote_port_state = int(port_state_tlvs[0].info) remote_dp_name = valve_util.utf8_decode( dp_name_tlvs[0].system_name) except ValueError: pass return (remote_dp_id, remote_dp_name, remote_port_id, remote_port_state) def lldp_handler(self, now, pkt_meta): """Handle an LLDP packet. Args: pkt_meta (PacketMeta): packet for control plane. """ if pkt_meta.eth_type != valve_of.ether.ETH_TYPE_LLDP: return pkt_meta.reparse_all() lldp_pkt = valve_packet.parse_lldp(pkt_meta.pkt) if not lldp_pkt: return port = pkt_meta.port (remote_dp_id, remote_dp_name, remote_port_id, remote_port_state) = self._parse_faucet_lldp(lldp_pkt) if remote_dp_id and remote_port_id: self.logger.info('FAUCET LLDP from %s (remote %s, port %u)' % ( pkt_meta.port, valve_util.dpid_log(remote_dp_id), remote_port_id)) if port.stack: remote_dp = port.stack['dp'] remote_port = port.stack['port'] stack_correct = True self.metrics.stack_probes_received.labels( # pylint: disable=no-member **self.base_prom_labels).inc() if (remote_dp_id != remote_dp.dp_id or remote_dp_name != remote_dp.name or remote_port_id != remote_port.number): self.logger.error( 'Stack %s cabling incorrect, expected %s:%s:%u, actual %s:%s:%u' % ( port, valve_util.dpid_log(remote_dp.dp_id), remote_dp.name, remote_port.number, valve_util.dpid_log(remote_dp_id), remote_dp_name, remote_port_id)) stack_correct = False self.metrics.stack_cabling_errors.labels( # pylint: disable=no-member **self.base_prom_labels).inc() port.dyn_stack_probe_info = { 'last_seen_lldp_time': now, 'stack_correct': stack_correct, 'remote_dp_id': remote_dp_id, 'remote_dp_name': remote_dp_name, 'remote_port_id': remote_port_id, 'remote_port_state': remote_port_state } self._update_stack_link_state(port, now) self.logger.debug('LLDP from %s: %s' % (pkt_meta.port, str(lldp_pkt))) @staticmethod def _control_plane_handler(now, pkt_meta, route_manager): """Handle a packet probably destined to FAUCET's route managers. For example, next hop resolution or ICMP echo requests. Args: pkt_meta (PacketMeta): packet for control plane. route_manager (ValveRouteManager): route manager for this eth_type. Returns: list: OpenFlow messages, if any. """ if (pkt_meta.eth_dst == pkt_meta.vlan.faucet_mac or not valve_packet.mac_addr_is_unicast(pkt_meta.eth_dst)): return route_manager.control_plane_handler(now, pkt_meta) return [] def rate_limit_packet_ins(self, now): """Return True if too many packet ins this second.""" if self._last_packet_in_sec != now: self._last_packet_in_sec = now self._packet_in_count_sec = 0 self._packet_in_count_sec += 1 if self.dp.ignore_learn_ins: if self._packet_in_count_sec % self.dp.ignore_learn_ins == 0: self.metrics.of_ignored_packet_ins.labels( # pylint: disable=no-member **self.base_prom_labels).inc() return True return False def _learn_host(self, now, other_valves, pkt_meta): """Possibly learn a host on a port. Args: valves (list): of all Valves (datapaths). pkt_meta (PacketMeta): PacketMeta instance for packet received. Returns: list: OpenFlow messages, if any. """ learn_port = self.flood_manager.edge_learn_port( other_valves, pkt_meta) if learn_port is not None: learn_flows, previous_port = self.host_manager.learn_host_on_vlan_ports( now, learn_port, pkt_meta.vlan, pkt_meta.eth_src, last_dp_coldstart_time=self.dp.dyn_last_coldstart_time) if learn_flows: if pkt_meta.l3_pkt is None: pkt_meta.reparse_ip() previous_port_no = None port_move_text = '' if previous_port is not None: previous_port_no = previous_port.number if pkt_meta.port.number != previous_port_no: port_move_text = ', moved from port %u' % previous_port_no self.logger.info( 'L2 learned %s (L2 type 0x%4.4x, L3 src %s, L3 dst %s) ' 'on %s%s on VLAN %u (%u hosts total)' % ( pkt_meta.eth_src, pkt_meta.eth_type, pkt_meta.l3_src, pkt_meta.l3_dst, pkt_meta.port, port_move_text, pkt_meta.vlan.vid, pkt_meta.vlan.hosts_count())) self._notify( {'L2_LEARN': { 'port_no': pkt_meta.port.number, 'previous_port_no': previous_port_no, 'vid': pkt_meta.vlan.vid, 'eth_src': pkt_meta.eth_src, 'eth_type': pkt_meta.eth_type, 'l3_src_ip': pkt_meta.l3_src, 'l3_dst_ip': pkt_meta.l3_dst}}) return learn_flows return [] def port_no_valid(self, port_no): """Return True if supplied port number valid on this datapath.""" if valve_of.ignore_port(port_no): return False if port_no not in self.dp.ports: self.logger.info('port %u unknown' % port_no) return False return True def parse_rcv_packet(self, in_port, vlan_vid, eth_type, data, orig_len, pkt, eth_pkt): """Parse a received packet into a PacketMeta instance. Args: in_port (int): port packet was received on. vlan_vid (int): VLAN VID of port packet was received on. eth_type (int): Ethernet type of packet. data (bytes): Raw packet data. orig_len (int): Original length of packet. pkt (ryu.lib.packet.packet): parsed packet received. ekt_pkt (ryu.lib.packet.ethernet): parsed Ethernet header. Returns: PacketMeta instance. """ eth_src = eth_pkt.src eth_dst = eth_pkt.dst vlan = None if vlan_vid is not None: vlan = self.dp.vlans[vlan_vid] port = self.dp.ports[in_port] return valve_packet.PacketMeta( data, orig_len, pkt, eth_pkt, port, vlan, eth_src, eth_dst, eth_type) def parse_pkt_meta(self, msg): """Parse OF packet-in message to PacketMeta.""" if not self.dp.running: return None if self.dp.cookie != msg.cookie: return None # Drop any packet we didn't specifically ask for if msg.reason != valve_of.ofp.OFPR_ACTION: return None if not msg.match: return None in_port = msg.match['in_port'] if not in_port or not self.port_no_valid(in_port): return None if not msg.data: return None # Truncate packet in data (OVS > 2.5 does not honor max_len) data = msg.data[:valve_of.MAX_PACKET_IN_BYTES] # eth/VLAN header only pkt, eth_pkt, eth_type, vlan_vid = valve_packet.parse_packet_in_pkt( data, max_len=valve_packet.ETH_VLAN_HEADER_SIZE) if pkt is None or eth_pkt is None: self.logger.info( 'unparseable packet from port %u' % in_port) return None if vlan_vid is not None and vlan_vid not in self.dp.vlans: self.logger.info( 'packet for unknown VLAN %u' % vlan_vid) return None pkt_meta = self.parse_rcv_packet( in_port, vlan_vid, eth_type, data, msg.total_len, pkt, eth_pkt) if not valve_packet.mac_addr_is_unicast(pkt_meta.eth_src): self.logger.info( 'packet with non-unicast eth_src %s port %u' % ( pkt_meta.eth_src, in_port)) return None if self.dp.stack is not None: if (not pkt_meta.port.stack and pkt_meta.vlan and pkt_meta.vlan not in pkt_meta.port.tagged_vlans and pkt_meta.vlan != pkt_meta.port.native_vlan): self.logger.warning( ('packet from non-stack port number %u is not member of VLAN %u' % ( pkt_meta.port.number, pkt_meta.vlan.vid))) return None return pkt_meta def update_config_metrics(self): """Update gauge/metrics for configuration.""" self.metrics.reset_dpid(self.base_prom_labels) for table_id, table in list(self.dp.tables_by_id.items()): self.metrics.faucet_config_table_names.labels( **dict(self.base_prom_labels, table_name=table.name)).set(table_id) def update_metrics(self, now, updated_port=None, rate_limited=False): """Update Gauge/metrics.""" if self._last_update_metrics_sec and rate_limited: if now - self._last_update_metrics_sec < self.dp.metrics_rate_limit_sec: return self._last_update_metrics_sec = now def _update_vlan(vlan): vlan_labels = dict(self.base_prom_labels, vlan=vlan.vid) self.metrics.vlan_hosts_learned.labels( **vlan_labels).set(vlan.hosts_count()) self.metrics.vlan_learn_bans.labels( **vlan_labels).set(vlan.dyn_learn_ban_count) for ipv in vlan.ipvs(): self.metrics.vlan_neighbors.labels( **dict(vlan_labels, ipv=ipv)).set(vlan.neigh_cache_count_by_ipv(ipv)) def _update_port(vlan, port): port_labels = dict(self.base_prom_labels, port=port.number) port_vlan_labels = dict(self.base_prom_labels, vlan=vlan.vid, port=port.number) port_vlan_hosts_learned = port.hosts_count(vlans=[vlan]) self.metrics.port_vlan_hosts_learned.labels( **port_vlan_labels).set(port_vlan_hosts_learned) self.metrics.port_learn_bans.labels( **port_labels).set(port.dyn_learn_ban_count) highwater = self._port_highwater[vlan.vid][port.number] if highwater > port_vlan_hosts_learned: for i in range(port_vlan_hosts_learned, highwater + 1): self.metrics.learned_macs.labels( **dict(port_vlan_labels, n=i)).set(0) self._port_highwater[vlan.vid][port.number] = port_vlan_hosts_learned port_vlan_hosts = port.hosts(vlans=[vlan]) assert port_vlan_hosts_learned == len(port_vlan_hosts) # TODO: make MAC table updates less expensive. for i, entry in enumerate(sorted(port_vlan_hosts)): self.metrics.learned_macs.labels( **dict(port_vlan_labels, n=i)).set(entry.eth_src_int) if updated_port: for vlan in updated_port.vlans(): _update_vlan(vlan) _update_port(vlan, updated_port) else: for vlan in list(self.dp.vlans.values()): _update_vlan(vlan) for port in vlan.get_ports(): _update_port(vlan, port) def rcv_packet(self, now, other_valves, pkt_meta): """Handle a packet from the dataplane (eg to re/learn a host). The packet may be sent to us also in response to FAUCET initiating IPv6 neighbor discovery, or ARP, to resolve a nexthop. Args: other_valves (list): all Valves other than this one. pkt_meta (PacketMeta): packet for control plane. Return: list: OpenFlow messages, if any. """ ofmsgs = [] self.logger.debug( 'Packet_in src:%s in_port:%d VLAN:%s' % ( pkt_meta.eth_src, pkt_meta.port.number, pkt_meta.vlan)) if pkt_meta.vlan is None: self.metrics.of_non_vlan_packet_ins.labels( # pylint: disable=no-member **self.base_prom_labels).inc() if pkt_meta.port.lacp: lacp_ofmsgs = self.lacp_handler(now, pkt_meta) if lacp_ofmsgs: return lacp_ofmsgs self.lldp_handler(now, pkt_meta) # TODO: verify LLDP message (e.g. org-specific authenticator TLV) return ofmsgs self.metrics.of_vlan_packet_ins.labels( # pylint: disable=no-member **self.base_prom_labels).inc() ban_rules = self.host_manager.ban_rules(pkt_meta) if ban_rules: return ban_rules if pkt_meta.eth_type in self._route_manager_by_eth_type: route_manager = self._route_manager_by_eth_type[pkt_meta.eth_type] if route_manager.active: pkt_meta.reparse_ip() if pkt_meta.l3_pkt: control_plane_ofmsgs = self._control_plane_handler(now, pkt_meta, route_manager) if control_plane_ofmsgs: ofmsgs.extend(control_plane_ofmsgs) else: ofmsgs.extend(route_manager.add_host_fib_route_from_pkt(now, pkt_meta)) ofmsgs.extend(self._learn_host(now, other_valves, pkt_meta)) return ofmsgs def _lacp_state_expire(self, vlan, now): """Expire controller state for LACP. Args: vlan (VLAN instance): VLAN with LAGs. now (float): current epoch time. Return: list: OpenFlow messages, if any. """ ofmsgs = [] for ports in list(vlan.lags().values()): lacp_up_ports = [port for port in ports if port.dyn_lacp_up] for port in lacp_up_ports: lacp_age = now - port.dyn_lacp_updated_time if lacp_age > self.dp.lacp_timeout: self.logger.info('LACP on %s expired' % port) ofmsgs.extend(self.lacp_down(port)) return ofmsgs def state_expire(self, now): """Expire controller caches/state (e.g. hosts learned). Expire state from the host manager only; the switch does its own flow expiry. Return: list: OpenFlow messages, if any. """ ofmsgs = [] if self.dp.running: for vlan in list(self.dp.vlans.values()): expired_hosts = self.host_manager.expire_hosts_from_vlan(vlan, now) for entry in expired_hosts: self._notify( {'L2_EXPIRE': { 'port_no': entry.port.number, 'vid': vlan.vid, 'eth_src': entry.eth_src}}) self._lacp_state_expire(vlan, now) return ofmsgs def _apply_config_changes(self, new_dp, changes): """Apply any detected configuration changes. Args: new_dp: (DP): new dataplane configuration. changes (tuple) of: deleted_ports (list): deleted port numbers. changed_ports (list): changed/added port numbers. changed_acl_ports (set): changed ACL only port numbers. deleted_vlans (list): deleted VLAN IDs. changed_vlans (list): changed/added VLAN IDs. all_ports_changed (bool): True if all ports changed. Returns: tuple: cold_start (bool): whether cold starting. ofmsgs (list): OpenFlow messages. """ new_dp.running = True (deleted_ports, changed_ports, changed_acl_ports, deleted_vlans, changed_vlans, all_ports_changed) = changes if all_ports_changed: self.logger.info('all ports changed') self.dp = new_dp self.dp_init() return True, [] ofmsgs = [] if deleted_ports: self.logger.info('ports deleted: %s' % deleted_ports) ofmsgs.extend(self.ports_delete(deleted_ports)) if deleted_vlans: self.logger.info('VLANs deleted: %s' % deleted_vlans) for vid in deleted_vlans: vlan = self.dp.vlans[vid] ofmsgs.extend(self._del_vlan(vlan)) if changed_ports: self.logger.info('ports changed/added: %s' % changed_ports) ofmsgs.extend(self.ports_delete(changed_ports)) self.dp = new_dp self.dp.reset_refs() self.dp_init() if changed_vlans: self.logger.info('VLANs changed/added: %s' % changed_vlans) for vid in changed_vlans: vlan = self.dp.vlans[vid] ofmsgs.extend(self._del_vlan(vlan)) ofmsgs.extend(self._add_vlan(vlan)) if changed_ports: ofmsgs.extend(self.ports_add(changed_ports)) if changed_acl_ports: self.logger.info('ports with ACL only changed: %s' % changed_acl_ports) for port_num in changed_acl_ports: port = self.dp.ports[port_num] ofmsgs.extend(self._port_add_acl(port, cold_start=True)) return False, ofmsgs def reload_config(self, now, new_dp): """Reload configuration new_dp. Following config changes are currently supported: - Port config: support all available configs (e.g. native_vlan, acl_in) & change operations (add, delete, modify) a port - ACL config:support any modification, currently reload all rules belonging to an ACL - VLAN config: enable, disable routing, etc... Args: now (float): current epoch time. new_dp (DP): new dataplane configuration. Returns: ofmsgs (list): OpenFlow messages. """ dp_running = self.dp.running up_ports = self.dp.dyn_up_ports cold_start, ofmsgs = self._apply_config_changes( new_dp, self.dp.get_config_changes(self.logger, new_dp)) self.dp.running = dp_running restart_type = 'none' if self.dp.running: if cold_start: # Need to reprovision pipeline on cold start. ofmsgs = self.switch_features(None) + self.datapath_connect(now, up_ports) if ofmsgs: if cold_start: self.metrics.faucet_config_reload_cold.labels( # pylint: disable=no-member **self.base_prom_labels).inc() self.logger.info('Cold starting') restart_type = 'cold' else: self.metrics.faucet_config_reload_warm.labels( # pylint: disable=no-member **self.base_prom_labels).inc() self.logger.info('Warm starting') restart_type = 'warm' else: ofmsgs = [] self._notify({'CONFIG_CHANGE': {'restart_type': restart_type}}) return ofmsgs @staticmethod def _add_faucet_vips(route_manager, vlan, faucet_vips): ofmsgs = [] for faucet_vip in faucet_vips: ofmsgs.extend(route_manager.add_faucet_vip(vlan, faucet_vip)) return ofmsgs def add_authed_mac(self, port_num, mac): """Add authed mac address""" # TODO: track dynamic auth state. ofmsg = self.dp.tables['port_acl'].flowmod( self.dp.tables['port_acl'].match( in_port=port_num, eth_src=mac), priority=self.dp.highest_priority, inst=[valve_of.goto_table(self.dp.tables['vlan'])]) return [ofmsg] def add_route(self, vlan, ip_gw, ip_dst): """Add route to VLAN routing table.""" route_manager = self._route_manager_by_ipv[ip_dst.version] return route_manager.add_route(vlan, ip_gw, ip_dst) def del_route(self, vlan, ip_dst): """Delete route from VLAN routing table.""" route_manager = self._route_manager_by_ipv[ip_dst.version] return route_manager.del_route(vlan, ip_dst) def resolve_gateways(self, now): """Call route managers to re/resolve gateways. Returns: list: OpenFlow messages, if any. """ if not self.dp.running: return [] ofmsgs = [] for vlan in list(self.dp.vlans.values()): for route_manager in list(self._route_manager_by_ipv.values()): ofmsgs.extend(route_manager.resolve_gateways(vlan, now)) return ofmsgs def oferror(self, msg): """Correlate OFError message with flow we sent, if any. Args: msg (ryu.controller.ofp_event.EventOFPMsgBase): message from datapath. """ self.metrics.of_errors.labels( # pylint: disable=no-member **self.base_prom_labels).inc() orig_msgs = [orig_msg for orig_msg in self.recent_ofmsgs if orig_msg.xid == msg.xid] error_txt = msg if orig_msgs: error_txt = orig_msgs[0] self.logger.error('OFError %s' % error_txt) def prepare_send_flows(self, flow_msgs): """Prepare to send flows to datapath. Args: flow_msgs (list): OpenFlow messages to send. """ reordered_flow_msgs = valve_of.valve_flowreorder( flow_msgs, use_barriers=self.USE_BARRIERS) self.ofchannel_log(reordered_flow_msgs) self.metrics.of_flowmsgs_sent.labels( # pylint: disable=no-member **self.base_prom_labels).inc(len(reordered_flow_msgs)) self.recent_ofmsgs.extend(reordered_flow_msgs) return reordered_flow_msgs def send_flows(self, ryu_dp, flow_msgs): """Send flows to datapath. Args: ryu_dp (ryu.controller.controller.Datapath): datapath. flow_msgs (list): OpenFlow messages to send. """ for flow_msg in self.prepare_send_flows(flow_msgs): flow_msg.datapath = ryu_dp ryu_dp.send_msg(flow_msg) def flow_timeout(self, now, table_id, match): """Call flow timeout message handler: Args: now (float): current epoch time. table_id (int): ID of table where flow was installed. match (dict): match conditions for expired flow. Returns: list: OpenFlow messages, if any. """ return self.host_manager.flow_timeout(now, table_id, match) def get_config_dict(self): """Return datapath config as a dict for experimental API.""" return self.dp.get_config_dict() class TfmValve(Valve): """Valve implementation that uses OpenFlow send table features messages.""" PIPELINE_CONF = 'tfm_pipeline.json' SKIP_VALIDATION_TABLES = () def _verify_pipeline_config(self, tfm): for tfm_table in tfm.body: table = self.dp.tables_by_id[tfm_table.table_id] if table.table_id in self.SKIP_VALIDATION_TABLES: continue if table.restricted_match_types is None: continue for prop in tfm_table.properties: if not (isinstance(prop, valve_of.parser.OFPTableFeaturePropOxm) and prop.type == 8): continue tfm_matches = set(sorted([oxm.type for oxm in prop.oxm_ids])) if tfm_matches != table.restricted_match_types: self.logger.info( 'table %s ID %s match TFM config %s != pipeline %s' % ( tfm_table.name, tfm_table.table_id, tfm_matches, table.restricted_match_types)) def switch_features(self, msg): ofmsgs = self._delete_all_valve_flows() ofmsgs.extend(super(TfmValve, self).switch_features(msg)) ryu_table_loader = tfm_pipeline.LoadRyuTables( self.dp.pipeline_config_dir, self.PIPELINE_CONF) self.logger.info('loading pipeline configuration') active_table_ids = [table.table_id for table in self._active_tables()] tfm = valve_of.table_features( ryu_table_loader.load_tables(active_table_ids)) self._verify_pipeline_config(tfm) ofmsgs.append(tfm) return ofmsgs class ArubaValve(TfmValve): """Valve implementation that uses OpenFlow send table features messages.""" PIPELINE_CONF = 'aruba_pipeline.json' DEC_TTL = False class CiscoC9KValve(TfmValve): """Valve implementation that uses OpenFlow send table features messages.""" PIPELINE_CONF = 'cisco_c9k_pipeline.json' class OVSValve(Valve): """Valve implementation for OVS.""" USE_BARRIERS = False class AlliedTelesis(OVSValve): """Valve implementation for AT.""" DEC_TTL = False SUPPORTED_HARDWARE = { 'Allied-Telesis': AlliedTelesis, 'Aruba': ArubaValve, 'CiscoC9K': CiscoC9KValve, 'GenericTFM': TfmValve, 'Lagopus': Valve, 'Netronome': Valve, 'NoviFlow': Valve, 'Open vSwitch': OVSValve, 'ZodiacFX': Valve, } def valve_factory(dp): """Return a Valve object based dp's hardware configuration field. Args: dp (DP): DP instance with the configuration for this Valve. """ if dp.hardware in SUPPORTED_HARDWARE: return SUPPORTED_HARDWARE[dp.hardware] return None
apache-2.0
3,192,262,531,037,498,000
40.245703
117
0.568468
false
Homegateway/SDTTool
sdtv3/SDT3PrintSDT4.py
1
7637
# SDT2PrintSDT4.py # # Print SDT4 to SDT4 from .SDT3Classes import * from common.SDTHelper import decTab, incTab, newLine # # Print functions # def print2DomainSDT4(domain, options): result = printXMLHeader(domain) incTab() result += r(printIncludes(domain.includes)) if len(domain.includes) > 0 else '' result += r(printModuleClasses(domain.modules)) if len(domain.modules) > 0 else '' result += r(printDevices(domain.devices)) if len(domain.devices) > 0 else '' decTab() result += r(printXMLFooter()) return result def printXMLHeader(domain): result = '<?xml version="1.0" encoding="iso-8859-1"?>' result += r('<Domain xmlns="http://www.onem2m.org/xml/sdt/4.0"') incTab() result += r('xmlns:xi="http://www.w3.org/2001/XInclude"') result += r('id="' + domain.id + '">') decTab() return result def printXMLFooter(): return '</Domain>' def printIncludes(includes): return _printList(includes, 'Imports', lambda x: r('<xi:include href="' + x.href + '" parse="' + x.parse + '" />')) # # Devices, SubDevices # def printDevices(devices): return _printList(devices, 'DeviceClasses', printDevice) def printDevice(device): result = r('<DeviceClass id="' + device.id + '">') incTab() result += r(printDoc(device.doc)) if device.doc else '' result += printProperties(device.properties) if len(device.properties) > 0 else '' result += printModuleClasses(device.modules) if len(device.modules) > 0 else '' result += _printList(device.subDevices, 'SubDevices', printSubDevice) decTab() result += r('</DeviceClass>') return result def printSubDevice(subDevice): result = r('<SubDevice id="' + subDevice.id + '">') incTab() result += r(printDoc(subDevice.doc)) if subDevice.doc else '' result += printProperties(subDevice.properties) if len(subDevice.properties) > 0 else '' result += printModuleClasses(subDevice.modules) if len(subDevice.modules) > 0 else '' decTab() result += r('</SubDevice>') return result # # DeviceInfo # def printProperties(properties): return _printList(properties, 'Properties', printProperty) def printProperty(property): result += r('<Property name="' + property.name + '"') result += ' optional="true"' if property.optional is not None and property.optional == 'true' else '' result += ' value="'+ property.value + '"' if property.value else '' result += '>' incTab() result += r(printDoc(property.doc)) if property.doc else '' result += r(printSimpleType(property.type)) decTab() result += newLine() + '</Property>' # # ModuleClass # def printModuleClasses(moduleClasses): return _printList(moduleClasses, 'ModuleClasses', printModuleClass) def printModuleClass(moduleClass): result = r('<ModuleClass name="' + moduleClass.name + '"') result += ' optional="true"' if moduleClass.optional is not None and moduleClass.optional == 'true' else '' result += '>' incTab() result += r(printDoc(moduleClass.doc)) if moduleClass.doc != None else '' result += r('<Extend domain="' + moduleClass.extends.domain + '" entity="' + moduleClass.extends.clazz + '"/>') if moduleClass.extends != None else '' result += _printList(moduleClass.actions, 'Actions', printAction) result += _printList(moduleClass.data, 'Data', printDataPoint) result += _printList(moduleClass.events, 'Events', printEvent) decTab() result += r('</ModuleClass>') return result # # Action, Argument # def printAction(action): result = r('<Action name="' + action.name + '"') result += ' optional="true"' if action.optional is not None and action.optional == 'true' else '' result += '>' incTab() result += r(printDoc(action.doc)) if action.doc != None else '' result += r(printDataType(action.type)) if action.type != None else '' result += _printList(action.args, 'Args', printArgument) decTab() result += r('</Action>') return result def printArgument(action): result = r('<Arg name="' + action.name + '">') incTab(); result += r(printDataType(action.type)) if (action.type) else '' decTab() result += r('</Arg>') return result # # Event # def printEvent(event): result = r('<Event name="' + event.name + '"') result += ' optional="true"' if module.optional is not None and module.optional == 'true' else '' result += '>' incTab() result += r(printDoc(event.doc)) if event.doc != None else '' result += _printList(event.data, 'Data', printDataPoint) decTab() result += r('</Event>') return result # # DataPoint # def printDataPoint(datapoint): result = r('<DataPoint name="' + datapoint.name + '"') result += ' optional="true"' if datapoint.optional is not None and datapoint.optional == 'true' else '' result += ' writable="false"' if datapoint.writable is not None and datapoint.writable == 'false' else '' result += ' readable="false"' if datapoint.readable is not None and datapoint.readable == 'false' else '' result += ' eventable="true"' if datapoint.eventable is not None and datapoint.eventable == 'true' else '' result += '>' incTab() result += r(printDoc(datapoint.doc)) if datapoint.doc != None else '' result += r(printDataType(datapoint.type)) if datapoint.type != None else '' decTab() result += r('</DataPoint>') return result # # Print the data types # def printDataType(dataType): # special handling for oneM2M enum definitions up to v3 name = dataType.type.type if isinstance(dataType.type, SDT3SimpleType) and dataType.type.type.startswith('hd:') else dataType.name result = '<DataType' result += ' name="' + name + '"' if name is not None else '' result += ' unitOfMeasure="' + dataType.unitOfMeasure + '"' if dataType.unitOfMeasure else '' result += '>' incTab() result += r(printDoc(dataType.doc)) if dataType.doc != None else '' if isinstance(dataType.type, SDT3SimpleType): result += newLine() + printSimpleType(dataType.type) elif isinstance(dataType.type, SDT3StructType): result += newLine() + printStructType(dataType.type) elif isinstance(dataType.type, SDT3ArrayType): result += newLine() + printArrayType(dataType.type) result += _printList(dataType.constraints, 'Constraints', printConstraint) decTab() result += r('</DataType>') return result def printSimpleType(dataType): result = '<Simple type="' + dataType.type + '" />' # hack for oneM2M enums if dataType.type.startswith('hd:'): result = '<Enum>' incTab() result += r('<!-- TODO: Add enum values -->') result += r('<EnumValue name="name" value="1" />') decTab() result += r('</Enum>') return result def printStructType(dataType): result = '<Struct>' incTab() for element in dataType.type.structElements: result += newLine() + printDataType(element) decTab() result += '</Struct>' return result def printArrayType(dataType): result = '<Array>' incTab() result += r(printDataType(dataType.arrayType)) decTab() result += r('</Array>') return result def printConstraint(constraint): result = r('<Constraint name="' + containt.name + '"') result += ' type="' + constraint.type + '"' if constraint.type else '' result += ' value="' + constraint.value + '"' if constraint.value is not None else '' result += '>' incTab() result += r(printDoc(constraint.doc)) if constraint.doc != None else '' decTab() result += newLine() + '</Constraint>' return result # # Doc # def printDoc(doc): return '<Doc>' + doc.content.strip() + '</Doc>' # # misc functions to help printing results # def _printList(lst, element, func): result = '' if len(lst) > 0: result += '%s<%s>' % (newLine(), element) incTab() for l in lst: result += func(l) decTab() result += '%s</%s>' % (newLine(), element) return result def r(line): return '%s%s' % (newLine(), line)
apache-2.0
8,722,265,272,410,320,000
26.875912
151
0.675265
false
132nd-etcher/EMFT
emft/miz/miz.py
1
9797
# coding=utf-8 import tempfile from filecmp import dircmp from os.path import exists, join from zipfile import BadZipFile, ZipFile, ZipInfo from emft.core.constant import ENCODING from emft.core.logging import make_logger from emft.core.path import Path from emft.core.progress import Progress from emft.core.sltp import SLTP from emft.miz.mission import Mission from emft.resources.dummy_miz import dummy_miz LOGGER = make_logger('miz') # noinspection PyAbstractClass class MizPath(Path): def __init__(self, path): Path.__init__(self, path) if not self.exists(): raise FileNotFoundError(path) if not self.isfile(): raise TypeError(path) if not self.ext == '.miz': raise ValueError(path) class Miz: def __init__(self, path_to_miz_file, temp_dir=None, keep_temp_dir: bool = False, overwrite: bool = False): self.miz_path = Path(path_to_miz_file) if not self.miz_path.exists(): raise FileNotFoundError(path_to_miz_file) if not self.miz_path.isfile(): raise TypeError(path_to_miz_file) if not self.miz_path.ext == '.miz': raise ValueError(path_to_miz_file) if temp_dir is not None: raise PendingDeprecationWarning() self.keep_temp_dir = keep_temp_dir self.overwrite = overwrite self.tmpdir = Path(tempfile.mkdtemp('EMFT_')) LOGGER.debug('temporary directory: {}'.format(self.tmpdir.abspath())) self.zip_content = None self._mission = None self._mission_qual = None self._l10n = None self._l10n_qual = None self._map_res = None self._map_res_qual = None def __enter__(self): LOGGER.debug('instantiating new Mission object as a context') self.unzip(self.overwrite) self._decode() return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: LOGGER.error('there were error with this mission, keeping temp dir at "{}" and re-raising'.format( self.tmpdir.abspath())) LOGGER.error('{}\n{}'.format(exc_type, exc_val)) return False else: LOGGER.debug('closing Mission object context') if not self.keep_temp_dir: LOGGER.debug('removing temp dir: {}'.format(self.tmpdir.abspath())) self.tmpdir.rmtree() @property def mission_file(self): return self.tmpdir.joinpath('mission') @property def dictionary_file(self): return self.tmpdir.joinpath('l10n', 'DEFAULT', 'dictionary') @property def map_res_file(self): return self.tmpdir.joinpath('l10n', 'DEFAULT', 'mapResource') @property def mission(self) -> Mission: if self._mission is None: raise RuntimeError() return self._mission @property def l10n(self) -> dict: if self._l10n is None: raise RuntimeError() return self._l10n @property def map_res(self) -> dict: if self._map_res is None: raise RuntimeError() return self._map_res @staticmethod def reorder(miz_file_path, target_dir, skip_options_file): LOGGER.debug('re-ordering miz file: {}'.format(miz_file_path)) LOGGER.debug('destination folder: {}'.format(target_dir)) LOGGER.debug('{}option file'.format('skipping' if skip_options_file else 'including')) if not Path(target_dir).exists(): LOGGER.debug(f'creating directory {target_dir}') Path(target_dir).makedirs() with Miz(miz_file_path, overwrite=True) as m: def mirror_dir(src, dst): LOGGER.debug('{} -> {}'.format(src, dst)) diff_ = dircmp(src, dst, ignore) diff_list = diff_.left_only + diff_.diff_files LOGGER.debug('differences: {}'.format(diff_list)) for x in diff_list: source = Path(diff_.left).joinpath(x) target = Path(diff_.right).joinpath(x) LOGGER.debug('looking at: {}'.format(x)) if source.isdir(): LOGGER.debug('isdir: {}'.format(x)) if not target.exists(): LOGGER.debug('creating: {}'.format(x)) target.mkdir() mirror_dir(source, target) else: LOGGER.debug('copying: {}'.format(x)) source.copy2(diff_.right) for sub in diff_.subdirs.values(): assert isinstance(sub, dircmp) mirror_dir(sub.left, sub.right) m._encode() if skip_options_file: ignore = ['options'] else: ignore = [] mirror_dir(m.tmpdir, target_dir) def _decode(self): LOGGER.debug('decoding lua tables') if not self.zip_content: self.unzip(overwrite=False) Progress.start('Decoding MIZ file', length=3) Progress.set_label('Decoding map resource') LOGGER.debug('reading map resource file') with open(self.map_res_file, encoding=ENCODING) as f: self._map_res, self._map_res_qual = SLTP().decode(f.read()) Progress.set_value(1) Progress.set_label('Decoding dictionary file') LOGGER.debug('reading l10n file') with open(self.dictionary_file, encoding=ENCODING) as f: self._l10n, self._l10n_qual = SLTP().decode(f.read()) Progress.set_value(2) Progress.set_label('Decoding mission file') LOGGER.debug('reading mission file') with open(self.mission_file, encoding=ENCODING) as f: mission_data, self._mission_qual = SLTP().decode(f.read()) self._mission = Mission(mission_data, self._l10n) Progress.set_value(3) LOGGER.debug('decoding done') def _encode(self): LOGGER.debug('encoding lua tables') Progress.start('Encoding MIZ file', length=3) Progress.set_label('Encoding map resource') LOGGER.debug('encoding map resource') with open(self.map_res_file, mode='w', encoding=ENCODING) as f: f.write(SLTP().encode(self._map_res, self._map_res_qual)) Progress.set_value(1) Progress.set_label('Encoding l10n dictionary') LOGGER.debug('encoding l10n dictionary') with open(self.dictionary_file, mode='w', encoding=ENCODING) as f: f.write(SLTP().encode(self.l10n, self._l10n_qual)) Progress.set_value(2) Progress.set_label('Encoding mission dictionary') LOGGER.debug('encoding mission dictionary') with open(self.mission_file, mode='w', encoding=ENCODING) as f: f.write(SLTP().encode(self.mission.d, self._mission_qual)) Progress.set_value(3) LOGGER.debug('encoding done') def _check_extracted_content(self): for filename in self.zip_content: p = self.tmpdir.joinpath(filename) if not p.exists(): raise FileNotFoundError(p.abspath()) def _extract_files_from_zip(self, zip_file): for item in zip_file.infolist(): # not using ZipFile.extractall() for security reasons assert isinstance(item, ZipInfo) LOGGER.debug('unzipping item: {}'.format(item.filename)) try: zip_file.extract(item, self.tmpdir.abspath()) except: LOGGER.error('failed to extract archive member: {}'.format(item.filename)) raise def unzip(self, overwrite: bool = False): if self.zip_content and not overwrite: raise FileExistsError(self.tmpdir.abspath()) LOGGER.debug('unzipping miz to temp dir') try: with ZipFile(self.miz_path.abspath()) as zip_file: LOGGER.debug('reading infolist') self.zip_content = [f.filename for f in zip_file.infolist()] self._extract_files_from_zip(zip_file) except BadZipFile: raise BadZipFile(self.miz_path.abspath()) except: LOGGER.exception('error while unzipping miz file: {}'.format(self.miz_path.abspath())) raise LOGGER.debug('checking miz content') # noinspection PyTypeChecker for miz_item in map( join, [self.tmpdir.abspath()], [ 'mission', 'options', 'warehouses', 'l10n/DEFAULT/dictionary', 'l10n/DEFAULT/mapResource' ] ): if not exists(miz_item): LOGGER.error('missing file in miz: {}'.format(miz_item)) raise FileNotFoundError(miz_item) self._check_extracted_content() LOGGER.debug('all files have been found, miz successfully unzipped') def zip(self, destination=None): self._encode() if destination is None: destination = Path(self.miz_path.dirname()).joinpath('{}_EMFT.miz'.format(self.miz_path.namebase)) destination = Path(destination).abspath() LOGGER.debug('zipping mission to: {}'.format(destination)) with open(destination, mode='wb') as f: f.write(dummy_miz) with ZipFile(destination, mode='w', compression=8) as _z: for f in self.zip_content: abs_path = self.tmpdir.joinpath(f).abspath() LOGGER.debug('injecting in zip file: {}'.format(abs_path)) _z.write(abs_path, arcname=f) return destination
gpl-3.0
6,541,689,551,129,313,000
31.541528
110
0.57417
false
childresslab/MicrocavityExp1
hardware/fpga_fastcounter/fast_counter_fpga_pi3.py
1
7991
# -*- coding: utf-8 -*- """ A hardware module for communicating with the fast counter FPGA. Qudi 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. Qudi 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 Qudi. If not, see <http://www.gnu.org/licenses/>. Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/> """ import numpy as np import os import thirdparty.stuttgart_counter.TimeTagger as tt from core.module import Base, ConfigOption from interface.fast_counter_interface import FastCounterInterface class FastCounterFGAPiP3(Base, FastCounterInterface): _modclass = 'FastCounterFGAPiP3' _modtype = 'hardware' # config options _fpgacounter_serial = ConfigOption('fpgacounter_serial', missing='error') _channel_apd_0 = ConfigOption('fpgacounter_channel_apd_0', 1, missing='warn') _channel_apd_1 = ConfigOption('fpgacounter_channel_apd_1', 3, missing='warn') _channel_detect = ConfigOption('fpgacounter_channel_detect', 2, missing='warn') _channel_sequence = ConfigOption('fpgacounter_channel_sequence', 6, missing='warn') def on_activate(self): """ Connect and configure the access to the FPGA. """ tt._Tagger_setSerial(self._fpgacounter_serial) thirdpartypath = os.path.join(self.get_main_dir(), 'thirdparty') bitfilepath = os.path.join(thirdpartypath, 'stuttgart_counter', 'TimeTaggerController.bit') tt._Tagger_setBitfilePath(bitfilepath) del bitfilepath, thirdpartypath self._number_of_gates = int(100) self._bin_width = 1 self._record_length = int(4000) self.configure( self._bin_width * 1e-9, self._record_length * 1e-9, self._number_of_gates) self.statusvar = 0 def get_constraints(self): """ Retrieve the hardware constrains from the Fast counting device. @return dict: dict with keys being the constraint names as string and items are the definition for the constaints. The keys of the returned dictionary are the str name for the constraints (which are set in this method). NO OTHER KEYS SHOULD BE INVENTED! If you are not sure about the meaning, look in other hardware files to get an impression. If still additional constraints are needed, then they have to be added to all files containing this interface. The items of the keys are again dictionaries which have the generic dictionary form: {'min': <value>, 'max': <value>, 'step': <value>, 'unit': '<value>'} Only the key 'hardware_binwidth_list' differs, since they contain the list of possible binwidths. If the constraints cannot be set in the fast counting hardware then write just zero to each key of the generic dicts. Note that there is a difference between float input (0.0) and integer input (0), because some logic modules might rely on that distinction. ALL THE PRESENT KEYS OF THE CONSTRAINTS DICT MUST BE ASSIGNED! """ constraints = dict() # the unit of those entries are seconds per bin. In order to get the # current binwidth in seonds use the get_binwidth method. constraints['hardware_binwidth_list'] = [1 / 1000e6] # TODO: think maybe about a software_binwidth_list, which will # postprocess the obtained counts. These bins must be integer # multiples of the current hardware_binwidth return constraints def on_deactivate(self): """ Deactivate the FPGA. """ if self.getState() == 'locked': self.pulsed.stop() self.pulsed.clear() self.pulsed = None def configure(self, bin_width_s, record_length_s, number_of_gates=0): """ Configuration of the fast counter. @param float bin_width_s: Length of a single time bin in the time trace histogram in seconds. @param float record_length_s: Total length of the timetrace/each single gate in seconds. @param int number_of_gates: optional, number of gates in the pulse sequence. Ignore for not gated counter. @return tuple(binwidth_s, gate_length_s, number_of_gates): binwidth_s: float the actual set binwidth in seconds gate_length_s: the actual set gate length in seconds number_of_gates: the number of gated, which are accepted """ self._number_of_gates = number_of_gates self._bin_width = bin_width_s * 1e9 self._record_length = int(record_length_s / bin_width_s) self.statusvar = 1 self.pulsed = tt.Pulsed( self._record_length, int(np.round(self._bin_width*1000)), self._number_of_gates, self._channel_apd_0, self._channel_detect, self._channel_sequence ) return (bin_width_s, record_length_s, number_of_gates) def start_measure(self): """ Start the fast counter. """ self.lock() self.pulsed.clear() self.pulsed.start() self.statusvar = 2 return 0 def stop_measure(self): """ Stop the fast counter. """ if self.getState() == 'locked': self.pulsed.stop() self.unlock() self.statusvar = 1 return 0 def pause_measure(self): """ Pauses the current measurement. Fast counter must be initially in the run state to make it pause. """ if self.getState() == 'locked': self.pulsed.stop() self.statusvar = 3 return 0 def continue_measure(self): """ Continues the current measurement. If fast counter is in pause state, then fast counter will be continued. """ if self.getState() == 'locked': self.pulsed.start() self.statusvar = 2 return 0 def is_gated(self): """ Check the gated counting possibility. Boolean return value indicates if the fast counter is a gated counter (TRUE) or not (FALSE). """ return True def get_data_trace(self): """ Polls the current timetrace data from the fast counter. @return numpy.array: 2 dimensional array of dtype = int64. This counter is gated the the return array has the following shape: returnarray[gate_index, timebin_index] The binning, specified by calling configure() in forehand, must be taken care of in this hardware class. A possible overflow of the histogram bins must be caught here and taken care of. """ return np.array(self.pulsed.getData(), dtype='int64') def get_status(self): """ Receives the current status of the Fast Counter and outputs it as return value. 0 = unconfigured 1 = idle 2 = running 3 = paused -1 = error state """ return self.statusvar def get_binwidth(self): """ Returns the width of a single timebin in the timetrace in seconds. """ width_in_seconds = self._bin_width * 1e-9 return width_in_seconds
gpl-3.0
-3,809,934,199,028,336,000
35.322727
99
0.620448
false
agnivesh/aft
aft.py
1
1983
import os import re from lib.adb import AndroidDebugBridge import string from lib.read_db import * adb = AndroidDebugBridge() def main(): dir = raw_input("Enter the location at which the workspace is to be created: ") if not os.path.exists(dir): os.makedirs(dir) os.makedirs("%s/database" % dir) os.makedirs("%s/photos" % dir) os.makedirs("%s/reports" % dir) db = dir + "/database" photo = dir + "/photos" report = dir + "/reports" aphoto = "/mnt/sdcard/DCIM/Camera/" result = adb.get_state() result = result.strip('\n') if result == "unknown": print "Not able to access device. Please check whether the device is connected properly and USB debugging mode is enabled" print "Extracting databases:" print "Extracting accounts.db" adb.pull('/data/system/accounts.db',db) print "Extracting mmssms.db" adb.pull('/data/data/com.android.providers.telephony/databases/mmssms.db',db) print "Extracting contacts2.db" adb.pull('/data/data/com.android.providers.contacts/databases/contacts2.db',db) print "Extracting webviewCache.db" adb.pull('/data/data/com.android.browser/databases/webviewCache.db',db) print "Extracting webview.db" adb.pull('/data/data/com.android.browser/databases/webview.db',db) print "Extracting browser" adb.pull('/data/data/com.android.browser/databases/browser.db',db) print "Extracting telephony.db" adb.pull('/data/data/com.android.providers.telephony/databases/telephony.db',db) print "\nExtracting photos:" result = adb.shell("ls /mnt/sdcard/DCIM/Camera") f = open ("%s/list.txt" % photo, 'w') f.write(result) f.close() regex = r'\S[^\r\n\t]*\.jpg' f = open("%s/list.txt" % photo,'r') content = f.read() fList = content.strip().split() regex = r'\S[^\r\n\t]*\.jpg' for x in range(0,len(fList)): if re.search(regex,fList[x]): adb.pull('/mnt/sdcard/DCIM/Camera/%s' % fList[x], photo) read_account(db, report) read_history(db, report) read_mmssms (db,report) if __name__ == "__main__": main()
mit
-5,867,725,327,053,168,000
28.61194
124
0.697932
false
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/aio/operations/_express_route_cross_connections_operations.py
1
43496
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ExpressRouteCrossConnectionsOperations: """ExpressRouteCrossConnectionsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2020_04_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs ) -> AsyncIterable["_models.ExpressRouteCrossConnectionListResult"]: """Retrieves all the ExpressRouteCrossConnections in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExpressRouteCrossConnectionListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnectionListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ExpressRouteCrossConnectionListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCrossConnections'} # type: ignore def list_by_resource_group( self, resource_group_name: str, **kwargs ) -> AsyncIterable["_models.ExpressRouteCrossConnectionListResult"]: """Retrieves all the ExpressRouteCrossConnections in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExpressRouteCrossConnectionListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnectionListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ExpressRouteCrossConnectionListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections'} # type: ignore async def get( self, resource_group_name: str, cross_connection_name: str, **kwargs ) -> "_models.ExpressRouteCrossConnection": """Gets details about the specified ExpressRouteCrossConnection. :param resource_group_name: The name of the resource group (peering location of the circuit). :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection (service key of the circuit). :type cross_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteCrossConnection, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteCrossConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, cross_connection_name: str, parameters: "_models.ExpressRouteCrossConnection", **kwargs ) -> "_models.ExpressRouteCrossConnection": cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ExpressRouteCrossConnection') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteCrossConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, cross_connection_name: str, parameters: "_models.ExpressRouteCrossConnection", **kwargs ) -> AsyncLROPoller["_models.ExpressRouteCrossConnection"]: """Update the specified ExpressRouteCrossConnection. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection. :type cross_connection_name: str :param parameters: Parameters supplied to the update express route crossConnection operation. :type parameters: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteCrossConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnection"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, cross_connection_name=cross_connection_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteCrossConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}'} # type: ignore async def update_tags( self, resource_group_name: str, cross_connection_name: str, cross_connection_parameters: "_models.TagsObject", **kwargs ) -> "_models.ExpressRouteCrossConnection": """Updates an express route cross connection tags. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the cross connection. :type cross_connection_name: str :param cross_connection_parameters: Parameters supplied to update express route cross connection tags. :type cross_connection_parameters: ~azure.mgmt.network.v2020_04_01.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteCrossConnection, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_tags.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(cross_connection_parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteCrossConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}'} # type: ignore async def _list_arp_table_initial( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> Optional["_models.ExpressRouteCircuitsArpTableListResult"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ExpressRouteCircuitsArpTableListResult"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" # Construct URL url = self._list_arp_table_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ExpressRouteCircuitsArpTableListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _list_arp_table_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/arpTables/{devicePath}'} # type: ignore async def begin_list_arp_table( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> AsyncLROPoller["_models.ExpressRouteCircuitsArpTableListResult"]: """Gets the currently advertised ARP table associated with the express route cross connection in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection. :type cross_connection_name: str :param peering_name: The name of the peering. :type peering_name: str :param device_path: The path of the device. :type device_path: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteCircuitsArpTableListResult or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitsArpTableListResult] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCircuitsArpTableListResult"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._list_arp_table_initial( resource_group_name=resource_group_name, cross_connection_name=cross_connection_name, peering_name=peering_name, device_path=device_path, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteCircuitsArpTableListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_list_arp_table.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/arpTables/{devicePath}'} # type: ignore async def _list_routes_table_summary_initial( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> Optional["_models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" # Construct URL url = self._list_routes_table_summary_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ExpressRouteCrossConnectionsRoutesTableSummaryListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _list_routes_table_summary_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTablesSummary/{devicePath}'} # type: ignore async def begin_list_routes_table_summary( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> AsyncLROPoller["_models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult"]: """Gets the route table summary associated with the express route cross connection in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection. :type cross_connection_name: str :param peering_name: The name of the peering. :type peering_name: str :param device_path: The path of the device. :type device_path: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteCrossConnectionsRoutesTableSummaryListResult or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._list_routes_table_summary_initial( resource_group_name=resource_group_name, cross_connection_name=cross_connection_name, peering_name=peering_name, device_path=device_path, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteCrossConnectionsRoutesTableSummaryListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_list_routes_table_summary.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTablesSummary/{devicePath}'} # type: ignore async def _list_routes_table_initial( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> Optional["_models.ExpressRouteCircuitsRoutesTableListResult"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ExpressRouteCircuitsRoutesTableListResult"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" # Construct URL url = self._list_routes_table_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ExpressRouteCircuitsRoutesTableListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _list_routes_table_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTables/{devicePath}'} # type: ignore async def begin_list_routes_table( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> AsyncLROPoller["_models.ExpressRouteCircuitsRoutesTableListResult"]: """Gets the currently advertised routes table associated with the express route cross connection in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection. :type cross_connection_name: str :param peering_name: The name of the peering. :type peering_name: str :param device_path: The path of the device. :type device_path: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteCircuitsRoutesTableListResult or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitsRoutesTableListResult] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCircuitsRoutesTableListResult"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._list_routes_table_initial( resource_group_name=resource_group_name, cross_connection_name=cross_connection_name, peering_name=peering_name, device_path=device_path, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteCircuitsRoutesTableListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_list_routes_table.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTables/{devicePath}'} # type: ignore
mit
-5,138,406,576,697,690,000
51.850547
277
0.660176
false
rudhir-upretee/Sumo17_With_Netsim
tools/output/analyze_teleports.py
1
2664
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @file analyze_teleports.py @author Jakob Erdmann @date 2012-11-20 @version $Id: analyze_teleports.py 13811 2013-05-01 20:31:43Z behrisch $ Extract statistics from the warning outputs of a simulation run for plotting. SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ Copyright (C) 2008-2013 DLR (http://www.dlr.de/) and contributors All rights reserved """ import os,sys import re from collections import defaultdict def parse_log(logfile, edges=True, aggregate=3600): print "Parsing %s" % logfile reFrom = re.compile("lane='([^']*)'") reTime = re.compile("time=(\d*)\.") # counts per lane waitingCounts = defaultdict(lambda:0) collisionCounts = defaultdict(lambda:0) # counts per step waitingStepCounts = defaultdict(lambda:0) collisionStepCounts = defaultdict(lambda:0) for line in open(logfile): try: if "Warning: Teleporting vehicle" in line: edge = reFrom.search(line).group(1) time = reTime.search(line).group(1) if edges: edge = edge[:-2] if "collision" in line: collisionCounts[edge] += 1 collisionStepCounts[int(time) / aggregate] += 1 else: waitingCounts[edge] += 1 waitingStepCounts[int(time) / aggregate] += 1 except: print sys.exc_info() sys.exit("error when parsing line '%s'" % line) return (waitingCounts, collisionCounts, waitingStepCounts, collisionStepCounts) def print_counts(countDict, label): counts = [(v,k) for k,v in countDict.items()] counts.sort() print counts print label, 'total:', sum(countDict.values()) def main(logfile): waitingCounts, collisionCounts, waitingStepCounts, collisionStepCounts = parse_log(logfile) print_counts(waitingCounts, 'waiting') print_counts(collisionCounts, 'collisions') # generate plot min_step = min(min(waitingStepCounts.keys()), min(collisionStepCounts.keys())) max_step = max(max(waitingStepCounts.keys()), max(collisionStepCounts.keys())) plotfile = logfile + '.plot' with open(plotfile, 'w') as f: f.write("# plot '%s' using 1:2 with lines title 'waiting', '%s' using 1:3 with lines title 'collisions'\n" % ( plotfile, plotfile)) for step in range(min_step, max_step + 1): print >>f, ' '.join(map(str,[step, waitingStepCounts[step], collisionStepCounts[step]])) if __name__ == "__main__": main(*sys.argv[1:])
gpl-3.0
-8,322,608,231,631,647,000
35
118
0.618994
false
priyawadhwa/runtimes-common
ftl/node/layer_builder.py
1
5885
# Copyright 2017 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. """This package implements the Node package layer builder.""" import logging import os import json import datetime from ftl.common import constants from ftl.common import ftl_util from ftl.common import ftl_error from ftl.common import single_layer_image from ftl.common import tar_to_dockerimage class LayerBuilder(single_layer_image.CacheableLayerBuilder): def __init__(self, ctx=None, descriptor_files=None, pkg_descriptor=None, directory=None, destination_path=constants.DEFAULT_DESTINATION_PATH, cache_key_version=None, cache=None): super(LayerBuilder, self).__init__() self._ctx = ctx self._descriptor_files = descriptor_files self._pkg_descriptor = pkg_descriptor self._directory = directory self._destination_path = destination_path self._cache_key_version = cache_key_version self._cache = cache def GetCacheKeyRaw(self): all_descriptor_contents = ftl_util.all_descriptor_contents( self._descriptor_files, self._ctx) cache_key = '%s %s' % (all_descriptor_contents, self._destination_path) return "%s %s" % (cache_key, self._cache_key_version) def BuildLayer(self): """Override.""" cached_img = None if self._cache: with ftl_util.Timing('checking_cached_packages_json_layer'): key = self.GetCacheKey() cached_img = self._cache.Get(key) self._log_cache_result(False if cached_img is None else True) if cached_img: self.SetImage(cached_img) else: with ftl_util.Timing('building_packages_json_layer'): self._build_layer() self._cleanup_build_layer() if self._cache: with ftl_util.Timing('uploading_packages_json_layer'): self._cache.Set(self.GetCacheKey(), self.GetImage()) def _build_layer(self): blob, u_blob = self._gen_npm_install_tar(self._pkg_descriptor, self._directory) self._img = tar_to_dockerimage.FromFSImage([blob], [u_blob], self._generate_overrides()) def _cleanup_build_layer(self): if self._directory: modules_dir = os.path.join(self._directory, "node_modules") rm_cmd = ['rm', '-rf', modules_dir] ftl_util.run_command('rm_node_modules', rm_cmd) def _gen_npm_install_tar(self, pkg_descriptor, app_dir): is_gcp_build = False if self._ctx and self._ctx.Contains(constants.PACKAGE_JSON): is_gcp_build = self._is_gcp_build( json.loads(self._ctx.GetFile(constants.PACKAGE_JSON))) if is_gcp_build: self._gcp_build(app_dir) else: npm_install_cmd = ['npm', 'install', '--production'] ftl_util.run_command( 'npm_install', npm_install_cmd, cmd_cwd=app_dir, err_type=ftl_error.FTLErrors.USER()) module_destination = os.path.join(self._destination_path, 'node_modules') modules_dir = os.path.join(self._directory, "node_modules") return ftl_util.zip_dir_to_layer_sha(modules_dir, module_destination) def _generate_overrides(self): overrides_dct = { 'created': str(datetime.date.today()) + "T00:00:00Z", } return overrides_dct def _is_gcp_build(self, package_json): scripts = package_json.get('scripts', {}) if scripts.get('gcp-build'): return True return False def _gcp_build(self, app_dir): env = os.environ.copy() env["NODE_ENV"] = "development" npm_install_cmd = ['npm', 'install'] ftl_util.run_command( 'npm_install', npm_install_cmd, app_dir, env, err_type=ftl_error.FTLErrors.USER()) npm_run_script_cmd = ['npm', 'run-script', 'gcp-build'] ftl_util.run_command( 'npm_run_script_gcp_build', npm_run_script_cmd, app_dir, env, err_type=ftl_error.FTLErrors.USER()) def _log_cache_result(self, hit): if self._pkg_descriptor: if hit: cache_str = constants.PHASE_2_CACHE_HIT else: cache_str = constants.PHASE_2_CACHE_MISS logging.info( cache_str.format( key_version=constants.CACHE_KEY_VERSION, language='NODE', package_name=self._pkg_descriptor[0], package_version=self._pkg_descriptor[1], key=self.GetCacheKey())) else: if hit: cache_str = constants.PHASE_1_CACHE_HIT else: cache_str = constants.PHASE_1_CACHE_MISS logging.info( cache_str.format( key_version=constants.CACHE_KEY_VERSION, language='NODE', key=self.GetCacheKey()))
apache-2.0
1,859,227,329,433,316,600
36.724359
79
0.564146
false
PayloadSecurity/VxAPI
helper_classes/cli_helper.py
1
3316
import datetime import traceback from colors import Color from constants import * class CliHelper: @staticmethod def print_call_info(cli_object): print(Color.control('Request was sent at ' + '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))) print('Endpoint URL: {}'.format(cli_object.api_object.get_full_endpoint_url())) print('HTTP Method: {}'.format(cli_object.api_object.request_method_name.upper())) print('Sent GET params: {}'.format(cli_object.api_object.params)) print('Sent POST params: {}'.format(cli_object.api_object.data)) print('Sent files: {}'.format(cli_object.api_object.files)) @staticmethod def print_error_info(e): print(Color.control('During the code execution, error has occurred. Please try again or contact the support.')) print(Color.error('Message: \'{}\'.').format(str(e)) + '\n') print(traceback.format_exc()) @staticmethod def prompt_for_sharing_confirmation(args, instance_url): if 'nosharevt' in args: if args['nosharevt'] == 'no' and args['quiet'] is False: warning_msg = 'You are about to submit your file to all users of {} and the public.'.format(instance_url) if 'hybrid-analysis.com' in instance_url: warning_msg += ' Please make sure you consent to the Terms and Conditions of Use and Data Privacy Policy available at: {} and {}.'.format('https://www.hybrid-analysis.com/terms', 'https://www.hybrid-analysis.com/data-protection-policy') warning_msg += ' [y/n]' submit_warning = input(warning_msg) if not submit_warning or submit_warning[0].lower() != 'y': print('You did not indicate approval, exiting ...') exit(1) @staticmethod def prompt_for_dir_content_submission(args): if args['chosen_action'] == ACTION_SUBMIT_FILE: number_of_files_to_submit = len(args['file']) if args['quiet'] is False and number_of_files_to_submit > 1: warning_msg = 'Are you sure that you want to submit the content of selected directory? It contains {} of files. [y/n]'.format(number_of_files_to_submit) submit_warning = input(warning_msg) if not submit_warning or submit_warning[0].lower() != 'y': print('You did not indicate approval, exiting ...') exit(1) @staticmethod def check_if_version_is_supported(args, api_instance_version_object, request_handler, headers, minimal_compatible_version): if args['quiet'] is False and 'hybrid-analysis.com' not in api_instance_version_object.server: api_instance_version_object.call(request_handler, headers) api_response = api_instance_version_object.get_api_response() if api_response.status_code == 200 and api_instance_version_object.get_response_msg_success_nature() is True: if api_instance_version_object.get_response_json()['response']['version'] < minimal_compatible_version: print(Color.warning('This version of VxAPI works best on VxWebService version {} (or above). Consider upgrading to ensure the flawless performance.'.format(minimal_compatible_version)))
gpl-3.0
-5,135,808,133,144,333,000
58.214286
256
0.637817
false
blockstack/blockstack-server
integration_tests/blockstack_integration_tests/scenarios/portal_test_env.py
1
3146
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Blockstack ~~~~~ copyright: (c) 2014-2015 by Halfmoon Labs, Inc. copyright: (c) 2016 by Blockstack.org This file is part of Blockstack Blockstack 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. Blockstack 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 Blockstack. If not, see <http://www.gnu.org/licenses/>. """ """ TEST ENV BLOCKSTACK_EPOCH_1_END_BLOCK 682 TEST ENV BLOCKSTACK_EPOCH_2_END_BLOCK 683 TEST ENV BLOCKSTACK_EPOCH_2_NAMESPACE_LIFETIME_MULTIPLIER 1 TEST ENV BLOCKSTACK_EPOCH_3_NAMESPACE_LIFETIME_MULTIPLIER 1 """ import testlib import virtualchain import time import json import sys import os wallets = [ testlib.Wallet( "5JesPiN68qt44Hc2nT8qmyZ1JDwHebfoh9KQ52Lazb1m1LaKNj9", 100000000000 ), testlib.Wallet( "5KHqsiU9qa77frZb6hQy9ocV7Sus9RWJcQGYYBJJBb2Efj1o77e", 100000000000 ), testlib.Wallet( "5Kg5kJbQHvk1B64rJniEmgbD83FpZpbw2RjdAZEzTefs9ihN3Bz", 100000000000 ), testlib.Wallet( "5JuVsoS9NauksSkqEjbUZxWwgGDQbMwPsEfoRBSpLpgDX1RtLX7", 100000000000 ), testlib.Wallet( "5KEpiSRr1BrT8vRD7LKGCEmudokTh1iMHbiThMQpLdwBwhDJB1T", 100000000000 ) ] consensus = "17ac43c1d8549c3181b200f1bf97eb7d" def scenario( wallets, **kw ): testlib.blockstack_namespace_preorder( "id", wallets[1].addr, wallets[0].privkey ) testlib.blockstack_namespace_preorder( "reveal", wallets[1].addr, wallets[0].privkey ) testlib.next_block( **kw ) testlib.blockstack_namespace_reveal( "id", wallets[1].addr, 52595, 250, 4, [6,5,4,3,2,1,0,0,0,0,0,0,0,0,0,0], 10, 10, wallets[0].privkey ) testlib.blockstack_namespace_reveal( "reveal", wallets[1].addr, 52595, 250, 4, [6,5,4,3,2,1,0,0,0,0,0,0,0,0,0,0], 10, 10, wallets[0].privkey ) testlib.next_block( **kw ) testlib.blockstack_namespace_ready( "id", wallets[1].privkey ) testlib.next_block( **kw ) testlib.blockstack_register_user('foo.id', wallets[2].privkey, wallets[3].privkey, **kw) print 'reveal key: {}'.format(wallets[1].privkey) print 'payment key: {}'.format(wallets[2].privkey) print 'address: {}'.format(wallets[3].addr) def check( state_engine ): # not revealed, but ready ns = state_engine.get_namespace_reveal( "id" ) if ns is not None: print "namespace reveal exists" return False ns = state_engine.get_namespace( "id" ) if ns is None: print "no namespace" return False if ns['namespace_id'] != 'id': print "wrong namespace" return False # registered name_rec = state_engine.get_name( "foo.id" ) if name_rec is None: print "name does not exist" return False return True
gpl-3.0
9,065,873,428,356,354,000
33.571429
146
0.701526
false
vathpela/anaconda
tests/nosetests/pyanaconda_tests/localization_test.py
1
8224
# # Copyright (C) 2013 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties 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 this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from pyanaconda import localization from pyanaconda.core.util import execWithCaptureBinary import locale as locale_mod import unittest class ParsingTests(unittest.TestCase): def invalid_langcodes_test(self): """Should return None for invalid langcodes.""" # None parts = localization.parse_langcode(None) self.assertIsNone(parts) # nonsense parts = localization.parse_langcode("*_&!") self.assertIsNone(parts) # no language parts = localization.parse_langcode("_CZ") self.assertIsNone(parts) def parsing_test(self): """Should correctly parse valid langcodes.""" parts = localization.parse_langcode("cs") self.assertIn("language", parts) self.assertEqual(parts["language"], "cs") parts = localization.parse_langcode("cs_CZ") self.assertIn("language", parts) self.assertIn("territory", parts) self.assertEqual(parts["language"], "cs") self.assertEqual(parts["territory"], "CZ") parts = localization.parse_langcode("cs_CZ.UTF-8") self.assertIn("language", parts) self.assertIn("territory", parts) self.assertIn("encoding", parts) self.assertEqual(parts["language"], "cs") self.assertEqual(parts["territory"], "CZ") self.assertEqual(parts["encoding"], "UTF-8") parts = localization.parse_langcode("cs_CZ.UTF-8@latin") self.assertIn("language", parts) self.assertIn("territory", parts) self.assertIn("encoding", parts) self.assertIn("script", parts) self.assertEqual(parts["language"], "cs") self.assertEqual(parts["territory"], "CZ") self.assertEqual(parts["encoding"], "UTF-8") self.assertEqual(parts["script"], "latin") parts = localization.parse_langcode("cs.UTF-8@latin") self.assertIn("language", parts) self.assertIn("encoding", parts) self.assertIn("script", parts) self.assertEqual(parts["language"], "cs") self.assertEqual(parts["encoding"], "UTF-8") self.assertEqual(parts["script"], "latin") parts = localization.parse_langcode("cs_CZ@latin") self.assertIn("language", parts) self.assertIn("territory", parts) self.assertIn("script", parts) self.assertEqual(parts["language"], "cs") self.assertEqual(parts["territory"], "CZ") self.assertEqual(parts["script"], "latin") class LangcodeLocaleMatchingTests(unittest.TestCase): def langcode_matches_locale_test(self): """Langcode-locale matching should work as expected.""" # should match self.assertTrue(localization.langcode_matches_locale("sr", "sr")) self.assertTrue(localization.langcode_matches_locale("sr", "sr_RS")) self.assertTrue(localization.langcode_matches_locale("sr", "sr_RS.UTF-8")) self.assertTrue(localization.langcode_matches_locale("sr", "sr_RS.UTF-8@latin")) self.assertTrue(localization.langcode_matches_locale("sr_RS", "sr_RS")) self.assertTrue(localization.langcode_matches_locale("sr_RS", "sr_RS.UTF-8")) self.assertTrue(localization.langcode_matches_locale("sr_RS", "sr_RS.UTF-8@latin")) self.assertTrue(localization.langcode_matches_locale("sr_RS.UTF-8", "sr_RS.UTF-8")) self.assertTrue(localization.langcode_matches_locale("sr_RS.UTF-8", "sr_RS.UTF-8@latin")) self.assertTrue(localization.langcode_matches_locale("sr_RS.UTF-8@latin", "sr_RS.UTF-8@latin")) # missing language, shouldn't match self.assertFalse(localization.langcode_matches_locale("", "sr")) self.assertFalse(localization.langcode_matches_locale("sr", "")) self.assertFalse(localization.langcode_matches_locale("sr", None)) self.assertFalse(localization.langcode_matches_locale(None, "sr")) # missing items in the locale, shouldn't match self.assertFalse(localization.langcode_matches_locale("sr_RS", "sr")) self.assertFalse(localization.langcode_matches_locale("sr_RS.UTF-8", "sr_RS")) self.assertFalse(localization.langcode_matches_locale("sr.UTF-8", "sr_RS")) self.assertFalse(localization.langcode_matches_locale("sr_RS.UTF-8", "sr.UTF-8")) self.assertFalse(localization.langcode_matches_locale("sr_RS.UTF-8@latin", "sr_RS")) self.assertFalse(localization.langcode_matches_locale("sr_RS@latin", "sr_RS")) self.assertFalse(localization.langcode_matches_locale("sr.UTF-8@latin", "sr_RS.UTF-8")) self.assertFalse(localization.langcode_matches_locale("sr@latin", "sr_RS")) # different parts, shouldn't match self.assertFalse(localization.langcode_matches_locale("sr", "en")) self.assertFalse(localization.langcode_matches_locale("de_CH", "fr_CH")) self.assertFalse(localization.langcode_matches_locale("sr_RS", "sr_ME")) self.assertFalse(localization.langcode_matches_locale("sr_RS@latin", "sr_RS@cyrilic")) self.assertFalse(localization.langcode_matches_locale("sr_RS@latin", "sr_ME@latin")) def find_best_locale_match_test(self): """Finding best locale matches should work as expected.""" # can find best matches self.assertEqual(localization.find_best_locale_match("cs_CZ", ["cs", "cs_CZ", "en", "en_US"]), "cs_CZ") self.assertEqual(localization.find_best_locale_match("cs", ["cs_CZ", "cs", "en", "en_US"]), "cs") self.assertEqual(localization.find_best_locale_match("pt_BR", ["pt", "pt_BR"]), "pt_BR") self.assertEqual(localization.find_best_locale_match("pt_BR", ["pt", "pt_BR", "pt_PT"]), "pt_BR") self.assertEqual(localization.find_best_locale_match("cs_CZ.UTF-8", ["cs", "cs_CZ", "cs_CZ.UTF-8"]), "cs_CZ.UTF-8") self.assertEqual(localization.find_best_locale_match("cs_CZ.UTF-8@latin", ["cs", "cs_CZ@latin", "cs_CZ.UTF-8"]), "cs_CZ@latin") # no matches self.assertIsNone(localization.find_best_locale_match("pt_BR", ["en_BR", "en"])) self.assertIsNone(localization.find_best_locale_match("cs_CZ.UTF-8", ["en", "en.UTF-8"])) def resolve_date_format_test(self): """All locales' date formats should be properly resolved.""" locales = (line.strip() for line in execWithCaptureBinary("locale", ["-a"]).splitlines()) for locale in locales: # "locale -a" might return latin-1 encoded local identifiers: # https://bugzilla.redhat.com/show_bug.cgi?id=1184168 # once that bug is fixed we should be able to remove the latin-1 decoding # fallback try: decoded_locale = locale.decode("utf-8") except UnicodeDecodeError: decoded_locale = locale.decode("latin-1") try: locale_mod.setlocale(locale_mod.LC_ALL, decoded_locale) except locale_mod.Error: # cannot set locale (a bug in the locale module?) continue order = localization.resolve_date_format(1, 2, 3, fail_safe=False)[0] for i in (1, 2, 3): self.assertIn(i, order)
gpl-2.0
-5,565,319,239,720,229,000
48.842424
114
0.649562
false
tommo/gii
lib/mock/asset/EffectAsset.py
1
1692
import os.path import logging import subprocess import shutil import json from gii.core import * from mock import _MOCK from gii.qt.dialogs import requestString, alertMessage, requestConfirm ##----------------------------------------------------------------## class EffectAssetManager( AssetManager ): def getName( self ): return 'asset_manager.effect' def acceptAssetFile(self, filePath): if not os.path.isfile( filePath ): return False name, ext = os.path.splitext( filePath ) return ext == '.effect' def importAsset( self, node, reload = False ): fileName, ext = os.path.splitext( node.getFilePath() ) node.assetType = 'effect' node.setObjectFile( 'def', node.getFilePath() ) return True def editAsset(self, node): editor = app.getModule( 'effect_editor' ) if not editor: return alertMessage( 'Editor not load', 'Effect Editor not found!' ) editor.openAsset( node ) ##----------------------------------------------------------------## class EffectAssetCreator( AssetCreator ): def getAssetType( self ): return 'effect' def getLabel( self ): return 'Effect Config' def createAsset( self, name, contextNode, assetType ): ext = '.effect' filename = name + ext if contextNode.isType('folder'): nodepath = contextNode.getChildPath( filename ) else: nodepath = contextNode.getSiblingPath( filename ) fullpath = AssetLibrary.get().getAbsPath( nodepath ) _MOCK.createEmptySerialization( fullpath, 'mock.EffectConfig' ) return nodepath ##----------------------------------------------------------------## EffectAssetManager().register() EffectAssetCreator().register() AssetLibrary.get().setAssetIcon( 'effect', 'fx' )
mit
-8,692,634,086,864,370,000
26.737705
72
0.637116
false
KelvinLu/krotos-convnet
krotos/convnet/model/training.py
1
1158
import tensorflow as tf def training_mse_loss(output, labels): with tf.variable_scope('loss') as scope: loss = tf.reduce_mean(tf.square(tf.sub(output, labels)), name='mse_loss') return loss def training_sigmoid_cross_entropy(output, labels): with tf.variable_scope('loss') as scope: loss = tf.nn.sigmoid_cross_entropy_with_logits(output, labels, name='sigmoid_cross_entropy') return loss def training_op(loss, initial_learning_rate, global_step, decay_steps, decay_rate): lr = tf.train.exponential_decay( learning_rate=initial_learning_rate, global_step=global_step, decay_steps=decay_steps, decay_rate=decay_rate, staircase=True, name='learning_rate' ) optimizer = tf.train.GradientDescentOptimizer(lr) gradients = optimizer.compute_gradients(loss) gradients = [(tf.clip_by_value(g, -1.0, 1.0), v) for g, v in gradients] apply_gradients = optimizer.apply_gradients(gradients, global_step=global_step) with tf.control_dependencies([apply_gradients]): train_op = tf.no_op(name='train') return train_op, gradients
mit
5,099,103,527,940,317,000
34.090909
100
0.670984
false
nsf/gotris
Tools/fontcompile.py
1
1537
#!/usr/bin/python # -*- coding: utf-8 -*- # compiled font is a binary blob: # 1. magic (MFNT) - 4 bytes # 2. number of symbols - 4 bytes # 3. font y advance - 4 bytes # 4. an array of glyphs (offset_x, offset_y, width, height, tx, ty, tx2, ty2, x_advance) - 36 * number of symbols # (iiIIffffI) # 5. png texture import sys import struct import os from xml2obj import xml2obj def print_usage_and_exit(): print "usage: {0} <UNPACKED FONT>".format(sys.argv[0]) sys.exit(1) if len(sys.argv) != 2: print_usage_and_exit() fontfile = sys.argv[1] if not os.path.exists(fontfile): print_usage_and_exit() glyphs = [] with file(fontfile + ".fontdef.xml", 'r') as f: xmlobj = xml2obj(f.read()) font_y_advance = int(xmlobj.height) for g in xmlobj.glyph: glyphs.append((unicode(g.symbol), int(g.offset_x), int(g.offset_y), int(g.width), int(g.height), float(g.tx), float(g.ty), float(g.tx2), float(g.ty2), int(g.x_advance))) with file(fontfile[:-4] + ".font", 'w') as f: f.write("MFNT") f.write(struct.pack("<I", len(glyphs))) f.write(struct.pack("<I", font_y_advance)) for g in glyphs: f.write(struct.pack("<iiIIffffI", g[1], g[2], g[3], g[4], g[5], g[6], g[7], g[8], g[9])) unicode_fontcp = [] for i, g in enumerate(glyphs): unicode_fontcp.append((g[0], i+1)) def unicode_fontcp_key(item): return item[0] unicode_fontcp.sort(key=unicode_fontcp_key) for entry in unicode_fontcp: f.write(struct.pack("<II", ord(entry[0]), entry[1])) with file(fontfile, 'r') as imgf: imgdata = imgf.read() f.write(imgdata)
mit
693,089,028,628,242,800
25.050847
170
0.648666
false
jamslevy/gsoc
app/soc/views/helper/list_info.py
1
1257
#!/usr/bin/python2.5 # # Copyright 2009 the Melange 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. """Helpers used for list info functions. """ __authors__ = [ '"Lennard de Rijk" <[email protected]>', ] def getStudentProposalInfo(ranking, proposals_keys): """Returns a function that returns information about the rank and assignment. Args: ranking: dict with a mapping from Student Proposal key to rank proposals_keys: list of proposal keys assigned a slot """ def wrapper(item, _): """Decorator wrapper method. """ info = {'rank': ranking[item.key()]} if item.key() in proposals_keys: info['item_class'] = 'selected' else: info['item_class'] = 'normal' return info return wrapper
apache-2.0
7,530,430,132,670,981,000
27.568182
79
0.703262
false
tlinnet/qNLS
qNLS.py
1
71993
#! /usr/bin/env python ############################################################################### # # # Copyright (C) 2014-2015 Troels E. Linnet, SBiNLab, Copenhagen University # # Copyright (C) 2014-2015 Kaare Teilum, SBiNLab, Copenhagen University # # # # This file is part of the program relax (http://www.nmr-relax.com). # # # # This program 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. # # # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### import csv import glob import nmrglue import matplotlib.pyplot as plt import matplotlib.cm import numpy from numpy.ma import masked_where import os import os.path import random import shutil import subprocess from scipy.optimize import leastsq from stat import S_IRWXU, S_IRGRP, S_IROTH import sys import time from warnings import warn # Get start time start_time = time.time() # Add arguments to the script. import argparse parser = argparse.ArgumentParser() parser.add_argument('-N', nargs='?', type=int, metavar='N', dest='N', default=4, help='Number of repeated spectra. -N 1') parser.add_argument('-sf', nargs='+', type=int, metavar='sf', dest='sf', default=[80, 60, 40, 20], help='list of sampling fractions in percent: -sf 80 60 40 20') parser.add_argument("-ref_FT", dest='ref_FT', action="store_true", help="Instead of using METHOD=coMDD at 100pct as reference for comparing, use METHOD=FT. Default False.") parser.add_argument('-N_NUS_SCHEDULES', nargs='?', type=int, metavar='N_NUS_SCHEDULES', dest='N_NUS_SCHEDULES', default=5000, help='dpoisson7.1 param: Number of NUS scedules to produce for scoring: -N_NUS_SCHEDULES 1000') parser.add_argument('-T2', nargs='?', type=float, metavar='T2', dest='T2', default=0.1, help='T2: spin-spin relaxation time, the expected time constant characterizing the signal decay in in-direct dimension (s): -T2 0.1.') parser.add_argument('-FST_PNT_PPM', nargs='?', type=float, metavar='FST_PNT_PPM', dest='FST_PNT_PPM', default=11, help='MDD param: Define from where the region of interest starts in the direct dimension [ppm]: -FST_PNT_PPM 11') parser.add_argument('-ROISW', nargs='?', type=float, metavar='ROISW', dest='ROISW', default=5, help='MDD param: Define sweep-width in ppm, to subtract from FST_PNT_PPM: -ROISW 5') parser.add_argument('-SRSIZE', nargs='?', type=float, metavar='SRSIZE', dest='SRSIZE', default=0.1, help='MDD param: Size of sub-region (ppm): -SRSIZE 0.1') parser.add_argument('-CEXP', nargs='?', type=str, metavar='CEXP', dest='CEXP', default='yn', help='Toggle R-MDD / MDD mode. For a dimension, with "y" time domain shape in the dimension is expected to be autoregressive. In other words, we assume that the FID in the dimension is a complex exponent. CEXP=y may be used, for example, for HNCO and HNcoCA experiments, but not for the NOESYs: -CEXP yn') parser.add_argument('-NCOMP', nargs='?', type=int, metavar='NCOMP', dest='NCOMP', default=25, help='MDD param: Number of components per sub-region: -NCOMP 25') parser.add_argument('-NITER', nargs='?', type=int, metavar='NITER', dest='NITER', default=50, help='MDD param: number of iteration in mddnmr: -NITER 50') parser.add_argument('-MDD_NOISE', nargs='?', type=float, metavar='MDD_NOISE', dest='MDD_NOISE', default=0.7, help='MDD param: Noise in mddnmr: -MDD_NOISE 0.7') parser.add_argument('-MDDTHREADS', nargs='?', type=int, metavar='MDDTHREADS', dest='MDDTHREADS', default=16, help='MDD param: Maximal number of parallel processes: -MDDTHREADS 16') input_args = parser.parse_args() def call_prog(args=None, verbose=True): """Call an external program. @keyword args: List of arguments to call @type args: list of str @keyword verbose: A flag which if True, will print to screen. @type verbose: bool @return: The return code from the program, and the list of lines from output. @rtype: int, list of str """ # Call function. Temp = subprocess.Popen(args, stdout=subprocess.PIPE) ## But do not wait until program finish, start displaying output immediately if verbose: while True: out = Temp.stdout.read(1) if out == '' and Temp.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush() # Communicate with program, and get output and error output. (output, errput) = Temp.communicate() # Wait for finish and get return code. returncode = Temp.wait() # Split the output into lines. line_split = output.splitlines() if returncode == 1: print("\nProgram call returned error code: %s\n"%args[0]) raise Exception("Program call returned error code %s."%returncode) return returncode, line_split def check_files(files=None): """Check list of files is available in current directory. @keyword files: List of expected filenames in current directory @type files: list of str """ # Loop over all files. for fname in files: test = os.path.isfile(fname) if not test: print("\nMissing a file. All these files are expected to be present: %s\n"%files) raise Exception("The file '%s' was not found in directory."%fname) def func_gauss(params=None, x=None): """Calculate the Gaussian distribution for a given x value. @param params: The vector of parameter values. @type params: numpy rank-1 float array @keyword x: The x value to calculate the probability for. @type x: numpy array @return: The probability corresponding to x. @rtype: float """ # Unpack, # a: The amplitude of the distribution. # mu: The center of the distribution. # sigma: The standard deviation of the distribution. a, mu, sigma = params # Calculate and return the probability. return a*numpy.exp(-(x-mu)**2/(2*sigma**2)) def func_gauss_residual(params=None, x=None, values=None): """Calculate the residual vector betwen measured values and the function values. @param params: The vector of parameter values. @type params: numpy rank-1 float array @keyword x: The x data points. @type x: numpy array @param values: The measured values. @type values: numpy array @return: The residuals. @rtype: numpy array """ # Let the vector K be the vector of the residuals. A residual is the difference between the observation and the equation calculated using the initial values. K = values - func_gauss(params=params, x=x) # Return return K def func_gauss_weighted_residual(params=None, x=None, values=None, errors=None): """Calculate the weighted residual vector betwen measured values and the function values. @param params: The vector of parameter values. @type params: numpy rank-1 float array @keyword x: The x data points. @type x: numpy array @param values: The measured values. @type values: numpy array @param errors: The standard deviation of the measured intensity values per time point. @type errors: numpy array @return: The weighted residuals. @rtype: numpy array """ # Let the vector Kw be the vector of the weighted residuals. A residual is the difference between the observation and the equation calculated using the initial values. Kw = 1. / errors * func_gauss_residual(params=params, x=x, values=values) # Return return Kw def hist_plot(ndarray=None, hist_kwargs=None, show=False): """Flatten the 2D numpy array, and plot as histogram. @keyword ndarray: The numpy array to flatten, and plot as histogram. @type ndarray: numpy array @keyword hist_kwargs: The dictionary of keyword arguments to be send to matplotlib.pyplot.hist() plot function. If None, standard values will be used. @type hist_kwargs: None or dic @keyword show: A flag which if True will make a call to matplotlib.pyplot.show(). @type show: bool @return: The matplotlib.axes.AxesSubplot class, which can be manipulated to add additional text to the axis. @rtype: matplotlib.axes.AxesSubplot """ # Flatten the numpy data array. data = ndarray.flatten() # Now make a histogram. # http://matplotlib.org/1.2.1/examples/api/histogram_demo.html fig = plt.figure() ax = fig.add_subplot(111) if hist_kwargs == None: hist_kwargs = {'bins': 3000, 'range': None, 'normed': False, 'facecolor':'green', 'alpha':0.75} # Make the plot, and unpack the dictionary keywords. #n : array or list of arrays. The values of the histogram bins. #bins : array. The edges of the bins. #patches : list or list of lists. Silent list of individual patches used to create the histogram. n, bins, patches = ax.hist(data, **hist_kwargs) # Calculate the bin centers. bincenters = 0.5*(bins[1:]+bins[:-1]) # Find index for maximum number in a bin. i = numpy.argmax(n) # Get the position for the maximum. bin_max_x = bincenters[i] # Get the amplitude for the maximum. bin_max_y = n[i] # Try find Full width at half maximum (FWHM). FWHM = 2 * sqrt(2 ln(2 )) * sigma ~ 2.355 * sigma. # Half maximum hm = 0.5 * bin_max_y # Find the first instances of left and right bin, where is lower than hm. for j in range(1, len(bins)): # Find the center values of the bins. left_bin_x = bincenters[i-j] right_bin_x = bincenters[i+j] # Find the values of the bins. left_bin_y = n[i-j] right_bin_y = n[i+j] if left_bin_y < hm and right_bin_y < hm: fwhm = right_bin_x - left_bin_x fwhm_std = fwhm / (2. * numpy.sqrt(2. * numpy.log(2.))) break # Define function to minimise. t_func = func_gauss_weighted_residual # All args to function. Params are packed out through function, then other parameters. # N is number of observations. N = len(bincenters) errors = numpy.ones(N) args=(bincenters, n, errors) # Initial guess for minimisation. x0 = numpy.asarray( [bin_max_y, bin_max_x, fwhm_std] ) # Call scipy.optimize.leastsq. #ftol: The function tolerance for the relative error desired in the sum of squares, parsed to leastsq. #xtol: The error tolerance for the relative error desired in the approximate solution, parsed to leastsq. #maxfev: The maximum number of function evaluations, parsed to leastsq. If zero, then 100*(N+1) is the maximum function calls. N is the number of elements in x0=[r2eff, i0]. #factor: The initial step bound, parsed to leastsq. It determines the initial step bound (''factor * || diag * x||''). Should be in the interval (0.1, 100). popt, pcov, infodict, errmsg, ier = leastsq(func=t_func, x0=x0, args=args, full_output=True, ftol=1e-15, xtol=1e-15, maxfev=10000000, factor=100.0) # Catch errors: if ier in [1, 2, 3, 4]: warning = None elif ier in [9]: warn("%s." % errmsg) warning = errmsg elif ier in [0, 5, 6, 7, 8]: raise Exception("scipy.optimize.leastsq raises following error: '%s'." % errmsg) # 'nfev' number of function calls. f_count = infodict['nfev'] # 'fvec': function evaluated at the output. fvec = infodict['fvec'] #fvec_test = func(popt, times, values) # 'fjac': A permutation of the R matrix of a QR factorization of the final approximate Jacobian matrix, stored column wise. Together with ipvt, the covariance of the estimate can be approximated. # fjac = infodict['fjac'] # 'qtf': The vector (transpose(q) * fvec). # qtf = infodict['qtf'] # 'ipvt' An integer array of length N which defines a permutation matrix, p, such that fjac*p = q*r, where r is upper triangular # with diagonal elements of nonincreasing magnitude. Column j of p is column ipvt(j) of the identity matrix. # 'pcov': The estimated covariance matrix of popt. # The diagonals provide the variance of the parameter estimate. # The reduced chi square: Take each "difference element, which could have been weighted" (O - E) and put to order 2. Sum them, and divide by number of degrees of freedom. # Calculated the (weighted) chi2 value. chi2 = numpy.sum( fvec**2 ) # p is number of fitted parameters. p = len(x0) # n is number of degrees of freedom #n = N - p - 1 n = N - p # The reduced chi square. chi2_red = chi2 / n # chi2_red >> 1 : indicates a poor model fit. # chi2_red > 1 : indicates that the fit has not fully captured the data (or that the error variance has been underestimated) # chi2_red = 1 : indicates that the extent of the match between observations and estimates is in accord with the error variance. # chi2_red < 1 : indicates that the model is 'over-fitting' the data: either the model is improperly fitting noise, or the error variance has been overestimated. absolute_sigma = True if pcov is None: # indeterminate covariance pcov = numpy.zeros((len(popt), len(popt)), dtype=float) pcov.fill(numpy.inf) elif not absolute_sigma: if N > p: pcov = pcov * chi2_red else: pcov.fill(inf) # To compute one standard deviation errors on the parameters, take the square root of the diagonal covariance. perr = numpy.sqrt(numpy.diag(pcov)) # Return as standard from minfx. param_vector = popt param_vector_error = perr # Extract parameters from vector. amp, mu, sigma = param_vector # Recalculate Full width at half maximum (FWHM) hm = 0.5 * amp fwhm = (2. * numpy.sqrt(2. * numpy.log(2.))) * sigma left_bin_x = mu - 0.5 * fwhm right_bin_x = mu + 0.5 * fwhm # Annotate the center. ax.annotate("%3.2f"%mu, xy=(mu, 0.0), xycoords='data', xytext=(mu, 0.25*amp), textcoords='data', size=8, horizontalalignment="center", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=0"), bbox=dict(boxstyle="round", facecolor="w")) # Annotate the Full width at half maximum. ax.annotate("", xy=(left_bin_x, hm), xycoords='data', xytext=(right_bin_x, hm), textcoords='data', arrowprops=dict(arrowstyle="<->", connectionstyle="arc3, rad=0")) ax.annotate("HM=%3.2f\nFWHM=%3.2f\nstd=%3.2f"%(hm, fwhm, sigma), xy=(mu, hm), xycoords="data", size=8, va="center", horizontalalignment="center", bbox=dict(boxstyle="round", facecolor="w")) # Calculate and plot the gauss values. gauss = func_gauss(params=param_vector, x=bincenters) ax.plot(bincenters, gauss, 'r-', label='gauss') # Calculate spread for sigma +/- 3. 99.7 % sigma3_p = mu+3*sigma sigma3_m = mu-3*sigma ax.annotate("Sigma 3 plus", xy=(sigma3_p, 0.0), xycoords='data', xytext=(sigma3_p, 0.2*amp), textcoords='data', size=8, horizontalalignment="center", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=0"), bbox=dict(boxstyle="round", facecolor="w")) ax.annotate("Sigma 3 minus", xy=(sigma3_m, 0.0), xycoords='data', xytext=(sigma3_m, 0.2*amp), textcoords='data', size=8, horizontalalignment="center", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=0"), bbox=dict(boxstyle="round", facecolor="w")) sigma6_p = mu+6*sigma sigma6_m = mu-6*sigma ax.annotate("Sigma 6 plus", xy=(sigma6_p, 0.0), xycoords='data', xytext=(sigma6_p, 0.1*amp), textcoords='data', size=8, horizontalalignment="center", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=0"), bbox=dict(boxstyle="round", facecolor="w")) ax.annotate("Sigma 6 minus", xy=(sigma6_m, 0.0), xycoords='data', xytext=(sigma6_m, 0.1*amp), textcoords='data', size=8, horizontalalignment="center", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=0"), bbox=dict(boxstyle="round", facecolor="w")) # Set limits. xlim = (mu-10*sigma, mu+25*sigma) ax.set_xlim(xlim) ylim = (0, bin_max_y) ax.set_ylim(ylim) # If show. if show: plt.show() # Return ax return ax, amp, mu, sigma, xlim, ylim def linear_corr(x=None, y=None): """Calculate the linear correlation 'a', for the function y=a*x. The function returns "a" and the sample correlation coefficient 'r_xy'. @keyword x: The data for the X-axis. @type x: float or numpy array. @keyword y: The data for the Y-axis. @type y: float or numpy array. @return: The correlation 'a', and sample correlation coefficient 'r_xy'. @rtype: float, float """ # The correlation is. a = numpy.sum(x*y) / numpy.sum(x**2) # The sample correlation coefficient is. r_xy = numpy.sum(x*y) / numpy.sqrt(numpy.sum(x**2) * numpy.sum(y**2)) return a, r_xy def extract_rmsd(lines=None): """Extract showApod 'Noise Std Dev' for spectrum fourier transformed with NMRPipe. @keyword lines: The output lines from calling showApod @type leins: list of sts @return: The Noise Std Dev from line: 'REMARK Automated Noise Std Dev in Processed Data' @rtype: float """ # Loop over the lines found = False for line in lines: # Look for line with this remark. if line[:49] == 'REMARK Automated Noise Std Dev in Processed Data:': # The rest of the line is the rmsd. rmsd = float(line[49:].split()[0]) return rmsd if not found: print(show_apod_lines) raise Exception("Could not find the line: 'REMARK Automated Noise Std Dev in Processed Data:', from the output of showApod.") def make_nus_data(dir_from=None, dir_to=None, np=None, ni=None): """Create binary data, with FIDs from nls.hdr_3. @keyword dir_from: Directory where original fid resides @type dir_from: str @keyword dir_to: Directory where to put the modified fid @type dir_from: str @keyword np: The number of points for the direct dimension in the original file. @type np: int @keyword ni: The number of points for the in-direct dimension in the original file. @type ni: int """ # Check that file exists: fname_or_fid = dir_from + os.sep + 'fid' test_fid = os.path.isfile(fname_or_fid) if not test_fid: print("\nThe original fid file cannot be found: %s\n"%fname_or_fid) raise Exception("The original fid file cannot be found") # Check that nls.hdr_3 exist in target dir fname_hdr3 = dir_to + os.sep + 'nls.hdr_3' test_hdr3 = os.path.isfile(fname_hdr3) if not test_hdr3: print("\nThe nls.hdr_3 file cannot be found: %s\n"%fname_hdr3) raise Exception("The nls.hdr_3 file cannot be found") # Open the NI from nls.hdr_3 file_hdr3 = open(fname_hdr3, "r") ni_list = [] for line in file_hdr3: ni_list.append(int(line)) file_hdr3.close() # Calculate the bytes bytes = 4*np # Calculate the expected filesize. expected_file_size = 2*ni*(bytes+28)+32 # Get the actual file size actual_file_size = os.path.getsize(fname_or_fid) test_file_size = expected_file_size == actual_file_size if not test_file_size: print("\nThe actual file size differs from the expected: %s vs: %s bytes.\n"%(actual_file_size, expected_file_size)) raise Exception("The actual file size differs from the expected filesize.") # Open file for binary reading. file_fid_in = open(fname_or_fid, 'rb') # Open file for binary writing. fname_out_fid = dir_to + os.sep + 'fid' file_fid_out = open(fname_out_fid, 'wb') # First read the header and copy it. header = file_fid_in.read(32) file_fid_out.write(header) # Then loop over the list of NI. for ni_i in ni_list: # Calculate the offset position. seek_pos = 2*ni_i*(bytes+28)+32 # Move the reader file_fid_in.seek(seek_pos) # Read header1, data1, header2, data2 head1 = file_fid_in.read(28) data1 = file_fid_in.read(bytes) head2 = file_fid_in.read(28) data2 = file_fid_in.read(bytes) # Then write. file_fid_out.write(head1) file_fid_out.write(data1) file_fid_out.write(head2) file_fid_out.write(data2) # Close files. file_fid_in.close() file_fid_out.close() # Test the size of the written file. written_file_size = os.path.getsize(fname_out_fid) expected_written_file_size = 2*len(ni_list)*(bytes+28)+32 test_file_size = expected_written_file_size == written_file_size if not test_file_size: print("\nThe actual written size differs from the expected: %s vs: %s bytes.\n"%(written_file_size, expected_written_file_size)) raise Exception("The actual file size differs from the expected filesize.") def read_spectrum(file=None): """Read the spectrum data. @keyword file: The name of the file containing the spectrum. @type file: str @return: The nmrglue data dictionary, the universal dictionary, and the data as numpy array. @rtype: dic, dic, numpy array """ # Open file dic, data = nmrglue.pipe.read(file) udic = nmrglue.pipe.guess_udic(dic, data) # Write out to txt. root, ext = os.path.splitext(file) if ext == ".ft2": numpy.savetxt('%s.out'%root, data.flatten(), delimiter=' ') # Return the nmrglue data object. return dic, udic, data def write_fidSP_recFT(dir_from=None, dir_to=None, cur_ni=None): """Write fidSP.com and recFT.com, which tells how qMDD should process files. @keyword dir_from: Directory where fid.com and nmrproc.com is located. @type dir_from: str @keyword dir_to: Directory where to put fidSP.com @type dir_to: str @keyword cur_ni: The number of in-direct increments to create the data matrix. @type cur_ni: int """ # Check that fid.com exist in original dir fname_fid_com = dir_from + os.sep + 'fid.com' test_fname_fid_com = os.path.isfile(fname_fid_com) if not test_fname_fid_com: print("\nThe fid.com file cannot be found: %s\n"%fname_fid_com) raise Exception("The fid.com file cannot be found") # Open the fid.com file_fid_com = open(fname_fid_com, "r") # Check that nmrproc.com exist in original dir fname_nmrproc_com = dir_from + os.sep + 'nmrproc.com' test_fname_nmrproc_com = os.path.isfile(fname_nmrproc_com) if not test_fname_nmrproc_com: print("\nThe nmrproc.com file cannot be found: %s\n"%fname_nmrproc_com) raise Exception("The nmrproc.com file cannot be found") # Open the nmrproc.com file_nmrproc_com = open(fname_nmrproc_com, "r") # Calculate dimension for matrix yT = cur_ni yN = 2*yT fidSP_lines = [] for line in file_fid_com: # Skip lines with # if line[0] == "#": continue # Skip empty lines elif line == '\n': continue # If out is in line elif "-out" in line: continue # Skip lines with sleep elif "sleep" in line: continue # Now look for yN if '-yN' in line: line_split = line.split() index_yN = line_split.index('-yN') line_split[index_yN+1] = str(yN) line = ' '.join(line_split) + '\n' # Now look for yT elif '-yT' in line: line_split = line.split() index_yT = line_split.index('-yT') line_split[index_yT+1] = str(yT) line = ' '.join(line_split) + '\n' else: line_split = line.split() line = ' '.join(line_split) + '\n' # Append lines fidSP_lines.append(line) # Store nmrpipe commands depending. pipe_pre = [] pipe_post = [] store_pre = True for line in file_nmrproc_com: # Skip lines with # if line[0] == "#": continue # Skip empty lines elif line == '\n': continue # Skip reading in line elif 'nmrPipe -in' in line: continue # Skip reading out line elif '-out' in line: continue # Make swith to store if 'TP' in line: store_pre = False # Store lines if store_pre: pipe_pre.append(line) else: pipe_post.append(line) # Now write fidSP.com wfile_name_fidSP_com = dir_to + os.sep + 'fidSP.com' wfile_fidSP_com = open(wfile_name_fidSP_com, "w") for line in fidSP_lines + pipe_pre: wfile_fidSP_com.write(line) # Write additional wfile_fidSP_com.write(r'| pipe2xyz -z -out ft/data%03d.DAT -ov -nofs -verb') # Now write to recFT.com wfile_name_recFT_com = dir_to + os.sep + 'recFT.com' wfile_recFT_com = open(wfile_name_recFT_com, "w") recFT_lines_pre = [ "#!/bin/tcsh -f", "echo '| ' in $0 $1", "if( $#argv < 1 ) then", 'echo "Use: $0 <input pipe> <template for output spectrum>"', 'echo "nmrPipe processing of YZ dimensions after MDD reconstruction"', "exit 1", "endif", "", "set ft4trec=$1", "if( $#argv > 1 ) set proc_out=$2", "", "if( ! -f $ft4trec ) then", " ls $ft4trec", " echo $0 failed", " exit 2", "endif", "", "echo '| Processing time domain MDD reconstruction '", "echo", "echo Processing Y dimensions", "showhdr $ft4trec", "cat $ft4trec \\", ] recFT_lines_post = [ "-ov -out $proc_out", "echo $proc_out ready", "exit", ] # Write for line in recFT_lines_pre: wfile_recFT_com.write(line + "\n") for line in pipe_post: wfile_recFT_com.write(line) for line in recFT_lines_post: wfile_recFT_com.write(line + "\n") # Close files. file_fid_com.close() file_nmrproc_com.close() wfile_fidSP_com.close() wfile_recFT_com.close() # Then make files executable. os.chmod(wfile_name_recFT_com, S_IRWXU|S_IRGRP|S_IROTH) def write_proc(dir=None, FID=None, NUS_POINTS=None, FST_PNT_PPM=None, ROISW=None, SRSIZE=None, CEXP=None, MDDTHREADS=None, NCOMP=None, NITER=None, MDD_NOISE=None): """Create the nls.in file for nussampler. @keyword dir: The directory where to create the nls.in file. @type dir: str @keyword FID: MDD param. The relative path to the directory with the fid file. The relative path should be wihtout ending of ".fid". @type FIDI: str @keyword NUS_POINTS: MDD param. How many points are sampled in the in-direct dimension. @type NUS_POINTS: int @keyword FST_PNT_PPM: MDD param. Define from where the region of interest starts in the direct dimension [ppm]. @type FST_PNT_PPM: float @keyword ROISW: MDD param: Define sweep-width in ppm, to subtract from FST_PNT_PPM. @type ROISW: float @keyword SRSIZE: MDD param: Size of sub-region (ppm). @type SRSIZE: float @keyword SRSIZE: MDD param: Size of sub-region (ppm). @type SRSIZE: str @keyword CEXP: MDD param. Toggle R-MDD / MDD mode. For a dimension, with "y" time domain shape in the dimension is expected to be autoregressive. In other words, we assume that the FID in the dimension is a complex exponent. CEXP=y may be used, for example, for HNCO and HNcoCA experiments, but not for the NOESYs. @type CEXP: str @keyword MDDTHREADS: MDD param: Maximal number of parallel processes. @type MDDTHREADS: int @keyword NCOMP: MDD param: Number of components per sub-region @type NCOMP: int @keyword NITER: MDD param: Number of iteration in mddnmr. @type NITER: int @keyword MDD_NOISE: MDD param: Noise in mddnmr. @type MDD_NOISE: float """ # Open files. wfile_name_proc_comdd_before = dir + os.sep + 'proc_comdd_before.sh' wfile_proc_comdd_before = open(wfile_name_proc_comdd_before, "w") wfile_name_proc_comdd_after = dir + os.sep + 'proc_comdd_after.sh' wfile_proc_comdd_after = open(wfile_name_proc_comdd_after, "w") wfile_name_proc_mdd = dir + os.sep + 'proc_mdd.sh' wfile_proc_mdd = open(wfile_name_proc_mdd, "w") lines = [ "#!/bin/tcsh", "setenv FID %s"%FID, "setenv fidSP fidSP.com", "setenv REC2FT recFT.com", "setenv in_file nls.in", "setenv selection_file nls.hdr_3", "setenv FST_PNT_PPM %s"%FST_PNT_PPM, "setenv ROISW %s"%ROISW, "setenv NUS_POINTS %i"%NUS_POINTS, "setenv NUS_TABLE_OFFSET 0", "setenv SRSIZE %s"%SRSIZE, "setenv CEXP %s"%CEXP, "setenv MDDTHREADS %i"%MDDTHREADS, "setenv METHOD MDD", "#MDD related parameters", "setenv NCOMP %s"%NCOMP, "setenv NITER %s"%NITER, "setenv MDD_NOISE %s"%MDD_NOISE, ] # Write to files. for line in lines: wfile_proc_comdd_before.write(line + "\n") wfile_proc_comdd_after.write(line + "\n") wfile_proc_mdd.write(line + "\n") # Then write independent wfile_proc_comdd_before.write("setenv proc_out test.ft2" + "\n") wfile_proc_comdd_after.write("setenv proc_out test.ft2" + "\n") wfile_proc_mdd.write("setenv proc_out test.ft2" + "\n") wfile_proc_comdd_before.write("mddnmr4pipeN.sh 1 23" + "\n") wfile_proc_comdd_after.write("mddnmr4pipeN.sh 4 5" + "\n") wfile_proc_mdd.write("mddnmr4pipeN.sh 1 2 3 4 5" + "\n") # Close files. wfile_proc_comdd_before.close() wfile_proc_comdd_after.close() wfile_proc_mdd.close() # Then make files executable. os.chmod(wfile_name_proc_comdd_before, S_IRWXU|S_IRGRP|S_IROTH) os.chmod(wfile_name_proc_comdd_after, S_IRWXU|S_IRGRP|S_IROTH) os.chmod(wfile_name_proc_mdd, S_IRWXU|S_IRGRP|S_IROTH) # Now write a proc file, which is only for FT wfile_name_proc_FT = dir + os.sep + 'proc_FT.sh' wfile_proc_FT = open(wfile_name_proc_FT, "w") lines = [ "#!/bin/tcsh", "setenv FID %s"%FID, "setenv fidSP fidSP.com", "setenv REC2FT recFT.com", "setenv in_file nls.in", "setenv selection_file nls.hdr_3", "setenv FST_PNT_PPM %s"%FST_PNT_PPM, "setenv ROISW %s"%ROISW, "setenv proc_out test_REF_FT.ft2", "setenv NUS_POINTS %i"%NUS_POINTS, "setenv NUS_TABLE_OFFSET 0", "setenv MDDTHREADS %i"%MDDTHREADS, "setenv METHOD FT", "mddnmr4pipeN.sh 1 2 3 4 5", ] # Write to file. for line in lines: wfile_proc_FT.write(line + "\n") # Close files. wfile_proc_FT.close() # Then make files executable. os.chmod(wfile_name_proc_FT, S_IRWXU|S_IRGRP|S_IROTH) def write_nls_in(dir=None, NI=None, NIMAX=None, CEXP=None, T2=None, SW=None): """Create the nls.in file for nussampler. @keyword dir: The directory where to create the nls.in file. @type dir: str @keyword NI: The number of increments to use out the full range of increments. @type NI: int @keyword NIMAX: The maximum number of increments in the in-indirect dimension. @type NIMAX: int @keyword CEXP: The maximum number of increments in the in-indirect dimension. @type CEXP: int @keyword T2: The spin-spin relaxation time, the expected time constant characterizing the signal decay in in-direct dimension [s]. @type T2: float @keyword SW: The spectral width in in-directly detected dimension [Hz]. @type SW: float """ # Open file wfile_name = dir + os.sep + 'nls.in' # If the file exists if os.path.exists(wfile_name): print(" nls.in file already exist. Skipping creating new, and nls.hdr_3. %s"%wfile_name) #raise Exception("nls.in file exist.") return wfile = open(wfile_name, "w") lines = [ "NDIM 2", "SPARSE y", "sptype shuffle", "seed %i"%random.randint(1,100000), "CEXP %s"%CEXP, "NIMAX %i 1"%NIMAX, "NI %i 1"%NI, "SW %s 1"%SW, "T2 %s 1"%T2, ] # Write file for line in lines: wfile.write(line + "\n") # Close file. wfile.close() # Call the nussampler on the nls.in file. args = ('nussampler', wfile_name) # Call nussampler and get return code. returncode, line_split = call_prog(args=args) def write_data(out=None, headings=None, data=None, sep=None): """Write out a table of the data to the given file handle. @keyword out: The file handle to write to. @type out: file handle @keyword headings: The optional headings to print out. @type headings: list of str or None @keyword data: The data to print out. @type data: list of list of str @keyword sep: The column separator which, if None, defaults to whitespace. @type sep: str or None """ # No data to print out. if data in [None, []]: return # The number of rows and columns. num_rows = len(data) num_cols = len(data[0]) # Pretty whitespace formatting. if sep == None: # Determine the widths for the headings. widths = [] for j in range(num_cols): if headings != None: if j == 0: widths.append(len(headings[j]) + 2) else: widths.append(len(headings[j])) # No headings. else: widths.append(0) # Determine the maximum column widths for nice whitespace formatting. for i in range(num_rows): for j in range(num_cols): size = len(data[i][j]) if size > widths[j]: widths[j] = size # Convert to format strings. formats = [] for j in range(num_cols): formats.append("%%-%ss" % (widths[j] + 4)) # The headings. if headings != None: out.write(formats[0] % ("# " + headings[0])) for j in range(1, num_cols): out.write(formats[j] % headings[j]) out.write('\n') # The data. for i in range(num_rows): # The row. for j in range(num_cols): out.write(formats[j] % data[i][j]) out.write('\n') # Non-whitespace formatting. else: # The headings. if headings != None: out.write('#') for j in range(num_cols): # The column separator. if j > 0: out.write(sep) # The heading. out.write(headings[j]) out.write('\n') # The data. for i in range(num_rows): # The row. for j in range(num_cols): # The column separator. if j > 0: out.write(sep) # The heading. out.write(data[i][j]) out.write('\n') def contour_plot(dic=None, udic=None, data=None, contour_start=30000., contour_num=20, contour_factor=1.20, ppm=True, show=False, table=None): """Plot the spectrum as contour plot. @keyword dic: The data dictionary, from nmrglue. @type dic: dict @keyword udic: The universal dictionary, from nmrglue. @type udic: dict @keyword data: The spectrum data as 2D numpy array. @type data: 2D numpy array @keyword contour_start: Contour level start value @type contour_start: float @keyword contour_num: Number of contour levels @type contour_num: int @keyword contour_factor: Scaling factor between contour levels @type contour_factor: float @keyword ppm: A flag which if True will make the plot in ppm scale. Else it is in points. @type ppm: bool @keyword show: A flag which if True will make a call to matplotlib.pyplot.show(). @type show: bool @keyword table: Peak table from nmrglue.analysis.peakpick.pick. @type table: recarray @return: The matplotlib.axes.AxesSubplot class, which can be manipulated to add additional text to the axis. @rtype: matplotlib.axes.AxesSubplot """ # Setup plot parameters # http://www.physics.ox.ac.uk/Users/msshin/science/code/matplotlib_cm/ # contour map (colors to use for contours) #cmap = matplotlib.cm.Blues_r #cmap = matplotlib.cm.bwr #cmap = matplotlib.cm.RdBu_r #cmap = matplotlib.cm.coolwarm #cmap = matplotlib.cm.brg cmap = matplotlib.cm.seismic_r # Calculate contour levels cl_pos = contour_start * contour_factor ** numpy.arange(contour_num) cl_neg = - contour_start * contour_factor ** numpy.arange(contour_num)[::-1] cl = numpy.concatenate((cl_neg, cl_pos)) # Create the figure fig = plt.figure() ax = fig.add_subplot(111) # Plot the contours # Plot in ppm scale if ppm: # make ppm scales uc_dim1 = nmrglue.pipe.make_uc(dic, data, dim=1) ppm_dim1 = uc_dim1.ppm_scale() ppm_dim1_0, ppm_dim1_1 = uc_dim1.ppm_limits() uc_dim0 = nmrglue.pipe.make_uc(dic, data, dim=0) ppm_dim0 = uc_dim0.ppm_scale() ppm_dim0_0, ppm_dim0_1 = uc_dim0.ppm_limits() ax.contour(data.T, cl, cmap=cmap, extent=(ppm_dim0_0, ppm_dim0_1, ppm_dim1_0, ppm_dim1_1)) # Decorate ax.set_title("Spectrum at contour %3.1f"%contour_start) ax.set_ylabel("%s (ppm)"%udic[0]['label']) ax.set_xlabel("%s (ppm)"%udic[1]['label']) lim_dim1 = [ppm_dim1_0, ppm_dim1_1] lim_dim0 = [ppm_dim0_0, ppm_dim0_1] ax.set_ylim(max(lim_dim1), min(lim_dim1)) ax.set_xlim(max(lim_dim0), min(lim_dim0)) # If point table scale. if table != None: x_ppm = uc_dim0.unit(table['Y_AXIS'],"ppm") y_ppm = uc_dim1.unit(table['X_AXIS'],"ppm") ax.plot(x_ppm, y_ppm, 'gx', alpha=0.5) # If show. if show: plt.show() # Return ax return ax def write_peak_list(filename=None, x_axis_pts=None, y_axis_pts=None, x_axis_ppm=None, y_axis_ppm=None, int_ref=None, list_int_cov=None, pct_change=3.): # Define headings filew = open(filename, "w") filew.write("VARS INDEX X_AXIS Y_AXIS X_PPM Y_PPM X1 X3 Y1 Y3 HEIGHT"+'\n') filew.write(r"FORMAT %5d %9.3f %9.3f %8.3f %8.3f %4d %4d %4d %4d %+e"+'\n') # Define proportion change prop_ch_p = 1.0 + pct_change / 100. prop_ch_m = 1.0 - pct_change / 100. # Find number of peaks n_peaks = len(int_ref) for i in range(len(x_axis_pts)): index = "%i" % i x_pts = "%i"% int(x_axis_pts[i]) y_pts = "%i"% int(y_axis_pts[i]) x_ppm = "%3.3f"% x_axis_ppm[i] y_ppm = "%3.3f"% y_axis_ppm[i] height = "%1.5e"% int_ref[i] string = "%3s %4s %4s %6s %6s %4s %4s %4s %4s %8s" % (index, x_pts, y_pts, x_ppm, y_ppm, x_pts, x_pts, y_pts, y_pts, height) if list_int_cov != None: for int_cov in list_int_cov: height_cov = int_cov[i] int_prop = height_cov / int_ref[i] int_prop_s = "%1.5f" % int_prop # Test for pct change per peak if int_prop > prop_ch_p or int_prop < prop_ch_m: mark = "x" else: mark = " " # Count all changes int_prop_array = int_cov/int_ref mask_pct_change = masked_where( numpy.logical_or( int_prop_array < prop_ch_m, prop_ch_p < int_prop_array) , int_prop_array) peaks_change = int_prop_array[mask_pct_change.mask] if type(peaks_change) != numpy.ndarray: n_peaks_change = 0 else: n_peaks_change = len(peaks_change) pct_peaks_change = float(n_peaks_change) / float(n_peaks) * 100. # Make rmsd of relative change deviation = int_ref/int_ref - int_prop_array rmsd = numpy.sqrt(numpy.mean(numpy.square(deviation))) string += "| %8s %s %2.1f%% %1.7f" % (int_prop_s, mark, pct_peaks_change, rmsd) filew.write(string + "\n") # Close file. filew.close() if __name__ == "__main__": # Check files are available. files = ['fid', 'fid.com', 'nmrproc.com', 'test.fid'] check_files(files=files) # Create dictionary to store results res_dic = {} res_dic['input'] = {} # Loop over args print("Input arguments") for arg in vars(input_args): print(arg, getattr(input_args, arg), type(getattr(input_args, arg))) res_dic['input']['arg'] = getattr(input_args, arg) # With nmrglue, read the binary transformed spectrum to get information. dic, udic, data = read_spectrum(file='test.fid') # Get the directory to create cwd = os.getcwd() now = time.localtime() #startdir = os.getcwd() + os.sep + "qNLS_%i%02i%02i_%02i%02i%02i" % (now[0],now[1], now[2], now[3], now[4], now[5]) startdir = cwd + os.sep + "qNLS_%i%02i%02i" % (now[0],now[1], now[2]) # Get the number of points in the direct dimension np = udic[1]['size']*2 # Get the number of real + imaginary reconstructed points. td1 = udic[0]['size'] # Get the number of increments pairs in the in-direct dimension. ni = td1 / 2 # Calculate R2 R2 = 1.0 / input_args.T2 # Get the obsfreq1 in MHz. obsfreq1 = udic[0]['obs'] # Get the sw in the in-direct dimension, in Hz sw = udic[0]['sw'] # Calculate the sw in ppm. sw_ppm = sw / obsfreq1 # Get path to dpoisson7.1.1. NUSScore script from Peter E. Wright. if sys.platform == "darwin": path_dpoisson = os.path.dirname(os.path.realpath(__file__))+os.sep+"Aoto_Fenwick_Kroon_Wright_2014_NUSScore"+os.sep+"mac64"+os.sep+"dpoisson7.1.1.mac" else: path_dpoisson = os.path.dirname(os.path.realpath(__file__))+os.sep+"Aoto_Fenwick_Kroon_Wright_2014_NUSScore"+os.sep+"linux32"+os.sep+"dpoisson7.1.1" test = ni < 400 if not test: print("\nNumber of increments in the in-direct dimension is to high: %i\n"%ni) raise Exception("NI is found to be to high. As a safety measure, it is expected to be under 400.") # Create list with nearest intergers of NI, from sampling fractions. sf_arr = numpy.array(input_args.sf) # Make NI array ni_arr = ni * sf_arr / 100. # Convert to nearest even ni. ni_arr = numpy.around(ni_arr/2)*2 # Convert to int16 ni_arr = numpy.array( ni_arr, dtype=numpy.int16 ) # Then create the directories. # Loop over the sampling fractions. sf_dirs = [] for sf in input_args.sf: cur_dir = '%02dpct'%sf sf_dirs.append(cur_dir) # Make list of ni and proc directories to create. # The first one is with poisson ni_dirs = ["0_test_poisson.fid"] proc_dirs = ["0_test_poisson.proc"] for j in range(1, input_args.N + 1): cur_dir = '%02d.fid'%j ni_dirs.append(cur_dir) cur_dir = '%02d.proc'%j proc_dirs.append(cur_dir) # Store to res_dic res_dic['sf_arr'] = sf_arr res_dic['ni_arr'] = ni_arr res_dic['sf_dirs'] = sf_dirs res_dic['ni_dirs'] = ni_dirs res_dic['proc_dirs'] = proc_dirs # Loop over sample fraction level. for i, sf_dir in enumerate(sf_dirs): cur_ni = ni_arr[i] # Store to dic res_dic[sf_dir] = {} res_dic[sf_dir]['cur_ni'] = cur_ni # Create dir for dpoisson out_dpoisson = startdir + os.sep + 'NUSScore' + os.sep + sf_dir if not os.path.exists(out_dpoisson): os.makedirs(out_dpoisson) # Calculate the current coverage cur_cov = float(cur_ni)/float(ni) # The filename for the best schedule. fname_nus_top_out = out_dpoisson + os.sep + "score" + os.sep + "nus_top.out" if not os.path.exists(fname_nus_top_out): # Create range of schdedules with dpoisson print("\nCreating %i NUSScedules with dpoisson7.1.1"%input_args.N_NUS_SCHEDULES) # Constant time: 1/0 for yes/no constant_time = 0 poisson_args = ["%1.7f"%cur_cov, "%i"%td1, "1", "%2.1f"%R2, "1", "%i"%constant_time, "0", "%2.3f"%obsfreq1, "1", "%2.2f"%sw_ppm, "1", "0", "%i"%input_args.N_NUS_SCHEDULES, "1", "%s"%out_dpoisson] print("Created with args:", poisson_args) print("%s"%(" ".join([path_dpoisson] + poisson_args))) returncode, line_split = call_prog(args=[path_dpoisson] + poisson_args, verbose=True) else: print("\nNUSScedules with dpoisson7.1.1 already exists. Using these.\n") # Open the file. file_nus_top_out = open(fname_nus_top_out, "r") lines_nus_top_out = file_nus_top_out.readlines() # Close the file. file_nus_top_out.close() # Get filename for best nus schedule fname_best_nus = out_dpoisson + os.sep + "lists" + os.sep + lines_nus_top_out[3].split()[0] # Create dir for restoring. create_sf_dir = startdir + os.sep + sf_dir if not os.path.exists(create_sf_dir): os.makedirs(create_sf_dir) # Then create reference dir. create_ni_ref_dir = create_sf_dir + os.sep + '00_ref.fid' if not os.path.exists(create_ni_ref_dir): os.makedirs(create_ni_ref_dir) # Make a full ni. write_nls_in(dir=create_ni_ref_dir, NI=ni, NIMAX=ni, T2=input_args.T2, SW=sw) # Then create the ni shuffled binary data make_nus_data(dir_from=cwd, dir_to=create_ni_ref_dir, np=np, ni=ni) # Now write: proc_FT.sh, proc_comdd_before.sh, proc_comdd_after.sh, fidSP.com, recFT.com create_proc_ref_dir = create_sf_dir + os.sep + '00_ref.proc' if not os.path.exists(create_proc_ref_dir): os.makedirs(create_proc_ref_dir) # Write the proc files. 'proc_comdd_before.sh', 'proc_comdd_after.sh' # The first one creates the MDD data # The second one is for coMDD solving. write_proc(dir=create_proc_ref_dir, FID='../00_ref', NUS_POINTS=ni, FST_PNT_PPM=input_args.FST_PNT_PPM, ROISW=input_args.ROISW, SRSIZE=input_args.SRSIZE, CEXP=input_args.CEXP, MDDTHREADS=input_args.MDDTHREADS, NCOMP=input_args.NCOMP, NITER=input_args.NITER, MDD_NOISE=input_args.MDD_NOISE) # Write fidSP.com and recFT.com file. write_fidSP_recFT(dir_from=cwd, dir_to=create_proc_ref_dir, cur_ni=ni) # Copy over nls.in and nls.hdr_3. shutil.copy(create_ni_ref_dir + os.sep + 'nls.in', create_proc_ref_dir) shutil.copy(create_ni_ref_dir + os.sep + 'nls.hdr_3', create_proc_ref_dir) # If MDD directory is missing, call initial script to create MDD files. if not os.path.isdir(create_proc_ref_dir + os.sep + 'MDD'): # Change current directory os.chdir(create_proc_ref_dir) # Call script to create files. call_prog(args=['proc_comdd_before.sh']) # Change back again os.chdir(cwd) # Now do the coMDD method to create .ft2 files. # Then create ni dirs. for j, ni_dir in enumerate(ni_dirs): create_ni_dir = create_sf_dir + os.sep + ni_dir if not os.path.exists(create_ni_dir): os.makedirs(create_ni_dir) # Make for ni. write_nls_in(dir=create_ni_dir, NI=cur_ni, NIMAX=ni, CEXP=input_args.CEXP, T2=input_args.T2, SW=sw) # If poisson dir, replace the nls.hdr_3 file with best scored NUSSchedule. if ni_dir == "0_test_poisson.fid": shutil.copy(fname_best_nus, create_ni_dir + os.sep + 'nls.hdr_3') # Then create the ni shuffled binary data make_nus_data(dir_from=cwd, dir_to=create_ni_dir, np=np, ni=ni) # Now write: proc_FT.sh, proc_comdd_before.sh, proc_comdd_after.sh, fidSP.com, recFT.com proc_dir = proc_dirs[j] create_proc_dir = create_sf_dir + os.sep + proc_dir if not os.path.exists(create_proc_dir): os.makedirs(create_proc_dir) # Write the proc files. 'proc_comdd_before.sh', 'proc_comdd_after.sh' # The first one creates the MDD data # The second one is for coMDD solving. FID = '..' + os.sep + proc_dir.split('.proc')[0] write_proc(dir=create_proc_dir, FID=FID, NUS_POINTS=cur_ni, FST_PNT_PPM=input_args.FST_PNT_PPM, ROISW=input_args.ROISW, SRSIZE=input_args.SRSIZE, CEXP=input_args.CEXP, MDDTHREADS=input_args.MDDTHREADS, NCOMP=input_args.NCOMP, NITER=input_args.NITER, MDD_NOISE=input_args.MDD_NOISE) # Write fidSP.com and recFT.com file. write_fidSP_recFT(dir_from=cwd, dir_to=create_proc_dir, cur_ni=cur_ni) # Copy over nls.in and nls.hdr_3. shutil.copy(create_ni_dir + os.sep + 'nls.in', create_proc_dir) shutil.copy(create_ni_dir + os.sep + 'nls.hdr_3', create_proc_dir) # If MDD directory is missing, call initial script to create MDD files. if not os.path.isdir(create_proc_dir + os.sep + 'MDD'): # Change current directory os.chdir(create_proc_dir) # Call script to create files. call_prog(args=['proc_comdd_before.sh']) # Change back again os.chdir(cwd) # Then create coMDD dir coMDD_dir = create_sf_dir + os.sep + 'coMDD' if not os.path.isdir(coMDD_dir): os.makedirs(coMDD_dir) # Then create coMDD.hd. wfile_name_coMDD_hd = coMDD_dir + os.sep + 'coMDD.hd' wfile_coMDD_hd = open(wfile_name_coMDD_hd, "w") # Collect all proc dirs all_proc_dirs = ['00_ref.proc'] + proc_dirs res_dic[sf_dir]['all_proc_dirs'] = all_proc_dirs for j, proc_dir in enumerate(all_proc_dirs): FID = proc_dir.split('.proc')[0] proc_pos = '..' + os.sep + proc_dir + os.sep + 'MDD' + os.sep + r'region%02d.mddH' # It is the reading of CEXP in nls.in, that makes coMDD/hd01.mdd be rmdd. nls_in_pos = '..' + os.sep + proc_dir + os.sep + 'nls.in' string = "%i %s 1.0 %s %s 1 2"%(j, FID, proc_pos, nls_in_pos) wfile_coMDD_hd.write(string + "\n") wfile_coMDD_hd.close() # Then get number of regions, and convert file to HD data assembling. nreg = 0 region_file = open(create_proc_ref_dir + os.sep + 'regions.runs', "r") hd_region_file = open(coMDD_dir + os.sep + 'regions.runs', "w") for line in region_file: if "mddsolver" in line: nreg += 1 wstring = line.replace("./MDD/region", "hd"); hd_region_file.write(wstring) region_file.close() hd_region_file.close() # Then do HD data assembling list_files = glob.glob(coMDD_dir+ os.sep + 'hd*.mdd') if len(list_files) != nreg: print("HD data assembling") # Change current directory os.chdir(coMDD_dir) # Call script to create files. call_prog(args=['setHD', 'coMDD.hd', 'mdd', '%i'%nreg, r'hd%02d.mdd']) # Change back again os.chdir(cwd) # Test if do MDD calculation list_files = glob.glob(coMDD_dir+ os.sep + 'hd*.res') if len(list_files) != nreg: # Then do MDD calculation print("MDD calculation") # Change current directory os.chdir(coMDD_dir) # Call script to create files. call_prog(args=['queMM.sh', 'regions.runs']) # Change back again os.chdir(cwd) # Make HD data disassembling # Change current directory os.chdir(coMDD_dir) # Call script to create files. for j, proc_dir in enumerate(all_proc_dirs): proc_MDD_dir = create_sf_dir + os.sep + proc_dir + os.sep + 'MDD' list_files = glob.glob(proc_MDD_dir + os.sep + 'region*.res') if len(list_files) != nreg: print("HD data disassembling in %s"%proc_MDD_dir) proc_pos = '..' + os.sep + proc_dir + os.sep + 'MDD' + os.sep + r'region%02d.res' args = ['setHD', 'coMDD.hd', 'res', '%i'%nreg, "%s"%proc_pos, r"hd%02d.res", str(j)] call_prog(args=args) # Change back again os.chdir(cwd) # Then assemble data for j, proc_dir in enumerate(all_proc_dirs): cur_proc_dir = create_sf_dir + os.sep + proc_dir path_ft2_file = cur_proc_dir + os.sep + 'test.ft2' if not os.path.exists(path_ft2_file): # Change current directory os.chdir(cur_proc_dir) # Call script to create files. print("Assembling data in: %s"%cur_proc_dir) call_prog(args=['proc_comdd_after.sh']) # Change back again os.chdir(cwd) else: print("File exists. I do not produce .ft2 file again.: %s"%path_ft2_file) ### Now do comparisons. print("\nNow making figures and reports.") # Producefile for reference. if input_args.ref_FT: REF_ft2file_name = 'test_REF_FT.ft2' path_ref_REF_ft2file = create_proc_ref_dir + os.sep + REF_ft2file_name else: REF_ft2file_name = 'test_REF_coMDD.ft2' shutil.copy(create_proc_ref_dir + os.sep + 'test.ft2', create_proc_ref_dir + os.sep + REF_ft2file_name) path_ref_REF_ft2file = create_proc_ref_dir + os.sep + REF_ft2file_name # test.ft2 has to exist for coMDD if not os.path.exists(path_ref_REF_ft2file): # Change current directory os.chdir(create_proc_ref_dir) # Call script to create files. call_prog(args=['proc_FT.sh']) # Change back again os.chdir(cwd) # Now read data for reference returncode, line_split = call_prog(args=['showApod', path_ref_REF_ft2file], verbose=False) rmsd_ref = extract_rmsd(lines=line_split) res_dic[sf_dir]['ref'] = {} res_dic[sf_dir]['ref']['rmsd'] = rmsd_ref # With nmrglue, read the fourier transformed spectrum to get information. dic_ref, udic_ref, data_ref = read_spectrum(file=path_ref_REF_ft2file) res_dic[sf_dir]['ref']['dic'] = dic_ref res_dic[sf_dir]['ref']['udic'] = udic_ref res_dic[sf_dir]['ref']['data'] = data_ref # Now do a peak list table = nmrglue.analysis.peakpick.pick(data=data_ref, pthres=20*rmsd_ref, nthres=None, algorithm='connected', est_params=False, cluster=False, table=True) #table = nmrglue.analysis.peakpick.pick(data=data_ref, pthres=20*rmsd_ref, nthres=None, algorithm='downward', est_params=False, cluster=False, table=True) ## Measure the intensity data_ref_int = data_ref[table['Y_AXIS'].astype(int), table['X_AXIS'].astype(int)] # Now convert points to ppm. uc_dim0 = nmrglue.pipe.make_uc(dic_ref, data_ref, dim=0) uc_dim1 = nmrglue.pipe.make_uc(dic_ref, data_ref, dim=1) y_axisppm = uc_dim0.unit(table['Y_AXIS'], "ppm") x_axisppm = uc_dim1.unit(table['X_AXIS'], "ppm") # Try a contour plot. print("\nNow making contour plot for reference.") png_path = startdir + os.sep + "spec_" + REF_ft2file_name + ".png" if not os.path.isfile(png_path): contour_plot(dic=dic_ref, udic=udic_ref, data=data_ref, contour_start=20*rmsd_ref, contour_num=10, contour_factor=1.20, ppm=True, show=False, table=table) plt.savefig(png_path, format='png', dpi=600) # Close figure. plt.close("all") # Make a histogram print("\nNow making histogram of intensities for reference.") ax, amp, mu, sigma, xlim_ref, ylim_ref = hist_plot(ndarray=data_ref, show=False) res_dic[sf_dir]['ref']['hist'] = [amp, mu, sigma] png_path = startdir + os.sep + "hist_" + REF_ft2file_name + ".png" if not os.path.isfile(png_path): plt.savefig(png_path, format='png', dpi=600) # Close figure. plt.close("all") # Flatten data data_ref_flat = data_ref.flatten() # Make selection masks sigma3 = mu + 3*sigma sigma10 = mu + 10*sigma sigma100 = mu + 100*sigma sigma1000 = mu + 1000*sigma mask_to_sigma3 = masked_where(data_ref_flat < sigma3, data_ref_flat) mask_3_to_10 = masked_where( numpy.logical_and( sigma3 <= data_ref_flat, data_ref_flat < sigma10) , data_ref_flat) mask_10_to_100 = masked_where( numpy.logical_and( sigma10 <= data_ref_flat, data_ref_flat < sigma100) , data_ref_flat) mask_100_to_1000 = masked_where( numpy.logical_and( sigma100 <= data_ref_flat, data_ref_flat < sigma1000 ) , data_ref_flat) mask_from_1000 = masked_where( sigma1000 <= data_ref_flat, data_ref_flat) ## Collect masks for graphs and their hex color. sn_masks = [ [r'$I < 3\sigma$', "#FC0000", mask_to_sigma3, 'to_s3'], [r'$3\sigma \leq I < 10\sigma$', "#F0FC00", mask_3_to_10, 's3_to_10'], [r'$10\sigma \leq I < 100\sigma$', "#0DFC00", mask_10_to_100, 's10_to_s100'], [r'$100\sigma \leq I < 1000\sigma$', "#00FCF8", mask_100_to_1000, 's100_to_s1000'], [r'$1000\sigma \leq I\sigma$', "#FC00F8", mask_from_1000, 'from_s1000'], ] # Now make report for pct pct_results_name = startdir + os.sep + "pct_%s_results.txt"%(sf_dir) pct_results = open(pct_results_name, 'w') # Collect header headers = [] # Collect data datacsv = [] sn_masks_used = [] for label, color, sel_mask, dickey in sn_masks: data_ref_mask = data_ref_flat[sel_mask.mask] if type(data_ref_mask) != numpy.ndarray: continue pct = float(len(data_ref_mask)) / float(len(data_ref_flat)) * 100. sn_masks_used.append([label, color, sel_mask, dickey, pct]) headers.append(dickey) datacsv.append("%2.1f"%pct) # Write data write_data(out=pct_results, headings=headers, data=[datacsv]) pct_results.close() # Then go through all processed directories # Collect proc ints proc_ints = [] for j, proc_dir in enumerate(all_proc_dirs): cur_proc_dir = create_sf_dir + os.sep + proc_dir path_ft2_file = cur_proc_dir + os.sep + 'test.ft2' returncode, line_split = call_prog(args=['showApod', path_ft2_file], verbose=False) rmsd = extract_rmsd(lines=line_split) # Store to results dic res_dic[sf_dir][proc_dir] = {} res_dic[sf_dir][proc_dir]['rmsd'] = rmsd # With nmrglue, read the fourier transformed spectrum to get information. dic_cur, udic_cur, data_cur = read_spectrum(file=path_ft2_file) res_dic[sf_dir][proc_dir]['dic'] = dic_cur res_dic[sf_dir][proc_dir]['udic'] = udic_cur res_dic[sf_dir][proc_dir]['data'] = data_cur # Measure the intensity of peaks. data_cur_int = data_cur[table['Y_AXIS'].astype(int), table['X_AXIS'].astype(int)] proc_ints.append(data_cur_int) # Try a contour plot. png_path = startdir + os.sep + "spect_%s_%s.png"%(sf_dir, proc_dir) if not os.path.isfile(png_path): contour_plot(dic=dic_cur, udic=udic_cur, data=data_cur, contour_start=20*rmsd_ref, contour_num=10, contour_factor=1.20, ppm=True, show=False, table=table) plt.savefig(png_path, format='png', dpi=600) # Close figure. plt.close("all") # Make a residual intensity spectrum. data_resi = data_cur - data_ref path_resi_spec = cur_proc_dir + os.sep + 'test_resi.ft2' nmrglue.fileio.pipe.write(filename=path_resi_spec, dic=dic_cur, data=data_resi, overwrite=True) # Try a contour plot. png_path = startdir + os.sep + "resi_spect_%s_%s.png"%(sf_dir, proc_dir) if not os.path.isfile(png_path): contour_plot(dic=dic_cur, udic=udic_cur, data=data_resi, contour_start=6*rmsd_ref, contour_num=10, contour_factor=1.20, ppm=True, show=False, table=table) plt.savefig(png_path, format='png', dpi=600) # Close figure. plt.close("all") # Make a histogram ax, amp, mu, sigma, xlim, ylim = hist_plot(ndarray=data_cur, show=False) res_dic[sf_dir][proc_dir]['hist'] = [amp, mu, sigma] # Set same limits as ref ax.set_xlim(xlim_ref) ax.set_ylim(ylim_ref) png_path = startdir + os.sep + "hist_%s_%s.png"%(sf_dir, proc_dir) if not os.path.isfile(png_path): plt.savefig(png_path, format='png', dpi=600) # Close figure. plt.close("all") print("Made figure: %s"%png_path) # Make a correlation plot fig = plt.figure() ax = fig.add_subplot(111) # Flatten data data_cur_flat = data_cur.flatten() # Try get the linear correlation a, r_xy = linear_corr(x=data_ref_flat, y=data_cur_flat) res_dic[sf_dir][proc_dir]['corr'] = [a, r_xy] # Make line. line = numpy.array( [data_ref_flat.min(), data_ref_flat.max()] ) ax.plot(line, line, 'g-', linewidth=0.5, label='ref vs ref.') ax.plot(line, line*a, 'b-', linewidth=0.2, label='Linear') # Collect for different signal levels. res_dic[sf_dir][proc_dir]['corr_s'] = {} # Loop over data mask #ax.plot(data_ref_flat, data_cur_flat, 'b.', markersize=2, label='all int') for label, color, sel_mask, dickey, pct in sn_masks_used: data_ref_mask = data_ref_flat[sel_mask.mask] data_cur_mask = data_cur_flat[sel_mask.mask] a_mask, r_xy_mask = linear_corr(x=data_ref_mask, y=data_cur_mask) res_dic[sf_dir][proc_dir]['corr_s'][dickey] = [a_mask, r_xy_mask] deviation = data_cur_mask - data_ref_mask rmsd_mask = numpy.sqrt(numpy.mean(numpy.square(deviation))) ax.plot(data_ref_mask, data_cur_mask, '.', color=color, markersize=2, label='%s , pct=%2.1f, a=%1.2f, r_xy^2=%3.4f, rmsd=%3.4f'%(label, pct, a_mask, r_xy_mask**2, rmsd_mask)) # Set text. ax.set_xlabel("All spectrum intensities for reference") ax.set_ylabel("All spectrum intensities for method") ax.annotate("a=%3.6f\nr_xy=%3.6f\nr_xy^2=%3.6f"%(a, r_xy, r_xy**2), xy=(data_ref_flat.min(), data_cur_flat.max()), xycoords="data", size=8, va="center", horizontalalignment="center", bbox=dict(boxstyle="round", facecolor="w")) ax.legend(loc='lower right', prop={'size':6}) png_path = startdir + os.sep + "corr_%s_%s.png"%(sf_dir, proc_dir) if not os.path.isfile(png_path): plt.savefig(png_path, format='png', dpi=600) # Close figure. plt.close("all") print("Made figure: %s"%png_path) ## Make relative comparisons # Define the ratio weighted values g = data_ref_int/data_ref_int h = data_cur_int/data_ref_int # Calculate the deviation d_gh = g - h # Calculate the mean of the deviations mean_d_gh = numpy.mean(d_gh) # Calculate the standard deviations std_d_gh = numpy.std(d_gh, ddof=1) # Calculate the root mean square deviation rmsd_gh = numpy.sqrt(numpy.mean(numpy.square(d_gh))) # Calculate the pooled error g_err = rmsd_ref / data_ref_int h_err = rmsd / data_ref_int pool_std_gh= numpy.sqrt( numpy.mean(numpy.square(g_err) + numpy.square(h_err)) ) # Make a plot fig = plt.figure() ax = fig.add_subplot(111) # Make line. ax.plot(numpy.zeros_like(d_gh), d_gh, 'b.', label='differences of relative change') ax.errorbar(mean_d_gh, mean_d_gh, yerr=std_d_gh, fmt='r.', label='mean of differences of relative change') max_dev = numpy.max(numpy.abs(d_gh)) ax.set_ylim([-max_dev, max_dev]) ax.set_xlim([-max_dev, max_dev]) png_path = startdir + os.sep + "rel_%s_%s.png"%(sf_dir, proc_dir) if not os.path.isfile(png_path): plt.savefig(png_path, format='png', dpi=600) # Close figure. plt.close("all") print("Made figure: %s"%png_path) # Write intensities peaks_results_name = startdir + os.sep + "peaks_%s_results.tab"%(sf_dir) write_peak_list(filename=peaks_results_name, x_axis_pts=table['X_AXIS'], y_axis_pts=table['Y_AXIS'], x_axis_ppm=x_axisppm, y_axis_ppm=y_axisppm, int_ref=data_ref_int, list_int_cov=proc_ints) # Now make report for Hist hist_results_name = startdir + os.sep + "hist_%s_results.txt"%(sf_dir) hist_results = open(hist_results_name, 'w') # Collect header headers = ['i', 'data', 'showApod_rmsd', 'hist_sigma', 'hist_amp', 'hist_mu', ] # Collect data datacsv = [] datacsv_ref = ["00", '%11s'%'REF', '%4.2f'%res_dic[sf_dir]['ref']['rmsd'], '%4.2f'%res_dic[sf_dir]['ref']['hist'][2], '%4.2f'%res_dic[sf_dir]['ref']['hist'][0], '%4.2f'%res_dic[sf_dir]['ref']['hist'][1]] datacsv.append(datacsv_ref) for j, proc_dir in enumerate(all_proc_dirs): datacsv_cur = ["%02d"%(j+1), '%11s'%proc_dir, '%4.2f'%res_dic[sf_dir][proc_dir]['rmsd'], '%4.2f'%res_dic[sf_dir][proc_dir]['hist'][2], '%4.2f'%res_dic[sf_dir][proc_dir]['hist'][0], '%4.2f'%res_dic[sf_dir][proc_dir]['hist'][1]] datacsv.append(datacsv_cur) # Write data write_data(out=hist_results, headings=headers, data=datacsv) hist_results.close() # Now make report for correlation corr_results_name = startdir + os.sep + "corr_%s_results.txt"%(sf_dir) corr_results = open(corr_results_name, 'w') # Collect header #headers = ['i', 'data', 'a', 'r_xy', 'r_xy^2'] headers = ['i', 'data', 'a', 'r_xy^2'] for label, color, sel_mask, dickey, pct in sn_masks_used: headers.append('a_%s'%dickey) #headers.append('r_xy_%s'%dickey) headers.append('r_xy^2_%s'%dickey) # Collect data datacsv = [] for j, proc_dir in enumerate(all_proc_dirs): #datacsv_cur = ["%02d"%(j+1), '%11s'%proc_dir, '%3.6f'%res_dic[sf_dir][proc_dir]['corr'][0], '%3.6f'%res_dic[sf_dir][proc_dir]['corr'][1], '%3.6f'%res_dic[sf_dir][proc_dir]['corr'][1]**2] datacsv_cur = ["%02d"%(j+1), '%11s'%proc_dir, '%3.6f'%res_dic[sf_dir][proc_dir]['corr'][0], '%3.6f'%res_dic[sf_dir][proc_dir]['corr'][1]**2] for label, color, sel_mask, dickey, pct in sn_masks_used: datacsv_cur.append('%3.6f'%res_dic[sf_dir][proc_dir]['corr_s'][dickey][0]) #datacsv_cur.append('%3.6f'%res_dic[sf_dir][proc_dir]['corr_s'][dickey][1]) datacsv_cur.append('%3.6f'%res_dic[sf_dir][proc_dir]['corr_s'][dickey][1]**2) datacsv.append(datacsv_cur) # Write data write_data(out=corr_results, headings=headers, data=datacsv) corr_results.close() # Now make a residual histogram. # Since the intensities are modulated by 1.2, we use the full 00_ref.proc as reference. data_ref = res_dic[sf_dir]['00_ref.proc']['data'] # Loop over all proc dirs. for j, proc_dir in enumerate(proc_dirs): data_cur = res_dic[sf_dir][proc_dir]['data'] # Data residual data_resi = data_cur - data_ref # Make a histogram ax, amp, mu, sigma, xlim, ylim = hist_plot(ndarray=data_resi, show=False) res_dic[sf_dir][proc_dir]['residual_hist'] = [amp, mu, sigma] # Set same limits as ref #ax.set_xlim(mu-6*sigma, mu+6*sigma) ax.set_xlim(-10*rmsd_ref, +10*rmsd_ref) #ax.set_ylim(ylim_ref) png_path = startdir + os.sep + "residual_hist_%s_%s.png"%(sf_dir, proc_dir) if not os.path.isfile(png_path): plt.savefig(png_path, format='png', dpi=600) # Close figure. plt.close("all") print("Made figure: %s"%png_path) # Now make report for Residual Hist hist_results_name = startdir + os.sep + "residual_hist_%s_results.txt"%(sf_dir) hist_results = open(hist_results_name, 'w') # Collect header headers = ['i', 'data', 'hist_sigma', 'hist_amp', 'hist_mu', ] # Collect data datacsv = [] for j, proc_dir in enumerate(proc_dirs): datacsv_cur = ["%02d"%(j+2), '%11s'%proc_dir, '%4.2f'%res_dic[sf_dir][proc_dir]['residual_hist'][2], '%4.2f'%res_dic[sf_dir][proc_dir]['residual_hist'][0], '%4.2f'%res_dic[sf_dir][proc_dir]['residual_hist'][1]] datacsv.append(datacsv_cur) # Write data write_data(out=hist_results, headings=headers, data=datacsv) hist_results.close() # Print elapsed time for running script. elapsed_time = time.time() - start_time print("--- %3.1f s seconds for run time---" % elapsed_time )
gpl-3.0
-3,546,921,911,397,787,000
39.513787
398
0.583654
false
pypingou/kittystore
kittystore/storm/store.py
1
20364
# -*- coding: utf-8 -*- """ Copyright (C) 2012 Aurélien Bompard <[email protected]> Author: Aurélien Bompard <[email protected]> This program 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 2 of the License, or (at your option) any later version. See http://www.gnu.org/copyleft/gpl.html for the full text of the license. """ from __future__ import absolute_import import datetime from email.utils import unquote from zope.interface import implements from mailman.interfaces.messages import IMessageStore from storm.locals import Desc from storm.expr import And, Or from dateutil.tz import tzutc from kittystore import MessageNotFound from kittystore.utils import parseaddr, parsedate from kittystore.utils import header_to_unicode from kittystore.scrub import Scrubber from kittystore.utils import get_ref_and_thread_id from .model import List, Email, Attachment, Thread, EmailFull class StormStore(object): """ Storm-powered interface to query emails from the database. """ implements(IMessageStore) def __init__(self, db, debug=False): """ Constructor. Create the session using the engine defined in the url. :param db: the Storm store object :param debug: a boolean to set the debug mode on or off. """ self.db = db self.debug = debug # IMessageStore methods def add(self, message): """Add the message to the store. :param message: An email.message.Message instance containing at least a unique Message-ID header. The message will be given an X-Message-ID-Hash header, overriding any existing such header. :returns: The calculated X-Message-ID-Hash header. :raises ValueError: if the message is missing a Message-ID header. The storage service is also allowed to raise this exception if it find, but disallows collisions. """ # Not sure this is useful: a message should always be in a list raise NotImplementedError def add_to_list(self, mlist, message): """Add the message to a specific list of the store. :param mlist: The mailing-list object, implementing mailman.interfaces.mailinglist.IMailingList. :param message: An email.message.Message instance containing at least a unique Message-ID header. The message will be given an X-Message-ID-Hash header, overriding any existing such header. :returns: The calculated X-Message-ID-Hash header. :raises ValueError: if the message is missing a Message-ID header. The storage service is also allowed to raise this exception if it find, but disallows collisions. """ list_name = unicode(mlist.fqdn_listname) # Create the list if it does not exist l = self.db.find(List, List.name == list_name).one() if l is None: l = List(list_name) self.db.add(l) l.display_name = mlist.display_name if not message.has_key("Message-Id"): raise ValueError("No 'Message-Id' header in email", message) msg_id = unicode(unquote(message['Message-Id'])) email = Email(list_name, msg_id) if self.is_message_in_list(list_name, email.message_id): print ("Duplicate email from %s: %s" % (message['From'], message.get('Subject', '""'))) return email.message_id_hash # the message.as_string() call must be done before scrubbing email_full = EmailFull(list_name, msg_id, message.as_string()) # Find thread id new_thread = False ref, thread_id = get_ref_and_thread_id(message, list_name, self) if thread_id is None: new_thread = True # make up the thread_id if not found thread_id = email.message_id_hash email.thread_id = thread_id email.in_reply_to = ref from_name, from_email = parseaddr(message['From']) from_name = header_to_unicode(from_name) email.sender_name = from_name.strip() email.sender_email = unicode(from_email).strip() email.subject = header_to_unicode(message.get('Subject')) msg_date = parsedate(message.get("Date")) if msg_date is None: # Absent or unparseable date msg_date = datetime.datetime.now() if msg_date.tzinfo is not None: msg_date = msg_date.astimezone(tzutc()).replace(tzinfo=None) email.date = msg_date utcoffset = msg_date.utcoffset() if utcoffset is None: email.timezone = 0 else: # in minutes email.timezone = ( (utcoffset.days * 24 * 60 * 60) + utcoffset.seconds) / 60 scrubber = Scrubber(list_name, message) # warning: scrubbing modifies the msg in-place email.content, attachments = scrubber.scrub() #category = 'Question' # TODO: enum + i18n ? #if ('agenda' in message.get('Subject', '').lower() or # 'reminder' in message.get('Subject', '').lower()): # # i18n! # category = 'Agenda' if new_thread: thread = Thread(list_name, thread_id, email.date) else: thread = self.db.find(Thread, And( Thread.list_name == list_name, Thread.thread_id == thread_id, )).one() thread.date_active = email.date self.db.add(thread) self.db.add(email) self.db.add(email_full) self.flush() for attachment in attachments: self.add_attachment(list_name, msg_id, *attachment) return email.message_id_hash def delete_message(self, message_id): """Remove the given message from the store. :param message: The Message-ID of the mesage to delete from the store. :raises LookupError: if there is no such message. """ # Not sure this is useful: a message should always be in a list raise NotImplementedError def delete_message_from_list(self, list_name, message_id): """Remove the given message for a specific list from the store. :param list_name: The fully qualified list name to which the message should be added. :param message: The Message-ID of the mesage to delete from the store. :raises LookupError: if there is no such message. """ msg = self.get_message_by_id_from_list(list_name, message_id) if msg is None: raise MessageNotFound(list_name, message_id) self.db.delete(msg) # Remove the thread if necessary thread = self.db.find(Thread, And( Thread.list_name == msg.list_name, Thread.thread_id == msg.thread_id, )).one() if len(thread.emails) == 0: self.db.delete(thread) self.flush() def get_list_size(self, list_name): """ Return the number of emails stored for a given mailing list. :arg list_name, name of the mailing list in which this email should be searched. """ return self.db.find(Email, Email.list_name == unicode(list_name)).count() def get_message_by_hash(self, message_id_hash): """Return the message with the matching X-Message-ID-Hash. :param message_id_hash: The X-Message-ID-Hash header contents to search for. :returns: The message, or None if no matching message was found. """ # Not sure this is useful: a message should always be in a list raise NotImplementedError def get_message_by_hash_from_list(self, list_name, message_id_hash): """Return the message with the matching X-Message-ID-Hash. :param message_id_hash: The X-Message-ID-Hash header contents to search for. :returns: The message, or None if no matching message was found. """ return self.db.find(Email, And( Email.list_name == unicode(list_name), Email.message_id_hash == unicode(message_id_hash) )).one() def get_message_by_id(self, message_id): """Return the message with a matching Message-ID. :param message_id: The Message-ID header contents to search for. :returns: The message, or None if no matching message was found. """ # Not sure this is useful: a message should always be in a list raise NotImplementedError def get_message_by_id_from_list(self, list_name, message_id): """Return the message with a matching Message-ID. :param list_name: The fully qualified list name to which the message should be added. :param message_id: The Message-ID header contents to search for. :returns: The message, or None if no matching message was found. """ msg = self.db.find(Email, And( Email.list_name == unicode(list_name), Email.message_id == unicode(message_id) )).one() return msg def search_list_for_content(self, list_name, keyword): """ Returns a list of email containing the specified keyword in their content. :param list_name: name of the mailing list in which this email should be searched. :param keyword: keyword to search in the content of the emails. """ emails = self.db.find(Email, And( Email.list_name == unicode(list_name), Email.content.ilike(u'%{0}%'.format(keyword)) )).order_by(Desc(Email.date)) return emails def search_list_for_content_subject(self, list_name, keyword): """ Returns a list of email containing the specified keyword in their content or their subject. :param list_name: name of the mailing list in which this email should be searched. :param keyword: keyword to search in the content or subject of the emails. """ emails = self.db.find(Email, And( Email.list_name == unicode(list_name), Or( Email.content.ilike(u'%{0}%'.format(keyword)), Email.subject.ilike(u'%{0}%'.format(keyword)), ))).order_by(Desc(Email.date)) return emails def search_list_for_sender(self, list_name, keyword): """ Returns a list of email containing the specified keyword in the name or email address of the sender of the email. :param list_name: name of the mailing list in which this email should be searched. :param keyword: keyword to search in the database. """ emails = self.db.find(Email, And( Email.list_name == unicode(list_name), Or( Email.sender_name.ilike(u'%{0}%'.format(keyword)), Email.sender_email.ilike(u'%{0}%'.format(keyword)), ))).order_by(Desc(Email.date)) return emails def search_list_for_subject(self, list_name, keyword): """ Returns a list of email containing the specified keyword in their subject. :param list_name: name of the mailing list in which this email should be searched. :param keyword: keyword to search in the subject of the emails. """ emails = self.db.find(Email, And( Email.list_name == unicode(list_name), Email.subject.ilike(u'%{0}%'.format(keyword)), )).order_by(Desc(Email.date)) return emails @property def messages(self): """An iterator over all messages in this message store.""" raise NotImplementedError # Other methods (not in IMessageStore) def is_message_in_list(self, list_name, message_id): """Return the number of messages with a matching Message-ID in the list. :param list_name: The fully qualified list name to which the message should be added. :param message_id: The Message-ID header contents to search for. :returns: The message, or None if no matching message was found. """ return self.db.find(Email.message_id, And( Email.list_name == unicode(list_name), Email.message_id == unicode(message_id) )).count() def get_list_names(self): """Return the names of the archived lists. :returns: A list containing the names of the archived mailing-lists. """ return list(self.db.find(List.name).order_by(List.name)) def get_messages(self, list_name, start, end): """ Return all emails between two given dates. :param list_name: The name of the mailing list in which these emails should be searched. :param start: A datetime object representing the starting date of the interval to query. :param end: A datetime object representing the ending date of the interval to query. :returns: The list of messages. """ emails = self.db.find(Email, And( Email.list_name == unicode(list_name), Email.date >= start, Email.date < end, )).order_by(Desc(Email.date)) return list(emails) def get_thread(self, list_name, thread_id): """ Return the specified thread. :param list_name: The name of the mailing list in which this email should be searched. :param thread_id: The thread_id as used in the web-pages. Used here to uniquely identify the thread in the database. :returns: The thread object. """ return self.db.find(Thread, And( Thread.list_name == unicode(list_name), Thread.thread_id == unicode(thread_id) )).one() def get_threads(self, list_name, start, end): """ Return all the threads active between two given dates. :param list_name: The name of the mailing list in which this email should be searched. :param start: A datetime object representing the starting date of the interval to query. :param end: A datetime object representing the ending date of the interval to query. :returns: The list of thread-starting messages. """ threads = self.db.find(Thread, And( Thread.list_name == unicode(list_name), Thread.date_active >= start, Thread.date_active < end, )).order_by(Desc(Thread.date_active)) return list(threads) def get_start_date(self, list_name): """ Get the date of the first archived email in a list. :param list_name: The fully qualified list name to search :returns: The datetime of the first message, or None if no message have been archived yet. """ date = self.db.find(Email.date, Email.list_name == unicode(list_name) ).order_by(Email.date)[:1] if date: return date.one() else: return None def get_thread_neighbors(self, list_name, thread_id): """ Return the previous and the next threads of the specified thread, in date order. The returned objects are the emails starting the threads. :param list_name: The name of the mailing list to query. :param thread_id: The unique identifier of the thread as specified in the database. :returns: A couple formed of the older thread and the newer thread, in this order. :rtype: tuple """ current_email = self.get_message_by_hash_from_list(list_name, thread_id) next_email = self.db.find(Email, And( Email.list_name == unicode(list_name), Email.in_reply_to == None, Email.date > current_email.date, )).order_by(Email.date) try: next_email = next_email[0] except IndexError: next_email = None prev_email = self.db.find(Email, And( Email.list_name == unicode(list_name), Email.in_reply_to == None, Email.date < current_email.date, )).order_by(Desc(Email.date)) try: prev_email = prev_email[0] except IndexError: prev_email = None return (prev_email, next_email) def get_list(self, list_name): """ Return the list object for a mailing list name. :arg list_name, name of the mailing list to retrieve. """ return self.db.find(List, List.name == unicode(list_name)).one() def get_message_by_number(self, list_name, num): """ Return the n-th email for the specified list. :param list_name: The name of the mailing list in which this email should be searched. :param num: The email number in order received. :returns: The email message. """ result = self.db.find(Email, Email.list_name == unicode(list_name) ).order_by(Email.archived_date )[num:num+1].one() return result # Attachments def add_attachment(self, mlist, msg_id, counter, name, content_type, encoding, content): existing = self.db.find(Attachment.message_id, And( Attachment.list_name == unicode(mlist), Attachment.message_id == unicode(msg_id), Attachment.counter == counter, )).count() if existing: return attachment = Attachment() attachment.list_name = unicode(mlist) attachment.message_id = unicode(msg_id) attachment.counter = counter attachment.name = unicode(name) attachment.content_type = unicode(content_type) attachment.encoding = unicode(encoding) if encoding is not None else None attachment.content = content attachment.size = len(content) self.db.add(attachment) self.flush() def get_attachments(self, list_name, message_id): """Return the message's attachments :param list_name: The fully qualified list name to which the message should be added. :param message_id: The Message-ID header contents to search for. :returns: A list of attachments """ att = self.db.find(Attachment, And( Attachment.list_name == unicode(list_name), Attachment.message_id == unicode(message_id) )).order_by(Attachment.counter) return list(att) def get_attachment_by_counter(self, list_name, message_id, counter): """Return the message's attachment at 'counter' position. :param list_name: The fully qualified list name to which the message should be added. :param message_id: The Message-ID header contents to search for. :param counter: The position in the MIME-multipart email. :returns: The corresponding attachment """ return self.db.find(Attachment, And( Attachment.list_name == unicode(list_name), Attachment.message_id == unicode(message_id), Attachment.counter == counter )).one() # Generic database operations def flush(self): """Flush pending database operations.""" self.db.flush() def commit(self): """Commit transaction to the database.""" self.db.commit() def close(self): """Close the connection.""" self.db.close() def rollback(self): self.db.rollback()
gpl-3.0
-7,081,884,858,392,199,000
38.082534
81
0.59169
false
overridelogic/bruces
src/bruces/ui/console.py
1
3385
from __future__ import print_function import os import sys import math from collections import OrderedDict class Console(object): """ Basic console outputter. """ def __init__(self, stream=sys.stdout, error_stream=sys.stderr): """ Initialize the console. stream -- the stream to output to (defaults to stdout). error_stream -- the stream to output errors to (defaults to stderr). """ self.stream = stream self.error_stream = error_stream def _print(self, *args, **kwargs): """ Internal function used to print stuff. It directly passes it to `print_function`. It is meant to be overridable for testing and such. """ print(file=self.stream, *args, **kwargs) def _print_error(self, *args, **kwargs): """ Internal function used to print errors. It directly passes it to `print_function`. It is meant to be overridable for testing and such. """ print(file=self.error_stream, *args, **kwargs) def display(self, data): """ Display data to the user. data -- the data to display. """ if data is not None: self._print(data) def display_error(self, data): """ Display error to the user. data -- the data to display. """ if data is not None: self._print_error(data) class PrettyConsole(Console): """ Console user interface class best-fitted for structured data. """ def _display_tree(self, data): pass def _display_table(self, data): """ Display a dictionary in table form. data -- the data to display. """ cols = list(data[0]) collen = {} for r in data: for c in r: if c not in collen: collen[c] = len(c) try: val = r[c] except TypeError: val = getattr(r, c) if len(str(val)) > collen[c]: collen[c] = len(str(val)) for c in cols: self._print(c, " " * (collen[c]-len(c)), end="") self._print() for r in data: for c in r: try: val = r[c] except TypeError: val = getattr(r, c) self._print(str(val), " " * (collen[c]-len(str(val))), end="") self._print() def _display_list(self, data): """ Display a list. data -- the data to display. """ for i in data: self.display(i) def display(self, data, prefix=""): """ Override of `Console.display()`. """ if isinstance(data, list): try: if hasattr(data[0], '__iter__') or isinstance(data[0], dict): self._display_table(data) else: self._display_list(data) except IndexError: self._display_list(data) elif isinstance(data, dict): self._display_tree(data) elif data is None: pass else: self._print(prefix, end="") self._print(data)
mit
-6,089,991,959,096,628,000
24.839695
92
0.483604
false
thuswa/subdms
subdms/propseturl.py
1
1720
#!/usr/bin/env python # -*- coding: utf-8 -*- # $Id$ # Last modified Wed Jul 7 20:51:13 2010 on stalker # update count: 102 # # subdms - A document management system based on subversion. # Copyright (C) 2009 Albert Thuswaldner # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. from svn import fs, repos, core # from . import lowlevel # Python 3.X import lowlevel conf = lowlevel.config() link = lowlevel.linkname() def propset(docnamelist, propname, propvalue): """ Own-rolled propset function that operates directly on the repo However it requires direct filesystem access to the repo. """ # Get repository object repository = repos.open(conf.repopath) # Get repo filesystem pointer fs_ptr = repos.fs(repository) # Get youngest revision youngest_revision_number = fs.youngest_rev(fs_ptr) # begin transaction txn = fs.begin_txn(fs_ptr, youngest_revision_number) txn_root = fs.txn_root(txn) # change property on node fs.change_node_prop(txn_root, link.const_docinrepopath(docnamelist), \ propname, propvalue) fs.commit_txn(txn)
gpl-3.0
4,931,710,476,619,434,000
30.272727
74
0.710465
false
zhuhang1/vccrResult
monitor.py
1
1392
from time import sleep, time from subprocess import * import re default_dir = '.' def monitor_qlen(iface, interval_sec = 0.01, fname='%s/qlen.txt' % default_dir): #pat_queued = re.compile(r'backlog\s[^\s]+\s([\d]+)p') pat_dropped = re.compile(r'dropped\s([\d]+),') pat_queued = re.compile(r'backlog\s([\d]+)b') cmd = "tc -s qdisc show dev %s" % (iface) ret = [] fname2='%s/dropped.txt' % default_dir open(fname, 'w').write('') open(fname2, 'w').write('') while 1: p = Popen(cmd, shell=True, stdout=PIPE) output = p.stdout.read() # Not quite right, but will do for now matches = pat_queued.findall(output) t = "%f" % time() if matches and len(matches) > 1: ret.append(matches[1]) open(fname, 'a').write(t + ',' + matches[1] + '\n') matches = pat_dropped.findall(output) if matches and len(matches) > 1: open(fname2, 'a').write(t + ',' + matches[1] + '\n') sleep(interval_sec) #open('qlen.txt', 'w').write('\n'.join(ret)) return def monitor_devs_ng(fname="%s/txrate.txt" % default_dir, interval_sec=0.01): """Uses bwm-ng tool to collect iface tx rate stats. Very reliable.""" cmd = ("sleep 1; bwm-ng -t %s -o csv " "-u bits -T rate -C ',' > %s" % (interval_sec * 1000, fname)) Popen(cmd, shell=True).wait()
mit
5,945,054,590,180,469,000
36.621622
80
0.556034
false
jonas-eberle/pyEOM
pyEOM/datasets/predefined/MODIS/MYD10CM.py
1
2137
__author__ = 'we32zac' from pyEOM.datasets import Dataset as DatasetAbs class Dataset(DatasetAbs): shortname = 'MYD10CM' platform = 'Aqua' collection = '005' rastertype = 'CMG' timeInterval = 'P1M' host = 'n5eil01u.ecs.nsidc.org' dir = '/SAN/MOSA/MYD10CM.005' sources = ['NSIDC'] def getDownloadInfo(self): return dict(shortname=self.shortname, platform=self.platform, collection=self.collection, rastertype=self.rastertype, host=self.host, directory=self.dir, sources=self.sources) def getBands(self): return self.bands def getThematicBands(self): return [self.bands['Snowcover']] def getQualityBands(self): return [] bands = dict(Snowcover={ 'name': 'MOD_CMG_Snow_5km:Snow_Cover_Monthly_CMG', 'nodata': 255, 'scale': 1, 'offset': None, 'imagetype': 'thematicClassification', 'identifier': 'MODIS_MYD10_CM_SnowCover_Series', 'title': 'Monthly Snow Cover from MODIS Aqua', 'abstract': 'Time-series of monthly Aqua MODIS Snow Cover at 0.05 deg spatial resolution. Available classes are: No Snow, Snow (in percent), Cloud, No decision, Water Mask. Original MODIS data retrieved from the National Snow &amp; Ice Data Center (ftp://n4ftl01u.ecs.nasa.gov/SAN/MOSA/).', 'keywords': 'MODIS,Aqua,Siberia,Snow,Snow Cover,Global,Monthly,Series,Classification', 'lineage': 'Original MODIS data retrieved from the National Snow &amp; Ice Data Center (ftp://n4ftl01u.ecs.nasa.gov/SAN/MOSA/) and processed with GDAL 1.9.0.', 'datasetname': 'Snow Cover', 'datatype': 'RASTER', 'resolution': 0.05, 'layername': 'myd10cm_snowcover', 'templates': 'template_header_evi.html', 'wcs_description': 'MODIS Aqua Snow Cover Monthly', 'wms_description': 'MODIS Aqua Snow Cover Monthly', 'colormap': 'snow_colorbar.map', 'resolution_unit': 'deg', 'unit': 'None' } )
mit
7,872,655,397,594,822,000
38.358491
302
0.605054
false
akkana/pytopo
pytopo/__init__.py
1
1157
#!/usr/bin/env python '''pytopo module: display tiled maps from a variety of sources, along with trackpoints, waypoints and other useful information. Copyright 2005-2021 by Akkana Peck. Feel free to use, distribute or modify this program under the terms of the GPL v2 or, at your option, a later GPL version. I'd appreciate hearing about it if you make any changes. ''' __version__ = "1.7" __author__ = "Akkana Peck <[email protected]>" __license__ = "GPL v2+" # Hack to make relative imports work in Python 3 as well as Python 2: import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__))) from .MapCollection import MapCollection from .GenericMapCollection import GenericMapCollection from .TopoMapCollection import TopoMapCollection from .TopoMapCollection import Topo1MapCollection from .TopoMapCollection import Topo2MapCollection from .TiledMapCollection import TiledMapCollection from .OSMMapCollection import OSMMapCollection from .MapWindow import MapWindow from .TrackPoints import TrackPoints from .MapViewer import MapViewer, ArgParseException # import trackstats user_agent = "PyTopo " + __version__
gpl-2.0
-806,987,653,849,583,600
34.060606
76
0.779602
false
nagyistoce/netzob
src/netzob/Export/TextExport.py
1
3142
# -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocols | #+---------------------------------------------------------------------------+ #| Copyright (C) 2011 Georges Bossert and Frédéric Guihéry | #| This program 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. | #| | #| This program 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 this program. If not, see <http://www.gnu.org/licenses/>. | #+---------------------------------------------------------------------------+ #| @url : http://www.netzob.org | #| @contact : [email protected] | #| @sponsors : Amossys, http://www.amossys.fr | #| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/ | #+---------------------------------------------------------------------------+ #+---------------------------------------------- #| Global Imports #+---------------------------------------------- from gettext import gettext as _ import logging #+---------------------------------------------- #| TextExport: #| GUI for exporting results in raw mode #+---------------------------------------------- class TextExport(object): #+---------------------------------------------- #| Constructor: #| @param netzob: the main netzob object #+---------------------------------------------- def __init__(self, netzob): self.netzob = netzob self.log = logging.getLogger('netzob.Export.TextExport.py') def getTextDefinition(self, symbolID): project = self.netzob.getCurrentProject() vocabulary = project.getVocabulary() symbols = vocabulary.getSymbols() resSymbol = None for symbol in symbols: if str(symbol.getID()) == symbolID: resSymbol = symbol break if resSymbol is None: self.log.warning("Impossible to retrieve the symbol having the id {0}".format(str(symbolID))) return None else: return resSymbol.getTextDefinition()
gpl-3.0
300,121,780,484,130,560
49.612903
105
0.416507
false
gixxi/comparareetpendere
setup.py
1
1143
''' :copyright: Copyright 2013 by [email protected], see AUTHORS. :license: BSD, see LICENSE for details. ''' from distutils.core import setup setup(name='ComparareEtPendere', version='0.9', packages=['MultisourceHtmlFormatter'], provides=['MultisourceHtmlFormatter'], description='Multisource Code Formatter outputting HTML. Based on pygments', author='Christian Meichsner', author_email='[email protected]', url='https://github.com/gixxi/comparareetpendere', license="BSD", platforms="Tested with Python 3.1", keywords='sourcecode formatting html output pygments python documentation', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: BSD License', 'Topic :: Software Development :: Documentation' ], )
bsd-2-clause
-4,088,039,210,472,963,000
42.961538
89
0.623797
false
JQIamo/artiq
artiq/compiler/builtins.py
1
7849
""" The :mod:`builtins` module contains the builtin Python and ARTIQ types, such as int or float. """ from collections import OrderedDict from . import types # Types class TNone(types.TMono): def __init__(self): super().__init__("NoneType") class TBool(types.TMono): def __init__(self): super().__init__("bool") @staticmethod def zero(): return False @staticmethod def one(): return True class TInt(types.TMono): def __init__(self, width=None): if width is None: width = types.TVar() super().__init__("int", {"width": width}) @staticmethod def zero(): return 0 @staticmethod def one(): return 1 def TInt32(): return TInt(types.TValue(32)) def TInt64(): return TInt(types.TValue(64)) def _int_printer(typ, printer, depth, max_depth): if types.is_var(typ["width"]): return "numpy.int?" else: return "numpy.int{}".format(types.get_value(typ.find()["width"])) types.TypePrinter.custom_printers["int"] = _int_printer class TFloat(types.TMono): def __init__(self): super().__init__("float") @staticmethod def zero(): return 0.0 @staticmethod def one(): return 1.0 class TStr(types.TMono): def __init__(self): super().__init__("str") class TBytes(types.TMono): def __init__(self): super().__init__("bytes") class TByteArray(types.TMono): def __init__(self): super().__init__("bytearray") class TList(types.TMono): def __init__(self, elt=None): if elt is None: elt = types.TVar() super().__init__("list", {"elt": elt}) class TArray(types.TMono): def __init__(self, elt=None): if elt is None: elt = types.TVar() super().__init__("array", {"elt": elt}) def _array_printer(typ, printer, depth, max_depth): return "numpy.array(elt={})".format(printer.name(typ["elt"], depth, max_depth)) types.TypePrinter.custom_printers["array"] = _array_printer class TRange(types.TMono): def __init__(self, elt=None): if elt is None: elt = types.TVar() super().__init__("range", {"elt": elt}) self.attributes = OrderedDict([ ("start", elt), ("stop", elt), ("step", elt), ]) class TException(types.TMono): # All exceptions share the same internal layout: # * Pointer to the unique global with the name of the exception (str) # (which also serves as the EHABI type_info). # * File, line and column where it was raised (str, int, int). # * Message, which can contain substitutions {0}, {1} and {2} (str). # * Three 64-bit integers, parameterizing the message (numpy.int64). # Keep this in sync with the function ARTIQIRGenerator.alloc_exn. attributes = OrderedDict([ ("__name__", TStr()), ("__file__", TStr()), ("__line__", TInt32()), ("__col__", TInt32()), ("__func__", TStr()), ("__message__", TStr()), ("__param0__", TInt64()), ("__param1__", TInt64()), ("__param2__", TInt64()), ]) def __init__(self, name="Exception", id=0): super().__init__(name) self.id = id def fn_bool(): return types.TConstructor(TBool()) def fn_int(): return types.TConstructor(TInt()) def fn_int32(): return types.TBuiltinFunction("int32") def fn_int64(): return types.TBuiltinFunction("int64") def fn_float(): return types.TConstructor(TFloat()) def fn_str(): return types.TConstructor(TStr()) def fn_bytes(): return types.TConstructor(TBytes()) def fn_bytearray(): return types.TConstructor(TByteArray()) def fn_list(): return types.TConstructor(TList()) def fn_array(): return types.TConstructor(TArray()) def fn_Exception(): return types.TExceptionConstructor(TException("Exception")) def fn_IndexError(): return types.TExceptionConstructor(TException("IndexError")) def fn_ValueError(): return types.TExceptionConstructor(TException("ValueError")) def fn_ZeroDivisionError(): return types.TExceptionConstructor(TException("ZeroDivisionError")) def fn_range(): return types.TBuiltinFunction("range") def fn_len(): return types.TBuiltinFunction("len") def fn_round(): return types.TBuiltinFunction("round") def fn_min(): return types.TBuiltinFunction("min") def fn_max(): return types.TBuiltinFunction("max") def fn_make_array(): return types.TBuiltinFunction("make_array") def fn_print(): return types.TBuiltinFunction("print") def fn_kernel(): return types.TBuiltinFunction("kernel") def obj_parallel(): return types.TBuiltin("parallel") def obj_interleave(): return types.TBuiltin("interleave") def obj_sequential(): return types.TBuiltin("sequential") def fn_watchdog(): return types.TBuiltinFunction("watchdog") def fn_delay(): return types.TBuiltinFunction("delay") def fn_now_mu(): return types.TBuiltinFunction("now_mu") def fn_delay_mu(): return types.TBuiltinFunction("delay_mu") def fn_at_mu(): return types.TBuiltinFunction("at_mu") def fn_rtio_log(): return types.TBuiltinFunction("rtio_log") # Accessors def is_none(typ): return types.is_mono(typ, "NoneType") def is_bool(typ): return types.is_mono(typ, "bool") def is_int(typ, width=None): if width is not None: return types.is_mono(typ, "int", width=width) else: return types.is_mono(typ, "int") def is_int32(typ): return is_int(typ, types.TValue(32)) def is_int64(typ): return is_int(typ, types.TValue(64)) def get_int_width(typ): if is_int(typ): return types.get_value(typ.find()["width"]) def is_float(typ): return types.is_mono(typ, "float") def is_str(typ): return types.is_mono(typ, "str") def is_bytes(typ): return types.is_mono(typ, "bytes") def is_bytearray(typ): return types.is_mono(typ, "bytearray") def is_numeric(typ): typ = typ.find() return isinstance(typ, types.TMono) and \ typ.name in ('int', 'float') def is_list(typ, elt=None): if elt is not None: return types.is_mono(typ, "list", elt=elt) else: return types.is_mono(typ, "list") def is_array(typ, elt=None): if elt is not None: return types.is_mono(typ, "array", elt=elt) else: return types.is_mono(typ, "array") def is_listish(typ, elt=None): if is_list(typ, elt) or is_array(typ, elt): return True elif elt is None: return is_str(typ) or is_bytes(typ) or is_bytearray(typ) else: return False def is_range(typ, elt=None): if elt is not None: return types.is_mono(typ, "range", {"elt": elt}) else: return types.is_mono(typ, "range") def is_exception(typ, name=None): if name is None: return isinstance(typ.find(), TException) else: return isinstance(typ.find(), TException) and \ typ.name == name def is_iterable(typ): return is_listish(typ) or is_range(typ) def get_iterable_elt(typ): if is_str(typ) or is_bytes(typ) or is_bytearray(typ): return TInt(types.TValue(8)) elif is_iterable(typ): return typ.find()["elt"].find() else: assert False def is_collection(typ): typ = typ.find() return isinstance(typ, types.TTuple) or \ types.is_mono(typ, "list") def is_allocated(typ): return not (is_none(typ) or is_bool(typ) or is_int(typ) or is_float(typ) or is_range(typ) or types._is_pointer(typ) or types.is_function(typ) or types.is_c_function(typ) or types.is_rpc(typ) or types.is_method(typ) or types.is_tuple(typ) or types.is_value(typ))
lgpl-3.0
6,893,321,347,055,614,000
23.605016
83
0.60581
false
Laucoonte/cpmx
socketVideoDesk.py
1
1385
import io import socket import struct from PIL import Image import cv2 import numpy # Start a socket listening for connections on 0.0.0.0:8000 (0.0.0.0 means # all interfaces) server_socket = socket.socket() server_socket.bind(('0.0.0.0', 8000)) server_socket.listen(0) # Accept a single connection and make a file-like object out of it connection = server_socket.accept()[0].makefile('rb') try: while True: # Read the length of the image as a 32-bit unsigned int. If the # length is zero, quit the loop image_len = struct.unpack('<L', connection.read(struct.calcsize('<L')))[0] if not image_len: break # Construct a stream to hold the image data and read the image # data from the connection image_stream = io.BytesIO() image_stream.write(connection.read(image_len)) # Rewind the stream, open it as an image with PIL and do some # processing on it image_stream.seek(0) image = Image.open(image_stream) #pil_image = PIL.Image.open('Image.jpg').convert('RGB') open_cv_image = numpy.array(image) cv2.imshow('Video', open_cv_image) cv2.waitKey(1) print type(open_cv_image) print('Image is %dx%d' % image.size) image.verify() print('Image is verified') finally: connection.close() server_socket.close()
mit
4,973,504,160,257,981,000
32.780488
82
0.641877
false
anushbmx/kitsune
kitsune/questions/tests/test_badges.py
1
1183
from datetime import date from django.conf import settings from kitsune.kbadge.tests import BadgeFactory from kitsune.questions.badges import QUESTIONS_BADGES from kitsune.questions.tests import AnswerFactory from kitsune.sumo.tests import TestCase from kitsune.users.tests import UserFactory class TestQuestionsBadges(TestCase): def test_answer_badge(self): """Verify the Support Forum Badge is awarded properly.""" # Create the user and badge. year = date.today().year u = UserFactory() badge_template = QUESTIONS_BADGES['answer-badge'] b = BadgeFactory( slug=badge_template['slug'].format(year=year), title=badge_template['title'].format(year=year), description=badge_template['description'].format(year=year)) # Create one less answer than reqiured to earn badge AnswerFactory.create_batch(settings.BADGE_LIMIT_SUPPORT_FORUM - 1, creator=u) # User should NOT have the badge yet. assert not b.is_awarded_to(u) # Create 1 more answer. AnswerFactory(creator=u) # User should have the badge now. assert b.is_awarded_to(u)
bsd-3-clause
4,984,153,013,888,068,000
32.8
85
0.6847
false
DolotovEvgeniy/ml-lib
3rdparty/cpplint.py
1
241896
#!/usr/bin/env python # # Copyright (c) 2009 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Does google-lint on c++ files. The goal of this script is to identify places in the code that *may* be in non-compliance with google style. It does not attempt to fix up these problems -- the point is to educate. It does also not attempt to find all problems, or to ensure that everything it does find is legitimately a problem. In particular, we can get very confused by /* and // inside strings! We do a small hack, which is to ignore //'s with "'s after them on the same line, but it is far from perfect (in either direction). """ import codecs import copy import getopt import math # for log import os import re import sre_compile import string import sys import unicodedata _USAGE = """ Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...] [--counting=total|toplevel|detailed] [--root=subdir] [--linelength=digits] <file> [file] ... The style guidelines this tries to follow are those in http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml Every problem is given a confidence score from 1-5, with 5 meaning we are certain of the problem, and 1 meaning it could be a legitimate construct. This will miss some errors, and is not a substitute for a code review. To suppress false-positive errors of a certain category, add a 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) suppresses errors of all categories on that line. The files passed in will be linted; at least one file must be provided. Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the extensions with the --extensions flag. Flags: output=vs7 By default, the output is formatted to ease emacs parsing. Visual Studio compatible output (vs7) may also be used. Other formats are unsupported. verbose=# Specify a number 0-5 to restrict errors to certain verbosity levels. filter=-x,+y,... Specify a comma-separated list of category-filters to apply: only error messages whose category names pass the filters will be printed. (Category names are printed with the message and look like "[whitespace/indent]".) Filters are evaluated left to right. "-FOO" and "FOO" means "do not print categories that start with FOO". "+FOO" means "do print categories that start with FOO". Examples: --filter=-whitespace,+whitespace/braces --filter=whitespace,runtime/printf,+runtime/printf_format --filter=-,+build/include_what_you_use To see a list of all the categories used in cpplint, pass no arg: --filter= counting=total|toplevel|detailed The total number of errors found is always printed. If 'toplevel' is provided, then the count of errors in each of the top-level categories like 'build' and 'whitespace' will also be printed. If 'detailed' is provided, then a count is provided for each category like 'build/class'. root=subdir The root directory used for deriving header guard CPP variable. By default, the header guard CPP variable is calculated as the relative path to the directory that contains .git, .hg, or .svn. When this flag is specified, the relative path is calculated from the specified directory. If the specified directory does not exist, this flag is ignored. Examples: Assuming that src/.git exists, the header guard CPP variables for src/chrome/browser/ui/browser.h are: No flag => CHROME_BROWSER_UI_BROWSER_H_ --root=chrome => BROWSER_UI_BROWSER_H_ --root=chrome/browser => UI_BROWSER_H_ linelength=digits This is the allowed line length for the project. The default value is 80 characters. Examples: --linelength=120 extensions=extension,extension,... The allowed file extensions that cpplint will check Examples: --extensions=hpp,cpp cpplint.py supports per-directory configurations specified in CPPLINT.cfg files. CPPLINT.cfg file can contain a number of key=value pairs. Currently the following options are supported: set noparent filter=+filter1,-filter2,... exclude_files=regex linelength=80 "set noparent" option prevents cpplint from traversing directory tree upwards looking for more .cfg files in parent directories. This option is usually placed in the top-level project directory. The "filter" option is similar in function to --filter flag. It specifies message filters in addition to the |_DEFAULT_FILTERS| and those specified through --filter command-line flag. "exclude_files" allows to specify a regular expression to be matched against a file name. If the expression matches, the file is skipped and not run through liner. "linelength" allows to specify the allowed line length for the project. CPPLINT.cfg has an effect on files in the same directory and all sub-directories, unless overridden by a nested configuration file. Example file: filter=-build/include_order,+build/include_alpha exclude_files=.*\.cc The above example disables build/include_order warning and enables build/include_alpha as well as excludes all .cc from being processed by linter, in the current directory (where the .cfg file is located) and all sub-directories. """ # We categorize each error message we print. Here are the categories. # We want an explicit list so we can list them all in cpplint --filter=. # If you add a new error message with a new category, add it to the list # here! cpplint_unittest.py should tell you if you forget to do this. _ERROR_CATEGORIES = [ 'build/class', 'build/c++11', 'build/deprecated', 'build/endif_comment', 'build/explicit_make_pair', 'build/forward_decl', 'build/header_guard', 'build/include', 'build/include_alpha', 'build/include_order', 'build/include_what_you_use', 'build/namespaces', 'build/printf_format', 'build/storage_class', 'legal/copyright', 'readability/alt_tokens', 'readability/braces', 'readability/casting', 'readability/check', 'readability/constructors', 'readability/fn_size', 'readability/function', 'readability/inheritance', 'readability/multiline_comment', 'readability/multiline_string', 'readability/namespace', 'readability/nolint', 'readability/nul', 'readability/strings', 'readability/todo', 'readability/utf8', 'runtime/arrays', 'runtime/casting', 'runtime/explicit', 'runtime/int', 'runtime/init', 'runtime/invalid_increment', 'runtime/member_string_references', 'runtime/memset', 'runtime/indentation_namespace', 'runtime/operator', 'runtime/printf', 'runtime/printf_format', 'runtime/references', 'runtime/string', 'runtime/threadsafe_fn', 'runtime/vlog', 'whitespace/blank_line', 'whitespace/braces', 'whitespace/comma', 'whitespace/comments', 'whitespace/empty_conditional_body', 'whitespace/empty_loop_body', 'whitespace/end_of_line', 'whitespace/ending_newline', 'whitespace/forcolon', 'whitespace/indent', 'whitespace/line_length', 'whitespace/newline', 'whitespace/operators', 'whitespace/parens', 'whitespace/semicolon', 'whitespace/tab', 'whitespace/todo', ] # These error categories are no longer enforced by cpplint, but for backwards- # compatibility they may still appear in NOLINT comments. _LEGACY_ERROR_CATEGORIES = [ 'readability/streams', ] # The default state of the category filter. This is overridden by the --filter= # flag. By default all errors are on, so only add here categories that should be # off by default (i.e., categories that must be enabled by the --filter= flags). # All entries here should start with a '-' or '+', as in the --filter= flag. _DEFAULT_FILTERS = ['-build/include_alpha'] # We used to check for high-bit characters, but after much discussion we # decided those were OK, as long as they were in UTF-8 and didn't represent # hard-coded international strings, which belong in a separate i18n file. # C++ headers _CPP_HEADERS = frozenset([ # Legacy 'algobase.h', 'algo.h', 'alloc.h', 'builtinbuf.h', 'bvector.h', 'complex.h', 'defalloc.h', 'deque.h', 'editbuf.h', 'fstream.h', 'function.h', 'hash_map', 'hash_map.h', 'hash_set', 'hash_set.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip.h', 'iostream.h', 'istream.h', 'iterator.h', 'list.h', 'map.h', 'multimap.h', 'multiset.h', 'ostream.h', 'pair.h', 'parsestream.h', 'pfstream.h', 'procbuf.h', 'pthread_alloc', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h', 'set.h', 'slist', 'slist.h', 'stack.h', 'stdiostream.h', 'stl_alloc.h', 'stl_relops.h', 'streambuf.h', 'stream.h', 'strfile.h', 'strstream.h', 'tempbuf.h', 'tree.h', 'type_traits.h', 'vector.h', # 17.6.1.2 C++ library headers 'algorithm', 'array', 'atomic', 'bitset', 'chrono', 'codecvt', 'complex', 'condition_variable', 'deque', 'exception', 'forward_list', 'fstream', 'functional', 'future', 'initializer_list', 'iomanip', 'ios', 'iosfwd', 'iostream', 'istream', 'iterator', 'limits', 'list', 'locale', 'map', 'memory', 'mutex', 'new', 'numeric', 'ostream', 'queue', 'random', 'ratio', 'regex', 'set', 'sstream', 'stack', 'stdexcept', 'streambuf', 'string', 'strstream', 'system_error', 'thread', 'tuple', 'typeindex', 'typeinfo', 'type_traits', 'unordered_map', 'unordered_set', 'utility', 'valarray', 'vector', # 17.6.1.2 C++ headers for C library facilities 'cassert', 'ccomplex', 'cctype', 'cerrno', 'cfenv', 'cfloat', 'cinttypes', 'ciso646', 'climits', 'clocale', 'cmath', 'csetjmp', 'csignal', 'cstdalign', 'cstdarg', 'cstdbool', 'cstddef', 'cstdint', 'cstdio', 'cstdlib', 'cstring', 'ctgmath', 'ctime', 'cuchar', 'cwchar', 'cwctype', ]) # These headers are excluded from [build/include] and [build/include_order] # checks: # - Anything not following google file name conventions (containing an # uppercase character, such as Python.h or nsStringAPI.h, for example). # - Lua headers. _THIRD_PARTY_HEADERS_PATTERN = re.compile( r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$') # Assertion macros. These are defined in base/logging.h and # testing/base/gunit.h. Note that the _M versions need to come first # for substring matching to work. _CHECK_MACROS = [ 'DCHECK', 'CHECK', 'EXPECT_TRUE_M', 'EXPECT_TRUE', 'ASSERT_TRUE_M', 'ASSERT_TRUE', 'EXPECT_FALSE_M', 'EXPECT_FALSE', 'ASSERT_FALSE_M', 'ASSERT_FALSE', ] # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS]) for op, replacement in [('==', 'EQ'), ('!=', 'NE'), ('>=', 'GE'), ('>', 'GT'), ('<=', 'LE'), ('<', 'LT')]: _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), ('>=', 'LT'), ('>', 'LE'), ('<=', 'GT'), ('<', 'GE')]: _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement # Alternative tokens and their replacements. For full list, see section 2.5 # Alternative tokens [lex.digraph] in the C++ standard. # # Digraphs (such as '%:') are not included here since it's a mess to # match those on a word boundary. _ALT_TOKEN_REPLACEMENT = { 'and': '&&', 'bitor': '|', 'or': '||', 'xor': '^', 'compl': '~', 'bitand': '&', 'and_eq': '&=', 'or_eq': '|=', 'xor_eq': '^=', 'not': '!', 'not_eq': '!=' } # Compile regular expression that matches all the above keywords. The "[ =()]" # bit is meant to avoid matching these keywords outside of boolean expressions. # # False positives include C-style multi-line comments and multi-line strings # but those have always been troublesome for cpplint. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') # These constants define types of headers for use with # _IncludeState.CheckNextIncludeOrder(). _C_SYS_HEADER = 1 _CPP_SYS_HEADER = 2 _LIKELY_MY_HEADER = 3 _POSSIBLE_MY_HEADER = 4 _OTHER_HEADER = 5 # These constants define the current inline assembly state _NO_ASM = 0 # Outside of inline assembly block _INSIDE_ASM = 1 # Inside inline assembly block _END_ASM = 2 # Last line of inline assembly block _BLOCK_ASM = 3 # The whole block is an inline assembly block # Match start of assembly blocks _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' r'(?:\s+(volatile|__volatile__))?' r'\s*[{(]') _regexp_compile_cache = {} # {str, set(int)}: a map from error categories to sets of linenumbers # on which those errors are expected and should be suppressed. _error_suppressions = {} # The root directory used for deriving header guard CPP variable. # This is set by --root flag. _root = None # The allowed line length of files. # This is set by --linelength flag. _line_length = 80 # The allowed extensions for file names # This is set by --extensions flag. _valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh', 'cxx']) def ParseNolintSuppressions(filename, raw_line, linenum, error): """Updates the global list of error-suppressions. Parses any NOLINT comments on the current line, updating the global error_suppressions store. Reports an error if the NOLINT comment was malformed. Args: filename: str, the name of the input file. raw_line: str, the line of input text, with comments. linenum: int, the number of the current line. error: function, an error handler. """ matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line) if matched: if matched.group(1): suppressed_line = linenum + 1 else: suppressed_line = linenum category = matched.group(2) if category in (None, '(*)'): # => "suppress all" _error_suppressions.setdefault(None, set()).add(suppressed_line) else: if category.startswith('(') and category.endswith(')'): category = category[1:-1] if category in _ERROR_CATEGORIES: _error_suppressions.setdefault(category, set()).add(suppressed_line) elif category not in _LEGACY_ERROR_CATEGORIES: error(filename, linenum, 'readability/nolint', 5, 'Unknown NOLINT error category: %s' % category) def ResetNolintSuppressions(): """Resets the set of NOLINT suppressions to empty.""" _error_suppressions.clear() def IsErrorSuppressedByNolint(category, linenum): """Returns true if the specified error category is suppressed on this line. Consults the global error_suppressions map populated by ParseNolintSuppressions/ResetNolintSuppressions. Args: category: str, the category of the error. linenum: int, the current line number. Returns: bool, True iff the error should be suppressed due to a NOLINT comment. """ return (linenum in _error_suppressions.get(category, set()) or linenum in _error_suppressions.get(None, set())) def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].match(s) def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s) def Search(pattern, s): """Searches the string for the pattern, caching the compiled regexp.""" if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s) class _IncludeState(object): """Tracks line numbers for includes, and the order in which includes appear. include_list contains list of lists of (header, line number) pairs. It's a lists of lists rather than just one flat list to make it easier to update across preprocessor boundaries. Call CheckNextIncludeOrder() once for each header in the file, passing in the type constants defined above. Calls in an illegal order will raise an _IncludeError with an appropriate error message. """ # self._section will move monotonically through this set. If it ever # needs to move backwards, CheckNextIncludeOrder will raise an error. _INITIAL_SECTION = 0 _MY_H_SECTION = 1 _C_SECTION = 2 _CPP_SECTION = 3 _OTHER_H_SECTION = 4 _TYPE_NAMES = { _C_SYS_HEADER: 'C system header', _CPP_SYS_HEADER: 'C++ system header', _LIKELY_MY_HEADER: 'header this file implements', _POSSIBLE_MY_HEADER: 'header this file may implement', _OTHER_HEADER: 'other header', } _SECTION_NAMES = { _INITIAL_SECTION: "... nothing. (This can't be an error.)", _MY_H_SECTION: 'a header this file implements', _C_SECTION: 'C system header', _CPP_SECTION: 'C++ system header', _OTHER_H_SECTION: 'other header', } def __init__(self): self.include_list = [[]] self.ResetSection('') def FindHeader(self, header): """Check if a header has already been included. Args: header: header to check. Returns: Line number of previous occurrence, or -1 if the header has not been seen before. """ for section_list in self.include_list: for f in section_list: if f[0] == header: return f[1] return -1 def ResetSection(self, directive): """Reset section checking for preprocessor directive. Args: directive: preprocessor directive (e.g. "if", "else"). """ # The name of the current section. self._section = self._INITIAL_SECTION # The path of last found header. self._last_header = '' # Update list of includes. Note that we never pop from the # include list. if directive in ('if', 'ifdef', 'ifndef'): self.include_list.append([]) elif directive in ('else', 'elif'): self.include_list[-1] = [] def SetLastHeader(self, header_path): self._last_header = header_path def CanonicalizeAlphabeticalOrder(self, header_path): """Returns a path canonicalized for alphabetical comparison. - replaces "-" with "_" so they both cmp the same. - removes '-inl' since we don't require them to be after the main header. - lowercase everything, just in case. Args: header_path: Path to be canonicalized. Returns: Canonicalized path. """ return header_path.replace('-inl.h', '.h').replace('-', '_').lower() def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): """Check if a header is in alphabetical order with the previous header. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. header_path: Canonicalized header to be checked. Returns: Returns true if the header is in alphabetical order. """ # If previous section is different from current section, _last_header will # be reset to empty string, so it's always less than current header. # # If previous line was a blank line, assume that the headers are # intentionally sorted the way they are. if (self._last_header > header_path and Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): return False return True def CheckNextIncludeOrder(self, header_type): """Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The empty string if the header is in the right order, or an error message describing what's wrong. """ error_message = ('Found %s after %s' % (self._TYPE_NAMES[header_type], self._SECTION_NAMES[self._section])) last_section = self._section if header_type == _C_SYS_HEADER: if self._section <= self._C_SECTION: self._section = self._C_SECTION else: self._last_header = '' return error_message elif header_type == _CPP_SYS_HEADER: if self._section <= self._CPP_SECTION: self._section = self._CPP_SECTION else: self._last_header = '' return error_message elif header_type == _LIKELY_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: self._section = self._OTHER_H_SECTION elif header_type == _POSSIBLE_MY_HEADER: if self._section <= self._MY_H_SECTION: self._section = self._MY_H_SECTION else: # This will always be the fallback because we're not sure # enough that the header is associated with this file. self._section = self._OTHER_H_SECTION else: assert header_type == _OTHER_HEADER self._section = self._OTHER_H_SECTION if last_section != self._section: self._last_header = '' return '' class _CppLintState(object): """Maintains module-wide state..""" def __init__(self): self.verbose_level = 1 # global setting. self.error_count = 0 # global count of reported errors # filters to apply when emitting error messages self.filters = _DEFAULT_FILTERS[:] # backup of filter list. Used to restore the state after each file. self._filters_backup = self.filters[:] self.counting = 'total' # In what way are we counting errors? self.errors_by_category = {} # string to int dict storing error counts # output format: # "emacs" - format that emacs can parse (default) # "vs7" - format that Microsoft Visual Studio 7 can parse self.output_format = 'emacs' def SetOutputFormat(self, output_format): """Sets the output format for errors.""" self.output_format = output_format def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level def SetCountingStyle(self, counting_style): """Sets the module's counting options.""" self.counting = counting_style def SetFilters(self, filters): """Sets the error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "+whitespace/indent"). Each filter should start with + or -; else we die. Raises: ValueError: The comma-separated filters did not all start with '+' or '-'. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" """ # Default filters always have less priority than the flag ones. self.filters = _DEFAULT_FILTERS[:] self.AddFilters(filters) def AddFilters(self, filters): """ Adds more filters to the existing list of error-message filters. """ for filt in filters.split(','): clean_filt = filt.strip() if clean_filt: self.filters.append(clean_filt) for filt in self.filters: if not (filt.startswith('+') or filt.startswith('-')): raise ValueError('Every filter in --filters must start with + or -' ' (%s does not)' % filt) def BackupFilters(self): """ Saves the current filter list to backup storage.""" self._filters_backup = self.filters[:] def RestoreFilters(self): """ Restores filters previously backed up.""" self.filters = self._filters_backup[:] def ResetErrorCounts(self): """Sets the module's error statistic back to zero.""" self.error_count = 0 self.errors_by_category = {} def IncrementErrorCount(self, category): """Bumps the module's error statistic.""" self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.errors_by_category[category] += 1 def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" for category, count in self.errors_by_category.iteritems(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stderr.write('Total errors found: %d\n' % self.error_count) _cpplint_state = _CppLintState() def _OutputFormat(): """Gets the module's output format.""" return _cpplint_state.output_format def _SetOutputFormat(output_format): """Sets the module's output format.""" _cpplint_state.SetOutputFormat(output_format) def _VerboseLevel(): """Returns the module's verbosity setting.""" return _cpplint_state.verbose_level def _SetVerboseLevel(level): """Sets the module's verbosity, and returns the previous setting.""" return _cpplint_state.SetVerboseLevel(level) def _SetCountingStyle(level): """Sets the module's counting options.""" _cpplint_state.SetCountingStyle(level) def _Filters(): """Returns the module's list of output filters, as a list.""" return _cpplint_state.filters def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters) def _AddFilters(filters): """Adds more filter overrides. Unlike _SetFilters, this function does not reset the current list of filters available. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.AddFilters(filters) def _BackupFilters(): """ Saves the current filter list to backup storage.""" _cpplint_state.BackupFilters() def _RestoreFilters(): """ Restores filters previously backed up.""" _cpplint_state.RestoreFilters() class _FunctionState(object): """Tracks current function name and the number of lines in its body.""" _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. def __init__(self): self.in_a_function = False self.lines_in_function = 0 self.current_function = '' def Begin(self, function_name): """Start analyzing function body. Args: function_name: The name of the function being tracked. """ self.in_a_function = True self.lines_in_function = 0 self.current_function = function_name def Count(self): """Count line in current function body.""" if self.in_a_function: self.lines_in_function += 1 def Check(self, error, filename, linenum): """Report if too many lines in function body. Args: error: The function to call with any errors found. filename: The name of the current file. linenum: The number of the line to check. """ if Match(r'T(EST|est)', self.current_function): base_trigger = self._TEST_TRIGGER else: base_trigger = self._NORMAL_TRIGGER trigger = base_trigger * 2**_VerboseLevel() if self.lines_in_function > trigger: error_level = int(math.log(self.lines_in_function / base_trigger, 2)) # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... if error_level > 5: error_level = 5 error(filename, linenum, 'readability/fn_size', error_level, 'Small and focused functions are preferred:' ' %s has %d non-comment lines' ' (error triggered by exceeding %d lines).' % ( self.current_function, self.lines_in_function, trigger)) def End(self): """Stop analyzing function body.""" self.in_a_function = False class _IncludeError(Exception): """Indicates a problem with the include order in a file.""" pass class FileInfo(object): """Provides utility functions for filenames. FileInfo provides easy access to the components of a file's path relative to the project root. """ def __init__(self, filename): self._filename = filename def FullName(self): """Make Windows paths like Unix.""" return os.path.abspath(self._filename).replace('\\', '/') def RepositoryName(self): """FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = os.path.dirname(fullname) while (root_dir != os.path.dirname(root_dir) and not os.path.exists(os.path.join(root_dir, ".git")) and not os.path.exists(os.path.join(root_dir, ".hg")) and not os.path.exists(os.path.join(root_dir, ".svn"))): root_dir = os.path.dirname(root_dir) if (os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname def Split(self): """Splits the file into the directory, basename, and extension. For 'chrome/browser/browser.cc', Split() would return ('chrome/browser', 'browser', '.cc') Returns: A tuple of (directory, basename, extension). """ googlename = self.RepositoryName() project, rest = os.path.split(googlename) return (project,) + os.path.splitext(rest) def BaseName(self): """File base name - text after the final slash, before the final period.""" return self.Split()[1] def Extension(self): """File extension - text following the final period.""" return self.Split()[2] def NoExtension(self): """File has no source file extension.""" return '/'.join(self.Split()[0:2]) def IsSource(self): """File has a source file extension.""" return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') def _ShouldPrintError(category, confidence, linenum): """If confidence >= verbose, category passes filter and is not suppressed.""" # There are three ways we might decide not to print an error message: # a "NOLINT(category)" comment appears in the source, # the verbosity level isn't high enough, or the filters filter it out. if IsErrorSuppressedByNolint(category, linenum): return False if confidence < _cpplint_state.verbose_level: return False is_filtered = False for one_filter in _Filters(): if one_filter.startswith('-'): if category.startswith(one_filter[1:]): is_filtered = True elif one_filter.startswith('+'): if category.startswith(one_filter[1:]): is_filtered = False else: assert False # should have been checked for in SetFilter. if is_filtered: return False return True def Error(filename, linenum, category, confidence, message): """Logs the fact we've found a lint error. We log where the error was found, and also our confidence in the error, that is, how certain we are this is a legitimate style regression, and not a misidentification or a use that's sometimes justified. False positives can be suppressed by the use of "cpplint(category)" comments on the offending line. These are parsed into _error_suppressions. Args: filename: The name of the file containing the error. linenum: The number of the line containing the error. category: A string used to describe the "category" this bug falls under: "whitespace", say, or "runtime". Categories may have a hierarchy separated by slashes: "whitespace/indent". confidence: A number from 1-5 representing a confidence score for the error, with 5 meaning that we are certain of the problem, and 1 meaning that it could be a legitimate construct. message: The error message. """ if _ShouldPrintError(category, confidence, linenum): _cpplint_state.IncrementErrorCount(category) if _cpplint_state.output_format == 'vs7': sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) elif _cpplint_state.output_format == 'eclipse': sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) else: sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( filename, linenum, message, category, confidence)) # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') # Match a single C style comment on the same line. _RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/' # Matches multi-line C style comments. # This RE is a little bit more complicated than one might expect, because we # have to take care of space removals tools so we can handle comments inside # statements better. # The current rule is: We only clear spaces from both sides when we're at the # end of the line. Otherwise, we try to remove spaces from the right side, # if this doesn't work we try on left side but only if there's a non-character # on the right. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' + _RE_PATTERN_C_COMMENTS + r'\s+|' + r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' + _RE_PATTERN_C_COMMENTS + r')') def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 def CleanseRawStrings(raw_lines): """Removes C++11 raw strings from lines. Before: static const char kData[] = R"( multi-line string )"; After: static const char kData[] = "" (replaced by blank line) ""; Args: raw_lines: list of raw lines. Returns: list of lines with C++11 raw strings replaced by empty strings. """ delimiter = None lines_without_raw_strings = [] for line in raw_lines: if delimiter: # Inside a raw string, look for the end end = line.find(delimiter) if end >= 0: # Found the end of the string, match leading space for this # line and resume copying the original lines, and also insert # a "" on the last line. leading_space = Match(r'^(\s*)\S', line) line = leading_space.group(1) + '""' + line[end + len(delimiter):] delimiter = None else: # Haven't found the end yet, append a blank line. line = '""' # Look for beginning of a raw string, and replace them with # empty strings. This is done in a loop to handle multiple raw # strings on the same line. while delimiter is None: # Look for beginning of a raw string. # See 2.14.15 [lex.string] for syntax. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) if matched: delimiter = ')' + matched.group(2) + '"' end = matched.group(3).find(delimiter) if end >= 0: # Raw string ended on same line line = (matched.group(1) + '""' + matched.group(3)[end + len(delimiter):]) delimiter = None else: # Start of a multi-line raw string line = matched.group(1) + '""' else: break lines_without_raw_strings.append(line) # TODO(unknown): if delimiter is not None here, we might want to # emit a warning for unterminated string. return lines_without_raw_strings def FindNextMultiLineCommentStart(lines, lineix): """Find the beginning marker for a multiline comment.""" while lineix < len(lines): if lines[lineix].strip().startswith('/*'): # Only return this marker if the comment goes beyond this line if lines[lineix].strip().find('*/', 2) < 0: return lineix lineix += 1 return len(lines) def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines) def RemoveMultiLineCommentsFromRange(lines, begin, end): """Clears a range of lines for multi-line comments.""" # Having // dummy comments makes the lines non-empty, so we will not get # unnecessary blank line warnings later in the code. for i in range(begin, end): lines[i] = '/**/' def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1 def CleanseComments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ commentpos = line.find('//') if commentpos != -1 and not IsCppString(line[:commentpos]): line = line[:commentpos].rstrip() # get rid of /* ... */ return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) class CleansedLines(object): """Holds 4 copies of all lines with different preprocessing applied to them. 1) elided member contains lines without strings and comments. 2) lines member contains lines without comments. 3) raw_lines member contains all the lines without processing. 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw strings removed. All these members are of <type 'list'>, and of the same length. """ def __init__(self, lines): self.elided = [] self.lines = [] self.raw_lines = lines self.num_lines = len(lines) self.lines_without_raw_strings = CleanseRawStrings(lines) for linenum in range(len(self.lines_without_raw_strings)): self.lines.append(CleanseComments( self.lines_without_raw_strings[linenum])) elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) self.elided.append(CleanseComments(elided)) def NumLines(self): """Returns the number of lines represented.""" return self.num_lines @staticmethod def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if _RE_PATTERN_INCLUDE.match(elided): return elided # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) # Replace quoted strings and digit separators. Both single quotes # and double quotes are processed in the same loop, otherwise # nested quotes wouldn't work. collapsed = '' while True: # Find the first quote character match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) if not match: collapsed += elided break head, quote, tail = match.groups() if quote == '"': # Collapse double quoted strings second_quote = tail.find('"') if second_quote >= 0: collapsed += head + '""' elided = tail[second_quote + 1:] else: # Unmatched double quote, don't bother processing the rest # of the line since this is probably a multiline string. collapsed += elided break else: # Found single quote, check nearby text to eliminate digit separators. # # There is no special handling for floating point here, because # the integer/fractional/exponent parts would all be parsed # correctly as long as there are digits on both sides of the # separator. So we are fine as long as we don't see something # like "0.'3" (gcc 4.9.0 will not allow this literal). if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) collapsed += head + match_literal.group(1).replace("'", '') elided = match_literal.group(2) else: second_quote = tail.find('\'') if second_quote >= 0: collapsed += head + "''" elided = tail[second_quote + 1:] else: # Unmatched single quote collapsed += elided break return collapsed def FindEndOfExpressionInLine(line, startpos, stack): """Find the position just after the end of current parenthesized expression. Args: line: a CleansedLines line. startpos: start searching at this position. stack: nesting stack at startpos. Returns: On finding matching end: (index just after matching end, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at end of this line) """ for i in xrange(startpos, len(line)): char = line[i] if char in '([{': # Found start of parenthesized expression, push to expression stack stack.append(char) elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator if stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) elif i > 0 and Search(r'\boperator\s*$', line[0:i]): # operator<, don't add to stack continue else: # Tentative start of template argument list stack.append('<') elif char in ')]}': # Found end of parenthesized expression. # # If we are currently expecting a matching '>', the pending '<' # must have been an operator. Remove them from expression stack. while stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) if ((stack[-1] == '(' and char == ')') or (stack[-1] == '[' and char == ']') or (stack[-1] == '{' and char == '}')): stack.pop() if not stack: return (i + 1, None) else: # Mismatched parentheses return (-1, None) elif char == '>': # Found potential end of template argument list. # Ignore "->" and operator functions if (i > 0 and (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))): continue # Pop the stack if there is a matching '<'. Otherwise, ignore # this '>' since it must be an operator. if stack: if stack[-1] == '<': stack.pop() if not stack: return (i + 1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '>', the matching '<' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '<': stack.pop() if not stack: return (-1, None) # Did not find end of expression or unbalanced parentheses on this line return (-1, stack) def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. TODO(unknown): cpplint spends a fair bit of time matching parentheses. Ideally we would want to index all opening and closing parentheses once and have CloseExpression be just a simple lookup, but due to preprocessor tricks, this is not so easy. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): return (line, clean_lines.NumLines(), -1) # Check first line (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while stack and linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) if end_pos > -1: return (line, linenum, end_pos) # Did not find end of expression before end of file, give up return (line, clean_lines.NumLines(), -1) def FindStartOfExpressionInLine(line, endpos, stack): """Find position at the matching start of current expression. This is almost the reverse of FindEndOfExpressionInLine, but note that the input position and returned position differs by 1. Args: line: a CleansedLines line. endpos: start searching at this position. stack: nesting stack at endpos. Returns: On finding matching start: (index at matching start, None) On finding an unclosed expression: (-1, None) Otherwise: (-1, new stack at beginning of this line) """ i = endpos while i >= 0: char = line[i] if char in ')]}': # Found end of expression, push to expression stack stack.append(char) elif char == '>': # Found potential end of template argument list. # # Ignore it if it's a "->" or ">=" or "operator>" if (i > 0 and (line[i - 1] == '-' or Match(r'\s>=\s', line[i - 1:]) or Search(r'\boperator\s*$', line[0:i]))): i -= 1 else: stack.append('>') elif char == '<': # Found potential start of template argument list if i > 0 and line[i - 1] == '<': # Left shift operator i -= 1 else: # If there is a matching '>', we can pop the expression stack. # Otherwise, ignore this '<' since it must be an operator. if stack and stack[-1] == '>': stack.pop() if not stack: return (i, None) elif char in '([{': # Found start of expression. # # If there are any unmatched '>' on the stack, they must be # operators. Remove those. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) if ((char == '(' and stack[-1] == ')') or (char == '[' and stack[-1] == ']') or (char == '{' and stack[-1] == '}')): stack.pop() if not stack: return (i, None) else: # Mismatched parentheses return (-1, None) elif char == ';': # Found something that look like end of statements. If we are currently # expecting a '<', the matching '>' must have been an operator, since # template argument list should not contain statements. while stack and stack[-1] == '>': stack.pop() if not stack: return (-1, None) i -= 1 return (-1, stack) def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] if line[pos] not in ')}]>': return (line, 0, -1) # Check last line (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while stack and linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) if start_pos > -1: return (line, linenum, start_pos) # Did not find start of expression before beginning of file, give up return (line, 0, -1) def CheckForCopyright(filename, lines, error): """Logs an error if no Copyright message appears at the top of the file.""" # We'll say it should occur by line 10. Don't forget there's a # dummy line at the front. for line in xrange(1, min(len(lines), 11)): if re.search(r'Copyright', lines[line], re.I): break else: # means no copyright line was found error(filename, 0, 'legal/copyright', 5, 'No copyright message found. ' 'You should have a line: "Copyright [year] <Copyright Owner>"') def GetIndentLevel(line): """Return the number of leading spaces in line. Args: line: A string to check. Returns: An integer count of leading spaces, possibly zero. """ indent = Match(r'^( *)\S', line) if indent: return len(indent.group(1)) else: return 0 def GetHeaderGuardCPPVariable(filename): """Returns the CPP variable that should be used as a header guard. Args: filename: The name of a C++ header file. Returns: The CPP variable that should be used as a header guard in the named file. """ # Restores original filename in case that cpplint is invoked from Emacs's # flymake. filename = re.sub(r'_flymake\.h$', '.h', filename) filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) # Replace 'c++' with 'cpp'. filename = filename.replace('C++', 'cpp').replace('c++', 'cpp') fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' def CheckForHeaderGuard(filename, clean_lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found. """ # Don't check for header guards if there are error suppression # comments somewhere in this file. # # Because this is silencing a warning for a nonexistent line, we # only support the very specific NOLINT(build/header_guard) syntax, # and not the general NOLINT or NOLINT(*) syntax. raw_lines = clean_lines.lines_without_raw_strings for i in raw_lines: if Search(r'//\s*NOLINT\(build/header_guard\)', i): return cppvar = GetHeaderGuardCPPVariable(filename) ifndef = '' ifndef_linenum = 0 define = '' endif = '' endif_linenum = 0 for linenum, line in enumerate(raw_lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef or not define or ifndef != define: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) # Check for "//" comments on endif line. ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, error) match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) if match: if match.group(1) == '_': # Issue low severity warning for deprecated double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif // %s"' % cppvar) return # Didn't find the corresponding "//" comment. If this file does not # contain any "//" comments at all, it could be that the compiler # only wants "/**/" comments, look for those instead. no_single_line_comments = True for i in xrange(1, len(raw_lines) - 1): line = raw_lines[i] if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): no_single_line_comments = False break if no_single_line_comments: match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) if match: if match.group(1) == '_': # Low severity warning for double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif /* %s */"' % cppvar) return # Didn't find anything error(filename, endif_linenum, 'build/header_guard', 5, '#endif line should be "#endif // %s"' % cppvar) def CheckHeaderFileIncluded(filename, include_state, error): """Logs an error if a .cc file does not include its header.""" # Do not check test files if filename.endswith('_test.cc') or filename.endswith('_unittest.cc'): return fileinfo = FileInfo(filename) headerfile = filename[0:len(filename) - 2] + 'h' if not os.path.exists(headerfile): return headername = FileInfo(headerfile).RepositoryName() first_include = 0 for section_list in include_state.include_list: for f in section_list: if headername in f[0] or f[0] in headername: return if not first_include: first_include = f[1] error(filename, first_include, 'build/include', 5, '%s should include its header file %s' % (fileinfo.RepositoryName(), headername)) def CheckForBadCharacters(filename, lines, error): """Logs an error for each line containing bad characters. Two kinds of bad characters: 1. Unicode replacement characters: These indicate that either the file contained invalid UTF-8 (likely) or Unicode replacement characters (which it shouldn't). Note that it's possible for this to throw off line numbering if the invalid UTF-8 occurred adjacent to a newline. 2. NUL bytes. These are problematic for some tools. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ for linenum, line in enumerate(lines): if u'\ufffd' in line: error(filename, linenum, 'readability/utf8', 5, 'Line contains invalid UTF-8 (or Unicode replacement character).') if '\0' in line: error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') def CheckForNewlineAtEOF(filename, lines, error): """Logs an error if there is no newline char at the end of the file. Args: filename: The name of the current file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ # The array lines() was created by adding two newlines to the # original file (go figure), then splitting on \n. # To verify that the file ends in \n, we just have to make sure the # last-but-two element of lines() exists and is empty. if len(lines) < 3 or lines[-2]: error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, 'Could not find a newline character at the end of the file.') def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.') # (non-threadsafe name, thread-safe alternative, validation pattern) # # The validation pattern is used to eliminate false positives such as: # _rand(); // false positive due to substring match. # ->rand(); // some member function rand(). # ACMRandom rand(seed); // some variable named rand. # ISAACRandom rand(); // another variable named rand. # # Basically we require the return value of these functions to be used # in some expression context on the same line by matching on some # operator before the function name. This eliminates constructors and # member function calls. _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)' _THREADING_LIST = ( ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'), ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'), ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'), ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'), ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'), ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'), ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'), ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'), ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'), ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'), ('strtok(', 'strtok_r(', _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'), ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'), ) def CheckPosixThreading(filename, clean_lines, linenum, error): """Checks for calls to thread-unsafe functions. Much code has been originally written without consideration of multi-threading. Also, engineers are relying on their old experience; they have learned posix before threading extensions were added. These tests guide the engineers to use thread-safe functions (when using posix directly). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: # Additional pattern matching check to confirm that this is the # function we are looking for if Search(pattern, line): error(filename, linenum, 'runtime/threadsafe_fn', 2, 'Consider using ' + multithread_safe_func + '...) instead of ' + single_thread_func + '...) for improved thread safety.') def CheckVlogArguments(filename, clean_lines, linenum, error): """Checks that VLOG() is only used for defining a logging level. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and VLOG(FATAL) are not. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): error(filename, linenum, 'runtime/vlog', 5, 'VLOG() should be used with numeric verbosity level. ' 'Use LOG() if you want symbolic severity levels.') # Matches invalid increment: *count++, which moves pointer instead of # incrementing a value. _RE_PATTERN_INVALID_INCREMENT = re.compile( r'^\s*\*\w+(\+\+|--);') def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).') def IsMacroDefinition(clean_lines, linenum): if Search(r'^#define', clean_lines[linenum]): return True if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]): return True return False def IsForwardClassDeclaration(clean_lines, linenum): return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum]) class _BlockInfo(object): """Stores information about a generic block of code.""" def __init__(self, seen_open_brace): self.seen_open_brace = seen_open_brace self.open_parentheses = 0 self.inline_asm = _NO_ASM self.check_namespace_indentation = False def CheckBegin(self, filename, clean_lines, linenum, error): """Run checks that applies to text up to the opening brace. This is mostly for checking the text after the class identifier and the "{", usually where the base class is specified. For other blocks, there isn't much to check, so we always pass. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def CheckEnd(self, filename, clean_lines, linenum, error): """Run checks that applies to text after the closing brace. This is mostly used for checking end of namespace comments. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ pass def IsBlockInfo(self): """Returns true if this block is a _BlockInfo. This is convenient for verifying that an object is an instance of a _BlockInfo, but not an instance of any of the derived classes. Returns: True for this class, False for derived classes. """ return self.__class__ == _BlockInfo class _ExternCInfo(_BlockInfo): """Stores information about an 'extern "C"' block.""" def __init__(self): _BlockInfo.__init__(self, True) class _ClassInfo(_BlockInfo): """Stores information about a class.""" def __init__(self, name, class_or_struct, clean_lines, linenum): _BlockInfo.__init__(self, False) self.name = name self.starting_linenum = linenum self.is_derived = False self.check_namespace_indentation = True if class_or_struct == 'struct': self.access = 'public' self.is_struct = True else: self.access = 'private' self.is_struct = False # Remember initial indentation level for this class. Using raw_lines here # instead of elided to account for leading comments. self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum]) # Try to find the end of the class. This will be confused by things like: # class A { # } *x = { ... # # But it's still good enough for CheckSectionSpacing. self.last_line = 0 depth = 0 for i in range(linenum, clean_lines.NumLines()): line = clean_lines.elided[i] depth += line.count('{') - line.count('}') if not depth: self.last_line = i break def CheckBegin(self, filename, clean_lines, linenum, error): # Look for a bare ':' if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): self.is_derived = True def CheckEnd(self, filename, clean_lines, linenum, error): # If there is a DISALLOW macro, it should appear near the end of # the class. seen_last_thing_in_class = False for i in xrange(linenum - 1, self.starting_linenum, -1): match = Search( r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' + self.name + r'\)', clean_lines.elided[i]) if match: if seen_last_thing_in_class: error(filename, i, 'readability/constructors', 3, match.group(1) + ' should be the last thing in the class') break if not Match(r'^\s*$', clean_lines.elided[i]): seen_last_thing_in_class = True # Check that closing brace is aligned with beginning of the class. # Only do this if the closing brace is indented by only whitespaces. # This means we will not check single-line class definitions. indent = Match(r'^( *)\}', clean_lines.elided[linenum]) if indent and len(indent.group(1)) != self.class_indent: if self.is_struct: parent = 'struct ' + self.name else: parent = 'class ' + self.name error(filename, linenum, 'whitespace/indent', 3, 'Closing brace should be aligned with beginning of %s' % parent) class _NamespaceInfo(_BlockInfo): """Stores information about a namespace.""" def __init__(self, name, linenum): _BlockInfo.__init__(self, False) self.name = name or '' self.starting_linenum = linenum self.check_namespace_indentation = True def CheckEnd(self, filename, clean_lines, linenum, error): """Check end of namespace comments.""" line = clean_lines.raw_lines[linenum] # Check how many lines is enclosed in this namespace. Don't issue # warning for missing namespace comments if there aren't enough # lines. However, do apply checks if there is already an end of # namespace comment and it's incorrect. # # TODO(unknown): We always want to check end of namespace comments # if a namespace is large, but sometimes we also want to apply the # check if a short namespace contained nontrivial things (something # other than forward declarations). There is currently no logic on # deciding what these nontrivial things are, so this check is # triggered by namespace size only, which works most of the time. if (linenum - self.starting_linenum < 10 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): return # Look for matching comment at end of namespace. # # Note that we accept C style "/* */" comments for terminating # namespaces, so that code that terminate namespaces inside # preprocessor macros can be cpplint clean. # # We also accept stuff like "// end of namespace <name>." with the # period at the end. # # Besides these, we don't accept anything else, otherwise we might # get false negatives when existing comment is a substring of the # expected namespace. if self.name: # Named namespace if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + r'[\*/\.\\\s]*$'), line): error(filename, linenum, 'readability/namespace', 5, 'Namespace should be terminated with "// namespace %s"' % self.name) else: # Anonymous namespace if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): # If "// namespace anonymous" or "// anonymous namespace (more text)", # mention "// anonymous namespace" as an acceptable form if Match(r'}.*\b(namespace anonymous|anonymous namespace)\b', line): error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"' ' or "// anonymous namespace"') else: error(filename, linenum, 'readability/namespace', 5, 'Anonymous namespace should be terminated with "// namespace"') class _PreprocessorInfo(object): """Stores checkpoints of nesting stacks when #if/#else is seen.""" def __init__(self, stack_before_if): # The entire nesting stack before #if self.stack_before_if = stack_before_if # The entire nesting stack up to #else self.stack_before_else = [] # Whether we have already seen #else or #elif self.seen_else = False class NestingState(object): """Holds states related to parsing braces.""" def __init__(self): # Stack for tracking all braces. An object is pushed whenever we # see a "{", and popped when we see a "}". Only 3 types of # objects are possible: # - _ClassInfo: a class or struct. # - _NamespaceInfo: a namespace. # - _BlockInfo: some other type of block. self.stack = [] # Top of the previous stack before each Update(). # # Because the nesting_stack is updated at the end of each line, we # had to do some convoluted checks to find out what is the current # scope at the beginning of the line. This check is simplified by # saving the previous top of nesting stack. # # We could save the full stack, but we only need the top. Copying # the full nesting stack would slow down cpplint by ~10%. self.previous_stack_top = [] # Stack of _PreprocessorInfo objects. self.pp_stack = [] def SeenOpenBrace(self): """Check if we have seen the opening brace for the innermost block. Returns: True if we have seen the opening brace, False if the innermost block is still expecting an opening brace. """ return (not self.stack) or self.stack[-1].seen_open_brace def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo) def InExternC(self): """Check if we are currently one level inside an 'extern "C"' block. Returns: True if top of the stack is an extern block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ExternCInfo) def InClassDeclaration(self): """Check if we are currently one level inside a class or struct declaration. Returns: True if top of the stack is a class/struct, False otherwise. """ return self.stack and isinstance(self.stack[-1], _ClassInfo) def InAsmBlock(self): """Check if we are currently one level inside an inline ASM block. Returns: True if the top of the stack is a block containing inline ASM. """ return self.stack and self.stack[-1].inline_asm != _NO_ASM def InTemplateArgumentList(self, clean_lines, linenum, pos): """Check if current position is inside template argument list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: position just after the suspected template argument. Returns: True if (linenum, pos) is inside template arguments. """ while linenum < clean_lines.NumLines(): # Find the earliest character that might indicate a template argument line = clean_lines.elided[linenum] match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) if not match: linenum += 1 pos = 0 continue token = match.group(1) pos += len(match.group(0)) # These things do not look like template argument list: # class Suspect { # class Suspect x; } if token in ('{', '}', ';'): return False # These things look like template argument list: # template <class Suspect> # template <class Suspect = default_value> # template <class Suspect[]> # template <class Suspect...> if token in ('>', '=', '[', ']', '.'): return True # Check if token is an unmatched '<'. # If not, move on to the next character. if token != '<': pos += 1 if pos >= len(line): linenum += 1 pos = 0 continue # We can't be sure if we just find a single '<', and need to # find the matching '>'. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) if end_pos < 0: # Not sure if template argument list or syntax error in file return False linenum = end_line pos = end_pos return False def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass # TODO(unknown): Update() is too long, but we will refactor later. def Update(self, filename, clean_lines, linenum, error): """Update nesting state with current line. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remember top of the previous nesting stack. # # The stack is always pushed/popped and not modified in place, so # we can just do a shallow copy instead of copy.deepcopy. Using # deepcopy would slow down cpplint by ~28%. if self.stack: self.previous_stack_top = self.stack[-1] else: self.previous_stack_top = None # Update pp_stack self.UpdatePreprocessor(line) # Count parentheses. This is to avoid adding struct arguments to # the nesting stack. if self.stack: inner_block = self.stack[-1] depth_change = line.count('(') - line.count(')') inner_block.open_parentheses += depth_change # Also check if we are starting or ending an inline assembly block. if inner_block.inline_asm in (_NO_ASM, _END_ASM): if (depth_change != 0 and inner_block.open_parentheses == 1 and _MATCH_ASM.match(line)): # Enter assembly block inner_block.inline_asm = _INSIDE_ASM else: # Not entering assembly block. If previous line was _END_ASM, # we will now shift to _NO_ASM state. inner_block.inline_asm = _NO_ASM elif (inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0): # Exit assembly block inner_block.inline_asm = _END_ASM # Consume namespace declaration at the beginning of the line. Do # this in a loop so that we catch same line declarations like this: # namespace proto2 { namespace bridge { class MessageSet; } } while True: # Match start of namespace. The "\b\s*" below catches namespace # declarations even if it weren't followed by a whitespace, this # is so that we don't confuse our namespace checker. The # missing spaces will be flagged by CheckSpacing. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) if not namespace_decl_match: break new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) self.stack.append(new_namespace) line = namespace_decl_match.group(2) if line.find('{') != -1: new_namespace.seen_open_brace = True line = line[line.find('{') + 1:] # Look for a class declaration in whatever is left of the line # after parsing namespaces. The regexp accounts for decorated classes # such as in: # class LOCKABLE API Object { # }; class_decl_match = Match( r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?' r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' r'(.*)$', line) if (class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0)): # We do not want to accept classes that are actually template arguments: # template <class Ignore1, # class Ignore2 = Default<Args>, # template <Args> class Ignore3> # void Function() {}; # # To avoid template argument cases, we scan forward and look for # an unmatched '>'. If we see one, assume we are inside a # template argument list. end_declaration = len(class_decl_match.group(1)) if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): self.stack.append(_ClassInfo( class_decl_match.group(3), class_decl_match.group(2), clean_lines, linenum)) line = class_decl_match.group(4) # If we have not yet seen the opening brace for the innermost block, # run checks here. if not self.SeenOpenBrace(): self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) # Update access control if we are inside a class/struct if self.stack and isinstance(self.stack[-1], _ClassInfo): classinfo = self.stack[-1] access_match = Match( r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' r':(?:[^:]|$)', line) if access_match: classinfo.access = access_match.group(2) # Check that access keywords are indented +1 space. Skip this # check if the keywords are not preceded by whitespaces. indent = access_match.group(1) if (len(indent) != classinfo.class_indent + 1 and Match(r'^\s*$', indent)): if classinfo.is_struct: parent = 'struct ' + classinfo.name else: parent = 'class ' + classinfo.name slots = '' if access_match.group(3): slots = access_match.group(3) error(filename, linenum, 'whitespace/indent', 3, '%s%s: should be indented +1 space inside %s' % ( access_match.group(2), slots, parent)) # Consume braces or semicolons from what's left of the line while True: # Match first brace, semicolon, or closed parenthesis. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) if not matched: break token = matched.group(1) if token == '{': # If namespace or class hasn't seen a opening brace yet, mark # namespace/class head as complete. Push a new block onto the # stack otherwise. if not self.SeenOpenBrace(): self.stack[-1].seen_open_brace = True elif Match(r'^extern\s*"[^"]*"\s*\{', line): self.stack.append(_ExternCInfo()) else: self.stack.append(_BlockInfo(True)) if _MATCH_ASM.match(line): self.stack[-1].inline_asm = _BLOCK_ASM elif token == ';' or token == ')': # If we haven't seen an opening brace yet, but we already saw # a semicolon, this is probably a forward declaration. Pop # the stack for these. # # Similarly, if we haven't seen an opening brace yet, but we # already saw a closing parenthesis, then these are probably # function arguments with extra "class" or "struct" keywords. # Also pop these stack for these. if not self.SeenOpenBrace(): self.stack.pop() else: # token == '}' # Perform end of block checks and pop the stack. if self.stack: self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) self.stack.pop() line = matched.group(2) def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None def CheckCompletedBlocks(self, filename, error): """Checks that all classes and namespaces have been completely parsed. Call this when all lines in a file have been processed. Args: filename: The name of the current file. error: The function to call with any errors found. """ # Note: This test can result in false positives if #ifdef constructs # get in the way of brace matching. See the testBuildClass test in # cpplint_unittest.py for an example of this. for obj in self.stack: if isinstance(obj, _ClassInfo): error(filename, obj.starting_linenum, 'build/class', 5, 'Failed to find complete declaration of class %s' % obj.name) elif isinstance(obj, _NamespaceInfo): error(filename, obj.starting_linenum, 'build/namespaces', 5, 'Failed to find complete declaration of namespace %s' % obj.name) def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error): r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. Complain about several constructs which gcc-2 accepts, but which are not standard C++. Warning about these in lint is one way to ease the transition to new compilers. - put storage class first (e.g. "static const" instead of "const static"). - "%lld" instead of %qd" in printf-type functions. - "%1$d" is non-standard in printf-type functions. - "\%" is an undefined character escape sequence. - text after #endif is not allowed. - invalid inner-style forward declaration. - >? and <? operators, and their >?= and <?= cousins. Additionally, check for constructor/destructor style violations and reference members, as it is very convenient to do so while checking for gcc-2 compliance. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message """ # Remove comments from the line, but leave in strings for now. line = clean_lines.lines[linenum] if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): error(filename, linenum, 'runtime/printf_format', 3, '%q in format strings is deprecated. Use %ll instead.') if Search(r'printf\s*\(.*".*%\d+\$', line): error(filename, linenum, 'runtime/printf_format', 2, '%N$ formats are unconventional. Try rewriting to avoid them.') # Remove escaped backslashes before looking for undefined escapes. line = line.replace('\\\\', '') if Search(r'("|\').*\\(%|\[|\(|{)', line): error(filename, linenum, 'build/printf_format', 3, '%, [, (, and { are undefined character escapes. Unescape them.') # For the rest, work with both comments and strings removed. line = clean_lines.elided[linenum] if Search(r'\b(const|volatile|void|char|short|int|long' r'|float|double|signed|unsigned' r'|schar|u?int8|u?int16|u?int32|u?int64)' r'\s+(register|static|extern|typedef)\b', line): error(filename, linenum, 'build/storage_class', 5, 'Storage class (static, extern, typedef, etc) should be first.') if Match(r'\s*#\s*endif\s*[^/\s]+', line): error(filename, linenum, 'build/endif_comment', 5, 'Uncommented text after #endif is non-standard. Use a comment.') if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): error(filename, linenum, 'build/forward_decl', 5, 'Inner-style forward declarations are invalid. Remove this line.') if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line): error(filename, linenum, 'build/deprecated', 3, '>? and <? (max and min) operators are non-standard and deprecated.') if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): # TODO(unknown): Could it be expanded safely to arbitrary references, # without triggering too many false positives? The first # attempt triggered 5 warnings for mostly benign code in the regtest, hence # the restriction. # Here's the original regexp, for the reference: # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' error(filename, linenum, 'runtime/member_string_references', 2, 'const string& members are dangerous. It is much better to use ' 'alternatives, such as pointers or simple constants.') # Everything else in this function operates on class declarations. # Return early if the top of the nesting stack is not a class, or if # the class head is not completed yet. classinfo = nesting_state.InnermostClass() if not classinfo or not classinfo.seen_open_brace: return # The class may have been declared with namespace or classname qualifiers. # The constructor and destructor will not have those qualifiers. base_classname = classinfo.name.split('::')[-1] # Look for single-argument constructors that aren't marked explicit. # Technically a valid construct, but against style. Also look for # non-single-argument constructors which are also technically valid, but # strongly suggest something is wrong. explicit_constructor_match = Match( r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*' r'\(((?:[^()]|\([^()]*\))*)\)' % re.escape(base_classname), line) if explicit_constructor_match: is_marked_explicit = explicit_constructor_match.group(1) if not explicit_constructor_match.group(2): constructor_args = [] else: constructor_args = explicit_constructor_match.group(2).split(',') # collapse arguments so that commas in template parameter lists and function # argument parameter lists don't split arguments in two i = 0 while i < len(constructor_args): constructor_arg = constructor_args[i] while (constructor_arg.count('<') > constructor_arg.count('>') or constructor_arg.count('(') > constructor_arg.count(')')): constructor_arg += ',' + constructor_args[i + 1] del constructor_args[i + 1] constructor_args[i] = constructor_arg i += 1 defaulted_args = [arg for arg in constructor_args if '=' in arg] noarg_constructor = (not constructor_args or # empty arg list # 'void' arg specifier (len(constructor_args) == 1 and constructor_args[0].strip() == 'void')) onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg not noarg_constructor) or # all but at most one arg defaulted (len(constructor_args) >= 1 and not noarg_constructor and len(defaulted_args) >= len(constructor_args) - 1)) initializer_list_constructor = bool( onearg_constructor and Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) copy_constructor = bool( onearg_constructor and Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' % re.escape(base_classname), constructor_args[0].strip())) if (not is_marked_explicit and onearg_constructor and not initializer_list_constructor and not copy_constructor): if defaulted_args: error(filename, linenum, 'runtime/explicit', 5, 'Constructors callable with one argument ' 'should be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 5, 'Single-parameter constructors should be marked explicit.') elif is_marked_explicit and not onearg_constructor: if noarg_constructor: error(filename, linenum, 'runtime/explicit', 5, 'Zero-parameter constructors should not be marked explicit.') else: error(filename, linenum, 'runtime/explicit', 0, 'Constructors that require multiple arguments ' 'should not be marked explicit.') def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): """Checks for the correctness of various spacing around function calls. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Since function calls often occur inside if/for/while/switch # expressions - which have their own, more liberal conventions - we # first see if we should be looking inside such an expression for a # function call, to which we can apply more strict standards. fncall = line # if there's no control flow construct, look at whole line for pattern in (r'\bif\s*\((.*)\)\s*{', r'\bfor\s*\((.*)\)\s*{', r'\bwhile\s*\((.*)\)\s*[{;]', r'\bswitch\s*\((.*)\)\s*{'): match = Search(pattern, line) if match: fncall = match.group(1) # look inside the parens for function calls break # Except in if/for/while/switch, there should never be space # immediately inside parens (eg "f( 3, 4 )"). We make an exception # for nested parens ( (a+b) + c ). Likewise, there should never be # a space before a ( when it's a function argument. I assume it's a # function argument when the char before the whitespace is legal in # a function name (alnum + _) and we're not starting a macro. Also ignore # pointers and references to arrays and functions coz they're too tricky: # we use a very simple way to recognize these: # " (something)(maybe-something)" or # " (something)(maybe-something," or # " (something)[something]" # Note that we assume the contents of [] to be short enough that # they'll never need to wrap. if ( # Ignore control structures. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', fncall) and # Ignore pointers/references to functions. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and # Ignore pointers/references to arrays. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call error(filename, linenum, 'whitespace/parens', 4, 'Extra space after ( in function call') elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Extra space after (') if (Search(r'\w\s+\(', fncall) and not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and not Search(r'\bcase\s+\(', fncall)): # TODO(unknown): Space after an operator function seem to be a common # error, silence those for now by restricting them to highest verbosity. if Search(r'\boperator_*\b', line): error(filename, linenum, 'whitespace/parens', 0, 'Extra space before ( in function call') else: error(filename, linenum, 'whitespace/parens', 4, 'Extra space before ( in function call') # If the ) is followed only by a newline or a { + newline, assume it's # part of a control statement (if/while/etc), and don't complain if Search(r'[^)]\s+\)\s*[^{\s]', fncall): # If the closing parenthesis is preceded by only whitespaces, # try to give a more descriptive error message. if Search(r'^\s+\)', fncall): error(filename, linenum, 'whitespace/parens', 2, 'Closing ) should be moved to the previous line') else: error(filename, linenum, 'whitespace/parens', 2, 'Extra space before )') def IsBlankLine(line): """Returns true if the given line is blank. We consider a line to be blank if the line is empty or consists of only white spaces. Args: line: A line of a string. Returns: True, if the given line is blank. """ return not line or line.isspace() def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error): is_namespace_indent_item = ( len(nesting_state.stack) > 1 and nesting_state.stack[-1].check_namespace_indentation and isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and nesting_state.previous_stack_top == nesting_state.stack[-2]) if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, clean_lines.elided, line): CheckItemIndentationInNamespace(filename, clean_lines.elided, line, error) def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error): """Reports for long function bodies. For an overview why this is done, see: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions Uses a simplistic algorithm assuming other style guidelines (especially spacing) are followed. Only checks unindented functions, so class members are unchecked. Trivial bodies are unchecked, so constructors with huge initializer lists may be missed. Blank/comment lines are not counted so as to avoid encouraging the removal of vertical space and comments just to get through a lint check. NOLINT *on the last line of a function* disables this check. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. function_state: Current function name and lines in body so far. error: The function to call with any errors found. """ lines = clean_lines.lines line = lines[linenum] joined_line = '' starting_func = False regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... match_result = Match(regexp, line) if match_result: # If the name is all caps and underscores, figure it's a macro and # ignore it, unless it's TEST or TEST_F. function_name = match_result.group(1).split()[-1] if function_name == 'TEST' or function_name == 'TEST_F' or ( not Match(r'[A-Z_]+$', function_name)): starting_func = True if starting_func: body_found = False for start_linenum in xrange(linenum, clean_lines.NumLines()): start_line = lines[start_linenum] joined_line += ' ' + start_line.lstrip() if Search(r'(;|})', start_line): # Declarations and trivial functions body_found = True break # ... ignore elif Search(r'{', start_line): body_found = True function = Search(r'((\w|:)*)\(', line).group(1) if Match(r'TEST', function): # Handle TEST... macros parameter_regexp = Search(r'(\(.*\))', joined_line) if parameter_regexp: # Ignore bad syntax function += parameter_regexp.group(1) else: function += '()' function_state.Begin(function) break if not body_found: # No body for the function (or evidence of a non-function) was found. error(filename, linenum, 'readability/fn_size', 5, 'Lint failed to find start of function body.') elif Match(r'^\}\s*$', line): # function end function_state.Check(error, filename, linenum) function_state.End() elif not Match(r'^\s*$', line): function_state.Count() # Count non-blank/non-comment lines. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') def CheckComment(line, filename, linenum, next_line_start, error): """Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found. """ commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison if (line.count('"', 0, commentpos) - line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes # Allow one space for new scopes, two spaces otherwise: if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # Checks for common mistakes in TODO comments. comment = line[commentpos:] match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') # If the comment contains an alphanumeric character, there # should be a space somewhere between it and the // unless # it's a /// or //! Doxygen comment. if (Match(r'//[^ ]*\w', comment) and not Match(r'(///|//\!)(\s+|$)', comment)): error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment') def CheckAccess(filename, clean_lines, linenum, nesting_state, error): """Checks for improper use of DISALLOW* macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) if not matched: return if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): if nesting_state.stack[-1].access != 'private': error(filename, linenum, 'readability/constructors', 3, '%s must be in the private: section' % matched.group(1)) else: # Found DISALLOW* macro outside a class declaration, or perhaps it # was used inside a function when it should have been part of the # class declaration. We could issue a warning here, but it # probably resulted in a compiler error already. pass def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): """Checks for the correctness of various spacing issues in the code. Things we check for: spaces around operators, spaces after if/for/while/switch, no spaces around parens in function calls, two spaces between code and comment, don't start a block with a blank line, don't end a function with a blank line, don't add a blank line after public/protected/private, don't have too many blank lines in a row. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw = clean_lines.lines_without_raw_strings line = raw[linenum] # Before nixing comments, check if the line is blank for no good # reason. This includes the first line after a block is opened, and # blank lines at the end of a function (ie, right before a line like '}' # # Skip all the blank line checks if we are immediately inside a # namespace body. In other words, don't issue blank line warnings # for this block: # namespace { # # } # # A warning about missing end of namespace comments will be issued instead. # # Also skip blank line checks for 'extern "C"' blocks, which are formatted # like namespaces. if (IsBlankLine(line) and not nesting_state.InNamespaceBody() and not nesting_state.InExternC()): elided = clean_lines.elided prev_line = elided[linenum - 1] prevbrace = prev_line.rfind('{') # TODO(unknown): Don't complain if line before blank line, and line after, # both start with alnums and are indented the same amount. # This ignores whitespace at the start of a namespace block # because those are not usually indented. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: # OK, we have a blank line at the start of a code block. Before we # complain, we check if it is an exception to the rule: The previous # non-empty line has the parameters of a function header that are indented # 4 spaces (because they did not fit in a 80 column line when placed on # the same line as the function name). We also check for the case where # the previous line is indented 6 spaces, which may happen when the # initializers of a constructor do not fit into a 80 column line. exception = False if Match(r' {6}\w', prev_line): # Initializer list? # We are looking for the opening column of initializer list, which # should be indented 4 spaces to cause 6 space indentation afterwards. search_position = linenum-2 while (search_position >= 0 and Match(r' {6}\w', elided[search_position])): search_position -= 1 exception = (search_position >= 0 and elided[search_position][:5] == ' :') else: # Search for the function arguments or an initializer list. We use a # simple heuristic here: If the line is indented 4 spaces; and we have a # closing paren, without the opening paren, followed by an opening brace # or colon (for initializer lists) we assume that it is the last line of # a function header. If we have a colon indented 4 spaces, it is an # initializer list. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', prev_line) or Match(r' {4}:', prev_line)) if not exception: error(filename, linenum, 'whitespace/blank_line', 2, 'Redundant blank line at the start of a code block ' 'should be deleted.') # Ignore blank lines at the end of a block in a long if-else # chain, like this: # if (condition1) { # // Something followed by a blank line # # } else if (condition2) { # // Something else # } if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] if (next_line and Match(r'\s*}', next_line) and next_line.find('} else ') == -1): error(filename, linenum, 'whitespace/blank_line', 3, 'Redundant blank line at the end of a code block ' 'should be deleted.') matched = Match(r'\s*(public|protected|private):', prev_line) if matched: error(filename, linenum, 'whitespace/blank_line', 3, 'Do not leave a blank line after "%s:"' % matched.group(1)) # Next, check comments next_line_start = 0 if linenum + 1 < clean_lines.NumLines(): next_line = raw[linenum + 1] next_line_start = len(next_line) - len(next_line.lstrip()) CheckComment(line, filename, linenum, next_line_start, error) # get rid of comments and strings line = clean_lines.elided[linenum] # You shouldn't have spaces before your brackets, except maybe after # 'delete []' or 'return []() {};' if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line): error(filename, linenum, 'whitespace/braces', 5, 'Extra space before [') # In range-based for, we wanted spaces before and after the colon, but # not around "::" tokens that might appear. if (Search(r'for *\(.*[^:]:[^: ]', line) or Search(r'for *\(.*[^: ]:[^:]', line)): error(filename, linenum, 'whitespace/forcolon', 2, 'Missing space around colon in range-based for loop') def CheckOperatorSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing around operators. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Don't try to do spacing checks for operator methods. Do this by # replacing the troublesome characters with something else, # preserving column position for all other characters. # # The replacement is done repeatedly to avoid false positives from # operators that call operators. while True: match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line) if match: line = match.group(1) + ('_' * len(match.group(2))) + match.group(3) else: break # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". # Otherwise not. Note we only check for non-spaces on *both* sides; # sometimes people put non-spaces on one side when aligning ='s among # many lines (not that this is behavior that I approve of...) if ((Search(r'[\w.]=', line) or Search(r'=[\w.]', line)) and not Search(r'\b(if|while|for) ', line) # Operators taken from [lex.operators] in C++11 standard. and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line) and not Search(r'operator=', line)): error(filename, linenum, 'whitespace/operators', 4, 'Missing spaces around =') # It's ok not to have spaces around binary operators like + - * /, but if # there's too little whitespace, we get concerned. It's hard to tell, # though, so we punt on this one for now. TODO. # You should always have whitespace around binary operators. # # Check <= and >= first to avoid false positives with < and >, then # check non-include lines for spacing around < and >. # # If the operator is followed by a comma, assume it's be used in a # macro context and don't do any checks. This avoids false # positives. # # Note that && is not included here. Those are checked separately # in CheckRValueReference match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around %s' % match.group(1)) elif not Match(r'#.*include', line): # Look for < that is not surrounded by spaces. This is only # triggered if both sides are missing spaces, even though # technically should should flag if at least one side is missing a # space. This is done to avoid some false positives with shifts. match = Match(r'^(.*[^\s<])<[^\s=<,]', line) if match: (_, _, end_pos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if end_pos <= -1: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <') # Look for > that is not surrounded by spaces. Similar to the # above, we only trigger if both sides are missing spaces to avoid # false positives with shifts. match = Match(r'^(.*[^-\s>])>[^\s=>,]', line) if match: (_, _, start_pos) = ReverseCloseExpression( clean_lines, linenum, len(match.group(1))) if start_pos <= -1: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >') # We allow no-spaces around << when used like this: 10<<20, but # not otherwise (particularly, not when used as streams) # # We also allow operators following an opening parenthesis, since # those tend to be macros that deal with operators. match = Search(r'(operator|[^\s(<])(?:L|UL|ULL|l|ul|ull)?<<([^\s,=<])', line) if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and not (match.group(1) == 'operator' and match.group(2) == ';')): error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around <<') # We allow no-spaces around >> for almost anything. This is because # C++11 allows ">>" to close nested templates, which accounts for # most cases when ">>" is not followed by a space. # # We still warn on ">>" followed by alpha character, because that is # likely due to ">>" being used for right shifts, e.g.: # value >> alpha # # When ">>" is used to close templates, the alphanumeric letter that # follows would be part of an identifier, and there should still be # a space separating the template type and the identifier. # type<type<type>> alpha match = Search(r'>>[a-zA-Z_]', line) if match: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around >>') # There shouldn't be space around unary operators match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) if match: error(filename, linenum, 'whitespace/operators', 4, 'Extra space for operator %s' % match.group(1)) def CheckParenthesisSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing around parentheses. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # No spaces after an if, while, switch, or for match = Search(r' (if\(|for\(|while\(|switch\()', line) if match: error(filename, linenum, 'whitespace/parens', 5, 'Missing space before ( in %s' % match.group(1)) # For if/for/while/switch, the left and right parens should be # consistent about how many spaces are inside the parens, and # there should either be zero or one spaces inside the parens. # We don't want: "if ( foo)" or "if ( foo )". # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. match = Search(r'\b(if|for|while|switch)\s*' r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', line) if match: if len(match.group(2)) != len(match.group(4)): if not (match.group(3) == ';' and len(match.group(2)) == 1 + len(match.group(4)) or not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): error(filename, linenum, 'whitespace/parens', 5, 'Mismatching spaces inside () in %s' % match.group(1)) if len(match.group(2)) not in [0, 1]: error(filename, linenum, 'whitespace/parens', 5, 'Should have zero or one spaces inside ( and ) in %s' % match.group(1)) def CheckCommaSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing near commas and semicolons. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ raw = clean_lines.lines_without_raw_strings line = clean_lines.elided[linenum] # You should always have a space after a comma (either as fn arg or operator) # # This does not apply when the non-space character following the # comma is another comma, since the only time when that happens is # for empty macro arguments. # # We run this check in two passes: first pass on elided lines to # verify that lines contain missing whitespaces, second pass on raw # lines to confirm that those missing whitespaces are not due to # elided comments. if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and Search(r',[^,\s]', raw[linenum])): error(filename, linenum, 'whitespace/comma', 3, 'Missing space after ,') # You should always have a space after a semicolon # except for few corner cases # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more # space after ; if Search(r';[^\s};\\)/]', line): error(filename, linenum, 'whitespace/semicolon', 3, 'Missing space after ;') def CheckBracesSpacing(filename, clean_lines, linenum, error): """Checks for horizontal spacing near commas. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Except after an opening paren, or after another opening brace (in case of # an initializer list, for instance), you should have spaces before your # braces. And since you should never have braces at the beginning of a line, # this is an easy test. match = Match(r'^(.*[^ ({>]){', line) if match: # Try a bit harder to check for brace initialization. This # happens in one of the following forms: # Constructor() : initializer_list_{} { ... } # Constructor{}.MemberFunction() # Type variable{}; # FunctionCall(type{}, ...); # LastArgument(..., type{}); # LOG(INFO) << type{} << " ..."; # map_of_type[{...}] = ...; # ternary = expr ? new type{} : nullptr; # OuterTemplate<InnerTemplateConstructor<Type>{}> # # We check for the character following the closing brace, and # silence the warning if it's one of those listed above, i.e. # "{.;,)<>]:". # # To account for nested initializer list, we allow any number of # closing braces up to "{;,)<". We can't simply silence the # warning on first sight of closing brace, because that would # cause false negatives for things that are not initializer lists. # Silence this: But not this: # Outer{ if (...) { # Inner{...} if (...){ // Missing space before { # }; } # # There is a false negative with this approach if people inserted # spurious semicolons, e.g. "if (cond){};", but we will catch the # spurious semicolon with a separate check. (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) trailing_text = '' if endpos > -1: trailing_text = endline[endpos:] for offset in xrange(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)): trailing_text += clean_lines.elided[offset] if not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before {') # Make sure '} else {' has spaces. if Search(r'}else', line): error(filename, linenum, 'whitespace/braces', 5, 'Missing space before else') # You shouldn't have a space before a semicolon at the end of the line. # There's a special case for "for" since the style guide allows space before # the semicolon there. if Search(r':\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Semicolon defining empty statement. Use {} instead.') elif Search(r'^\s*;\s*$', line): error(filename, linenum, 'whitespace/semicolon', 5, 'Line contains only semicolon. If this should be an empty statement, ' 'use {} instead.') elif (Search(r'\s+;\s*$', line) and not Search(r'\bfor\b', line)): error(filename, linenum, 'whitespace/semicolon', 5, 'Extra space before last semicolon. If this should be an empty ' 'statement, use {} instead.') def IsDecltype(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is decltype(). Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is decltype() expression, False otherwise. """ (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) if start_col < 0: return False if Search(r'\bdecltype\s*$', text[0:start_col]): return True return False def IsTemplateParameterList(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is the end of template<>. Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is end of a template parameter list, False otherwise. """ (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, column) if (startpos > -1 and Search(r'\btemplate\s*$', clean_lines.elided[startline][0:startpos])): return True return False def IsRValueType(typenames, clean_lines, nesting_state, linenum, column): """Check if the token ending on (linenum, column) is a type. Assumes that text to the right of the column is "&&" or a function name. Args: typenames: set of type names from template-argument-list. clean_lines: A CleansedLines instance containing the file. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is a type, False if we are not sure. """ prefix = clean_lines.elided[linenum][0:column] # Get one word to the left. If we failed to do so, this is most # likely not a type, since it's unlikely that the type name and "&&" # would be split across multiple lines. match = Match(r'^(.*)(\b\w+|[>*)&])\s*$', prefix) if not match: return False # Check text following the token. If it's "&&>" or "&&," or "&&...", it's # most likely a rvalue reference used inside a template. suffix = clean_lines.elided[linenum][column:] if Match(r'&&\s*(?:[>,]|\.\.\.)', suffix): return True # Check for known types and end of templates: # int&& variable # vector<int>&& variable # # Because this function is called recursively, we also need to # recognize pointer and reference types: # int* Function() # int& Function() if (match.group(2) in typenames or match.group(2) in ['char', 'char16_t', 'char32_t', 'wchar_t', 'bool', 'short', 'int', 'long', 'signed', 'unsigned', 'float', 'double', 'void', 'auto', '>', '*', '&']): return True # If we see a close parenthesis, look for decltype on the other side. # decltype would unambiguously identify a type, anything else is # probably a parenthesized expression and not a type. if match.group(2) == ')': return IsDecltype( clean_lines, linenum, len(match.group(1)) + len(match.group(2)) - 1) # Check for casts and cv-qualifiers. # match.group(1) remainder # -------------- --------- # const_cast< type&& # const type&& # type const&& if Search(r'\b(?:const_cast\s*<|static_cast\s*<|dynamic_cast\s*<|' r'reinterpret_cast\s*<|\w+\s)\s*$', match.group(1)): return True # Look for a preceding symbol that might help differentiate the context. # These are the cases that would be ambiguous: # match.group(1) remainder # -------------- --------- # Call ( expression && # Declaration ( type&& # sizeof ( type&& # if ( expression && # while ( expression && # for ( type&& # for( ; expression && # statement ; type&& # block { type&& # constructor { expression && start = linenum line = match.group(1) match_symbol = None while start >= 0: # We want to skip over identifiers and commas to get to a symbol. # Commas are skipped so that we can find the opening parenthesis # for function parameter lists. match_symbol = Match(r'^(.*)([^\w\s,])[\w\s,]*$', line) if match_symbol: break start -= 1 line = clean_lines.elided[start] if not match_symbol: # Probably the first statement in the file is an rvalue reference return True if match_symbol.group(2) == '}': # Found closing brace, probably an indicate of this: # block{} type&& return True if match_symbol.group(2) == ';': # Found semicolon, probably one of these: # for(; expression && # statement; type&& # Look for the previous 'for(' in the previous lines. before_text = match_symbol.group(1) for i in xrange(start - 1, max(start - 6, 0), -1): before_text = clean_lines.elided[i] + before_text if Search(r'for\s*\([^{};]*$', before_text): # This is the condition inside a for-loop return False # Did not find a for-init-statement before this semicolon, so this # is probably a new statement and not a condition. return True if match_symbol.group(2) == '{': # Found opening brace, probably one of these: # block{ type&& = ... ; } # constructor{ expression && expression } # Look for a closing brace or a semicolon. If we see a semicolon # first, this is probably a rvalue reference. line = clean_lines.elided[start][0:len(match_symbol.group(1)) + 1] end = start depth = 1 while True: for ch in line: if ch == ';': return True elif ch == '{': depth += 1 elif ch == '}': depth -= 1 if depth == 0: return False end += 1 if end >= clean_lines.NumLines(): break line = clean_lines.elided[end] # Incomplete program? return False if match_symbol.group(2) == '(': # Opening parenthesis. Need to check what's to the left of the # parenthesis. Look back one extra line for additional context. before_text = match_symbol.group(1) if linenum > 1: before_text = clean_lines.elided[linenum - 1] + before_text before_text = match_symbol.group(1) # Patterns that are likely to be types: # [](type&& # for (type&& # sizeof(type&& # operator=(type&& # if Search(r'(?:\]|\bfor|\bsizeof|\boperator\s*\S+\s*)\s*$', before_text): return True # Patterns that are likely to be expressions: # if (expression && # while (expression && # : initializer(expression && # , initializer(expression && # ( FunctionCall(expression && # + FunctionCall(expression && # + (expression && # # The last '+' represents operators such as '+' and '-'. if Search(r'(?:\bif|\bwhile|[-+=%^(<!?:,&*]\s*)$', before_text): return False # Something else. Check that tokens to the left look like # return_type function_name match_func = Match(r'^(.*\S.*)\s+\w(?:\w|::)*(?:<[^<>]*>)?\s*$', match_symbol.group(1)) if match_func: # Check for constructors, which don't have return types. if Search(r'\b(?:explicit|inline)$', match_func.group(1)): return True implicit_constructor = Match(r'\s*(\w+)\((?:const\s+)?(\w+)', prefix) if (implicit_constructor and implicit_constructor.group(1) == implicit_constructor.group(2)): return True return IsRValueType(typenames, clean_lines, nesting_state, linenum, len(match_func.group(1))) # Nothing before the function name. If this is inside a block scope, # this is probably a function call. return not (nesting_state.previous_stack_top and nesting_state.previous_stack_top.IsBlockInfo()) if match_symbol.group(2) == '>': # Possibly a closing bracket, check that what's on the other side # looks like the start of a template. return IsTemplateParameterList( clean_lines, start, len(match_symbol.group(1))) # Some other symbol, usually something like "a=b&&c". This is most # likely not a type. return False def IsDeletedOrDefault(clean_lines, linenum): """Check if current constructor or operator is deleted or default. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if this is a deleted or default constructor. """ open_paren = clean_lines.elided[linenum].find('(') if open_paren < 0: return False (close_line, _, close_paren) = CloseExpression( clean_lines, linenum, open_paren) if close_paren < 0: return False return Match(r'\s*=\s*(?:delete|default)\b', close_line[close_paren:]) def IsRValueAllowed(clean_lines, linenum, typenames): """Check if RValue reference is allowed on a particular line. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. typenames: set of type names from template-argument-list. Returns: True if line is within the region where RValue references are allowed. """ # Allow region marked by PUSH/POP macros for i in xrange(linenum, 0, -1): line = clean_lines.elided[i] if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line): if not line.endswith('PUSH'): return False for j in xrange(linenum, clean_lines.NumLines(), 1): line = clean_lines.elided[j] if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line): return line.endswith('POP') # Allow operator= line = clean_lines.elided[linenum] if Search(r'\boperator\s*=\s*\(', line): return IsDeletedOrDefault(clean_lines, linenum) # Allow constructors match = Match(r'\s*(?:[\w<>]+::)*([\w<>]+)\s*::\s*([\w<>]+)\s*\(', line) if match and match.group(1) == match.group(2): return IsDeletedOrDefault(clean_lines, linenum) if Search(r'\b(?:explicit|inline)\s+[\w<>]+\s*\(', line): return IsDeletedOrDefault(clean_lines, linenum) if Match(r'\s*[\w<>]+\s*\(', line): previous_line = 'ReturnType' if linenum > 0: previous_line = clean_lines.elided[linenum - 1] if Match(r'^\s*$', previous_line) or Search(r'[{}:;]\s*$', previous_line): return IsDeletedOrDefault(clean_lines, linenum) # Reject types not mentioned in template-argument-list while line: match = Match(r'^.*?(\w+)\s*&&(.*)$', line) if not match: break if match.group(1) not in typenames: return False line = match.group(2) # All RValue types that were in template-argument-list should have # been removed by now. Those were allowed, assuming that they will # be forwarded. # # If there are no remaining RValue types left (i.e. types that were # not found in template-argument-list), flag those as not allowed. return line.find('&&') < 0 def GetTemplateArgs(clean_lines, linenum): """Find list of template arguments associated with this function declaration. Args: clean_lines: A CleansedLines instance containing the file. linenum: Line number containing the start of the function declaration, usually one line after the end of the template-argument-list. Returns: Set of type names, or empty set if this does not appear to have any template parameters. """ # Find start of function func_line = linenum while func_line > 0: line = clean_lines.elided[func_line] if Match(r'^\s*$', line): return set() if line.find('(') >= 0: break func_line -= 1 if func_line == 0: return set() # Collapse template-argument-list into a single string argument_list = '' match = Match(r'^(\s*template\s*)<', clean_lines.elided[func_line]) if match: # template-argument-list on the same line as function name start_col = len(match.group(1)) _, end_line, end_col = CloseExpression(clean_lines, func_line, start_col) if end_col > -1 and end_line == func_line: start_col += 1 # Skip the opening bracket argument_list = clean_lines.elided[func_line][start_col:end_col] elif func_line > 1: # template-argument-list one line before function name match = Match(r'^(.*)>\s*$', clean_lines.elided[func_line - 1]) if match: end_col = len(match.group(1)) _, start_line, start_col = ReverseCloseExpression( clean_lines, func_line - 1, end_col) if start_col > -1: start_col += 1 # Skip the opening bracket while start_line < func_line - 1: argument_list += clean_lines.elided[start_line][start_col:] start_col = 0 start_line += 1 argument_list += clean_lines.elided[func_line - 1][start_col:end_col] if not argument_list: return set() # Extract type names typenames = set() while True: match = Match(r'^[,\s]*(?:typename|class)(?:\.\.\.)?\s+(\w+)(.*)$', argument_list) if not match: break typenames.add(match.group(1)) argument_list = match.group(2) return typenames def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error): """Check for rvalue references. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Find lines missing spaces around &&. # TODO(unknown): currently we don't check for rvalue references # with spaces surrounding the && to avoid false positives with # boolean expressions. line = clean_lines.elided[linenum] match = Match(r'^(.*\S)&&', line) if not match: match = Match(r'(.*)&&\S', line) if (not match) or '(&&)' in line or Search(r'\boperator\s*$', match.group(1)): return # Either poorly formed && or an rvalue reference, check the context # to get a more accurate error message. Mostly we want to determine # if what's to the left of "&&" is a type or not. typenames = GetTemplateArgs(clean_lines, linenum) and_pos = len(match.group(1)) if IsRValueType(typenames, clean_lines, nesting_state, linenum, and_pos): if not IsRValueAllowed(clean_lines, linenum, typenames): error(filename, linenum, 'build/c++11', 3, 'RValue references are an unapproved C++ feature.') else: error(filename, linenum, 'whitespace/operators', 3, 'Missing spaces around &&') def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1)) def GetPreviousNonBlankLine(clean_lines, linenum): """Return the most recent non-blank line and its line number. Args: clean_lines: A CleansedLines instance containing the file contents. linenum: The number of the line to check. Returns: A tuple with two elements. The first element is the contents of the last non-blank line before the current line, or the empty string if this is the first non-blank line. The second is the line number of that line, or -1 if this is the first non-blank line. """ prevlinenum = linenum - 1 while prevlinenum >= 0: prevline = clean_lines.elided[prevlinenum] if not IsBlankLine(prevline): # if not a blank line... return (prevline, prevlinenum) prevlinenum -= 1 return ('', -1) def CheckBraces(filename, clean_lines, linenum, error): """Looks for misplaced braces (e.g. at the end of line). Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # get rid of comments and strings if Match(r'\s*{\s*$', line): # We allow an open brace to start a line in the case where someone is using # braces in a block to explicitly create a new scope, which is commonly used # to control the lifetime of stack-allocated variables. Braces are also # used for brace initializers inside function calls. We don't detect this # perfectly: we just don't complain if the last non-whitespace character on # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the # previous line starts a preprocessor block. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if (not Search(r'[,;:}{(]\s*$', prevline) and not Match(r'\s*#', prevline)): error(filename, linenum, 'whitespace/braces', 4, '{ should almost always be at the end of the previous line') # An else clause should be on the same line as the preceding closing brace. if Match(r'\s*else\b\s*(?:if\b|\{|$)', line): prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if Match(r'\s*}\s*$', prevline): error(filename, linenum, 'whitespace/newline', 4, 'An else should appear on the same line as the preceding }') # If braces come on one side of an else, they should be on both. # However, we have to worry about "else if" that spans multiple lines! if Search(r'else if\s*\(', line): # could be multi-line if brace_on_left = bool(Search(r'}\s*else if\s*\(', line)) # find the ( after the if pos = line.find('else if') pos = line.find('(', pos) if pos > 0: (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) brace_on_right = endline[endpos:].find('{') != -1 if brace_on_left != brace_on_right: # must be brace after if error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): error(filename, linenum, 'readability/braces', 5, 'If an else has a brace on one side, it should have it on both') # Likewise, an else should never have the else clause on the same line if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): error(filename, linenum, 'whitespace/newline', 4, 'Else clause should never be on same line as else (use 2 lines)') # In the same way, a do/while should never be on one line if Match(r'\s*do [^\s{]', line): error(filename, linenum, 'whitespace/newline', 4, 'do/while clauses should not be on a single line') # Check single-line if/else bodies. The style guide says 'curly braces are not # required for single-line statements'. We additionally allow multi-line, # single statements, but we reject anything with more than one semicolon in # it. This means that the first semicolon after the if should be at the end of # its line, and the line after that should have an indent level equal to or # lower than the if. We also check for ambiguous if/else nesting without # braces. if_else_match = Search(r'\b(if\s*\(|else\b)', line) if if_else_match and not Match(r'\s*#', line): if_indent = GetIndentLevel(line) endline, endlinenum, endpos = line, linenum, if_else_match.end() if_match = Search(r'\bif\s*\(', line) if if_match: # This could be a multiline if condition, so find the end first. pos = if_match.end() - 1 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos) # Check for an opening brace, either directly after the if or on the next # line. If found, this isn't a single-statement conditional. if (not Match(r'\s*{', endline[endpos:]) and not (Match(r'\s*$', endline[endpos:]) and endlinenum < (len(clean_lines.elided) - 1) and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))): while (endlinenum < len(clean_lines.elided) and ';' not in clean_lines.elided[endlinenum][endpos:]): endlinenum += 1 endpos = 0 if endlinenum < len(clean_lines.elided): endline = clean_lines.elided[endlinenum] # We allow a mix of whitespace and closing braces (e.g. for one-liner # methods) and a single \ after the semicolon (for macros) endpos = endline.find(';') if not Match(r';[\s}]*(\\?)$', endline[endpos:]): # Semicolon isn't the last character, there's something trailing. # Output a warning if the semicolon is not contained inside # a lambda expression. if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$', endline): error(filename, linenum, 'readability/braces', 4, 'If/else bodies with multiple statements require braces') elif endlinenum < len(clean_lines.elided) - 1: # Make sure the next line is dedented next_line = clean_lines.elided[endlinenum + 1] next_indent = GetIndentLevel(next_line) # With ambiguous nested if statements, this will error out on the # if that *doesn't* match the else, regardless of whether it's the # inner one or outer one. if (if_match and Match(r'\s*else\b', next_line) and next_indent != if_indent): error(filename, linenum, 'readability/braces', 4, 'Else clause should be indented at the same level as if. ' 'Ambiguous nested if/else chains require braces.') elif next_indent > if_indent: error(filename, linenum, 'readability/braces', 4, 'If/else bodies with multiple statements require braces') def CheckTrailingSemicolon(filename, clean_lines, linenum, error): """Looks for redundant trailing semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Block bodies should not be followed by a semicolon. Due to C++11 # brace initialization, there are more places where semicolons are # required than not, so we use a whitelist approach to check these # rather than a blacklist. These are the places where "};" should # be replaced by just "}": # 1. Some flavor of block following closing parenthesis: # for (;;) {}; # while (...) {}; # switch (...) {}; # Function(...) {}; # if (...) {}; # if (...) else if (...) {}; # # 2. else block: # if (...) else {}; # # 3. const member function: # Function(...) const {}; # # 4. Block following some statement: # x = 42; # {}; # # 5. Block at the beginning of a function: # Function(...) { # {}; # } # # Note that naively checking for the preceding "{" will also match # braces inside multi-dimensional arrays, but this is fine since # that expression will not contain semicolons. # # 6. Block following another block: # while (true) {} # {}; # # 7. End of namespaces: # namespace {}; # # These semicolons seems far more common than other kinds of # redundant semicolons, possibly due to people converting classes # to namespaces. For now we do not warn for this case. # # Try matching case 1 first. match = Match(r'^(.*\)\s*)\{', line) if match: # Matched closing parenthesis (case 1). Check the token before the # matching opening parenthesis, and don't warn if it looks like a # macro. This avoids these false positives: # - macro that defines a base class # - multi-line macro that defines a base class # - macro that defines the whole class-head # # But we still issue warnings for macros that we know are safe to # warn, specifically: # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P # - TYPED_TEST # - INTERFACE_DEF # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: # # We implement a whitelist of safe macros instead of a blacklist of # unsafe macros, even though the latter appears less frequently in # google code and would have been easier to implement. This is because # the downside for getting the whitelist wrong means some extra # semicolons, while the downside for getting the blacklist wrong # would result in compile errors. # # In addition to macros, we also don't want to warn on # - Compound literals # - Lambdas # - alignas specifier with anonymous structs: closing_brace_pos = match.group(1).rfind(')') opening_parenthesis = ReverseCloseExpression( clean_lines, linenum, closing_brace_pos) if opening_parenthesis[2] > -1: line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] macro = Search(r'\b([A-Z_]+)\s*$', line_prefix) func = Match(r'^(.*\])\s*$', line_prefix) if ((macro and macro.group(1) not in ( 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or Search(r'\s+=\s*$', line_prefix)): match = None if (match and opening_parenthesis[1] > 1 and Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])): # Multi-line lambda-expression match = None else: # Try matching cases 2-3. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) if not match: # Try matching cases 4-6. These are always matched on separate lines. # # Note that we can't simply concatenate the previous line to the # current line and do a single match, otherwise we may output # duplicate warnings for the blank line case: # if (cond) { # // blank line # } prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] if prevline and Search(r'[;{}]\s*$', prevline): match = Match(r'^(\s*)\{', line) # Check matching closing brace if match: (endline, endlinenum, endpos) = CloseExpression( clean_lines, linenum, len(match.group(1))) if endpos > -1 and Match(r'^\s*;', endline[endpos:]): # Current {} pair is eligible for semicolon check, and we have found # the redundant semicolon, output warning here. # # Note: because we are scanning forward for opening braces, and # outputting warnings for the matching closing brace, if there are # nested blocks with trailing semicolons, we will get the error # messages in reversed order. error(filename, endlinenum, 'readability/braces', 4, "You don't need a ; after a }") def CheckEmptyBlockBody(filename, clean_lines, linenum, error): """Look for empty loop/conditional body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Search for loop keywords at the beginning of the line. Because only # whitespaces are allowed before the keywords, this will also ignore most # do-while-loops, since those lines should start with closing brace. # # We also check "if" blocks here, since an empty conditional block # is likely an error. line = clean_lines.elided[linenum] matched = Match(r'\s*(for|while|if)\s*\(', line) if matched: # Find the end of the conditional expression (end_line, end_linenum, end_pos) = CloseExpression( clean_lines, linenum, line.find('(')) # Output warning if what follows the condition expression is a semicolon. # No warning for all other cases, including whitespace or newline, since we # have a separate check for semicolons preceded by whitespace. if end_pos >= 0 and Match(r';', end_line[end_pos:]): if matched.group(1) == 'if': error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, 'Empty conditional bodies should use {}') else: error(filename, end_linenum, 'whitespace/empty_loop_body', 5, 'Empty loop bodies should use {} or continue') def FindCheckMacro(line): """Find a replaceable CHECK-like macro. Args: line: line to search on. Returns: (macro name, start position), or (None, -1) if no replaceable macro is found. """ for macro in _CHECK_MACROS: i = line.find(macro) if i >= 0: # Find opening parenthesis. Do a regular expression match here # to make sure that we are matching the expected CHECK macro, as # opposed to some other macro that happens to contain the CHECK # substring. matched = Match(r'^(.*\b' + macro + r'\s*)\(', line) if not matched: continue return (macro, len(matched.group(1))) return (None, -1) def CheckCheck(filename, clean_lines, linenum, error): """Checks the use of CHECK and EXPECT macros. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Decide the set of replacement macros that should be suggested lines = clean_lines.elided (check_macro, start_pos) = FindCheckMacro(lines[linenum]) if not check_macro: return # Find end of the boolean expression by matching parentheses (last_line, end_line, end_pos) = CloseExpression( clean_lines, linenum, start_pos) if end_pos < 0: return # If the check macro is followed by something other than a # semicolon, assume users will log their own custom error messages # and don't suggest any replacements. if not Match(r'\s*;', last_line[end_pos:]): return if linenum == end_line: expression = lines[linenum][start_pos + 1:end_pos - 1] else: expression = lines[linenum][start_pos + 1:] for i in xrange(linenum + 1, end_line): expression += lines[i] expression += last_line[0:end_pos - 1] # Parse expression so that we can take parentheses into account. # This avoids false positives for inputs like "CHECK((a < 4) == b)", # which is not replaceable by CHECK_LE. lhs = '' rhs = '' operator = None while expression: matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' r'==|!=|>=|>|<=|<|\()(.*)$', expression) if matched: token = matched.group(1) if token == '(': # Parenthesized operand expression = matched.group(2) (end, _) = FindEndOfExpressionInLine(expression, 0, ['(']) if end < 0: return # Unmatched parenthesis lhs += '(' + expression[0:end] expression = expression[end:] elif token in ('&&', '||'): # Logical and/or operators. This means the expression # contains more than one term, for example: # CHECK(42 < a && a < b); # # These are not replaceable with CHECK_LE, so bail out early. return elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): # Non-relational operator lhs += token expression = matched.group(2) else: # Relational operator operator = token rhs = matched.group(2) break else: # Unparenthesized operand. Instead of appending to lhs one character # at a time, we do another regular expression match to consume several # characters at once if possible. Trivial benchmark shows that this # is more efficient when the operands are longer than a single # character, which is generally the case. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) if not matched: matched = Match(r'^(\s*\S)(.*)$', expression) if not matched: break lhs += matched.group(1) expression = matched.group(2) # Only apply checks if we got all parts of the boolean expression if not (lhs and operator and rhs): return # Check that rhs do not contain logical operators. We already know # that lhs is fine since the loop above parses out && and ||. if rhs.find('&&') > -1 or rhs.find('||') > -1: return # At least one of the operands must be a constant literal. This is # to avoid suggesting replacements for unprintable things like # CHECK(variable != iterator) # # The following pattern matches decimal, hex integers, strings, and # characters (in that order). lhs = lhs.strip() rhs = rhs.strip() match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' if Match(match_constant, lhs) or Match(match_constant, rhs): # Note: since we know both lhs and rhs, we can provide a more # descriptive error message like: # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) # Instead of: # Consider using CHECK_EQ instead of CHECK(a == b) # # We are still keeping the less descriptive message because if lhs # or rhs gets long, the error message might become unreadable. error(filename, linenum, 'readability/check', 2, 'Consider using %s instead of %s(a %s b)' % ( _CHECK_REPLACEMENT[check_macro][operator], check_macro, operator)) def CheckAltTokens(filename, clean_lines, linenum, error): """Check alternative keywords being used in boolean expressions. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Avoid preprocessor lines if Match(r'^\s*#', line): return # Last ditch effort to avoid multi-line comments. This will not help # if the comment started before the current line or ended after the # current line, but it catches most of the false positives. At least, # it provides a way to workaround this warning for people who use # multi-line comments in preprocessor macros. # # TODO(unknown): remove this once cpplint has better support for # multi-line comments. if line.find('/*') >= 0 or line.find('*/') >= 0: return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, 'Use operator %s instead of %s' % ( _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) def GetLineWidth(line): """Determines the width of the line in column positions. Args: line: A string, which may be a Unicode string. Returns: The width of the line in column positions, accounting for Unicode combining characters and wide characters. """ if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width else: return len(line) def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error): """Checks rules from the 'C++ style rules' section of cppguide.html. Most of these rules are hard to test (naming, comment style), but we do what we can. In particular we check for 2-space indents, line lengths, tab usage, spaces inside code, etc. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Don't use "elided" lines here, otherwise we can't check commented lines. # Don't want to use "raw" either, because we don't want to check inside C++11 # raw strings, raw_lines = clean_lines.lines_without_raw_strings line = raw_lines[linenum] if line.find('\t') != -1: error(filename, linenum, 'whitespace/tab', 1, 'Tab found; better to use spaces') # One or three blank spaces at the beginning of the line is weird; it's # hard to reconcile that with 2-space indents. # NOTE: here are the conditions rob pike used for his tests. Mine aren't # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces # if(RLENGTH > 20) complain = 0; # if(match($0, " +(error|private|public|protected):")) complain = 0; # if(match(prev, "&& *$")) complain = 0; # if(match(prev, "\\|\\| *$")) complain = 0; # if(match(prev, "[\",=><] *$")) complain = 0; # if(match($0, " <<")) complain = 0; # if(match(prev, " +for \\(")) complain = 0; # if(prevodd && match(prevprev, " +for \\(")) complain = 0; scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$' classinfo = nesting_state.InnermostClass() initial_spaces = 0 cleansed_line = clean_lines.elided[linenum] while initial_spaces < len(line) and line[initial_spaces] == ' ': initial_spaces += 1 if line and line[-1].isspace(): error(filename, linenum, 'whitespace/end_of_line', 4, 'Line ends in whitespace. Consider deleting these extra spaces.') # There are certain situations we allow one space, notably for # section labels, and also lines containing multi-line raw strings. elif ((initial_spaces == 1 or initial_spaces == 3) and not Match(scope_or_label_pattern, cleansed_line) and not (clean_lines.raw_lines[linenum] != line and Match(r'^\s*""', line))): error(filename, linenum, 'whitespace/indent', 3, 'Weird number of spaces at line-start. ' 'Are you using a 2-space indent?') # Check if the line is a header guard. is_header_guard = False if file_extension == 'h': cppvar = GetHeaderGuardCPPVariable(filename) if (line.startswith('#ifndef %s' % cppvar) or line.startswith('#define %s' % cppvar) or line.startswith('#endif // %s' % cppvar)): is_header_guard = True # #include lines and header guards can be long, since there's no clean way to # split them. # # URLs can be long too. It's possible to split these, but it makes them # harder to cut&paste. # # The "$Id:...$" comment may also get very long without it being the # developers fault. if (not line.startswith('#include') and not is_header_guard and not Match(r'^\s*//.*http(s?)://\S*$', line) and not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): line_width = GetLineWidth(line) extended_length = int((_line_length * 1.25)) if line_width > extended_length: error(filename, linenum, 'whitespace/line_length', 4, 'Lines should very rarely be longer than %i characters' % extended_length) elif line_width > _line_length: error(filename, linenum, 'whitespace/line_length', 2, 'Lines should be <= %i characters long' % _line_length) if (cleansed_line.count(';') > 1 and # for loops are allowed two ;'s (and may run over two lines). cleansed_line.find('for') == -1 and (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and # It's ok to have many commands in a switch case that fits in 1 line not ((cleansed_line.find('case ') != -1 or cleansed_line.find('default:') != -1) and cleansed_line.find('break;') != -1)): error(filename, linenum, 'whitespace/newline', 0, 'More than one command on the same line') # Some more style checks CheckBraces(filename, clean_lines, linenum, error) CheckTrailingSemicolon(filename, clean_lines, linenum, error) CheckEmptyBlockBody(filename, clean_lines, linenum, error) CheckAccess(filename, clean_lines, linenum, nesting_state, error) CheckSpacing(filename, clean_lines, linenum, nesting_state, error) CheckOperatorSpacing(filename, clean_lines, linenum, error) CheckParenthesisSpacing(filename, clean_lines, linenum, error) CheckCommaSpacing(filename, clean_lines, linenum, error) CheckBracesSpacing(filename, clean_lines, linenum, error) CheckSpacingForFunctionCall(filename, clean_lines, linenum, error) CheckRValueReference(filename, clean_lines, linenum, nesting_state, error) CheckCheck(filename, clean_lines, linenum, error) CheckAltTokens(filename, clean_lines, linenum, error) classinfo = nesting_state.InnermostClass() if classinfo: CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') # Matches the first component of a filename delimited by -s and _s. That is: # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') def _DropCommonSuffixes(filename): """Drops common suffixes like _test.cc or -inl.h from filename. For example: >>> _DropCommonSuffixes('foo/foo-inl.h') 'foo/foo' >>> _DropCommonSuffixes('foo/bar/foo.cc') 'foo/bar/foo' >>> _DropCommonSuffixes('foo/foo_internal.h') 'foo/foo' >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') 'foo/foo_unusualinternal' Args: filename: The input filename. Returns: The filename with the common suffix removed. """ for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', 'inl.h', 'impl.h', 'internal.h'): if (filename.endswith(suffix) and len(filename) > len(suffix) and filename[-len(suffix) - 1] in ('-', '_')): return filename[:-len(suffix) - 1] return os.path.splitext(filename)[0] def _IsTestFilename(filename): """Determines if the given filename has a suffix that identifies it as a test. Args: filename: The input filename. Returns: True if 'filename' looks like a test, False otherwise. """ if (filename.endswith('_test.cc') or filename.endswith('_unittest.cc') or filename.endswith('_regtest.cc')): return True else: return False def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) _C_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) _CPP_SYS_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) _LIKELY_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), ... 'bar/foo_other_ext.h', False) _POSSIBLE_MY_HEADER >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) _OTHER_HEADER """ # This is a list of all standard c++ header files, except # those already checked for above. is_cpp_h = include in _CPP_HEADERS if is_system: if is_cpp_h: return _CPP_SYS_HEADER else: return _C_SYS_HEADER # If the target file and the include we're checking share a # basename when we drop common extensions, and the include # lives in . , then it's likely to be owned by the target file. target_dir, target_base = ( os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) if target_base == include_base and ( include_dir == target_dir or include_dir == os.path.normpath(target_dir + '/../public')): return _LIKELY_MY_HEADER # If the target and include share some initial basename # component, it's possible the target is implementing the # include, so it's allowed to be first, but we'll never # complain if it's not there. target_first_component = _RE_FIRST_COMPONENT.match(target_base) include_first_component = _RE_FIRST_COMPONENT.match(include_base) if (target_first_component and include_first_component and target_first_component.group(0) == include_first_component.group(0)): return _POSSIBLE_MY_HEADER return _OTHER_HEADER def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" # Only do this check if the included header follows google naming # conventions. If not, assume that it's a 3rd party API that # requires special include conventions. # # We also make an exception for Lua headers, which follow google # naming convention but not the include convention. match = Match(r'#include\s*"([^/]+\.h)"', line) if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)): error(filename, linenum, 'build/include', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') duplicate_line = include_state.FindHeader(include) if duplicate_line >= 0: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, duplicate_line)) elif (include.endswith('.cc') and os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)): error(filename, linenum, 'build/include', 4, 'Do not include .cc files from other packages') elif not _THIRD_PARTY_HEADERS_PATTERN.match(include): include_state.include_list[-1].append((include, linenum)) # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include) def _GetTextInside(text, start_pattern): r"""Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found. """ # TODO(unknown): Audit cpplint.py to see what places could be profitably # rewritten to use _GetTextInside (and use inferior regexp matching today). # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} closing_punctuation = set(matching_punctuation.itervalues()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) if not match: # start_pattern not found in text. return None start_position = match.end(0) assert start_position > 0, ( 'start_pattern must ends with an opening punctuation.') assert text[start_position - 1] in matching_punctuation, ( 'start_pattern must ends with an opening punctuation.') # Stack of closing punctuations we expect to have in text after position. punctuation_stack = [matching_punctuation[text[start_position - 1]]] position = start_position while punctuation_stack and position < len(text): if text[position] == punctuation_stack[-1]: punctuation_stack.pop() elif text[position] in closing_punctuation: # A closing punctuation without matching opening punctuations. return None elif text[position] in matching_punctuation: punctuation_stack.append(matching_punctuation[text[position]]) position += 1 if punctuation_stack: # Opening punctuations left without matching close-punctuations. return None # punctuations match. return text[start_position:position - 1] # Patterns for matching call-by-reference parameters. # # Supports nested templates up to 2 levels deep using this messy pattern: # < (?: < (?: < [^<>]* # > # | [^<>] )* # > # | [^<>] )* # > _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]* _RE_PATTERN_TYPE = ( r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?' r'(?:\w|' r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|' r'::)+') # A call-by-reference parameter ends with '& identifier'. _RE_PATTERN_REF_PARAM = re.compile( r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*' r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]') # A call-by-const-reference parameter either ends with 'const& identifier' # or looks like 'const type& identifier' when 'type' is atomic. _RE_PATTERN_CONST_REF_PARAM = ( r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT + r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')') def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, nesting_state, error): """Checks rules from the 'C++ language rules' section of cppguide.html. Some of these rules are hard to test (function overloading, using uint32 inappropriately), but we do the best we can. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. file_extension: The extension (without the dot) of the filename. include_state: An _IncludeState instance in which the headers are inserted. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # If the line is empty or consists of entirely a comment, no need to # check it. line = clean_lines.elided[linenum] if not line: return match = _RE_PATTERN_INCLUDE.search(line) if match: CheckIncludeLine(filename, clean_lines, linenum, include_state, error) return # Reset include state across preprocessor directives. This is meant # to silence warnings for conditional includes. match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) if match: include_state.ResetSection(match.group(1)) # Make Windows paths like Unix. fullname = os.path.abspath(filename).replace('\\', '/') # Perform other checks now that we are sure that this is not an include line CheckCasts(filename, clean_lines, linenum, error) CheckGlobalStatic(filename, clean_lines, linenum, error) CheckPrintf(filename, clean_lines, linenum, error) if file_extension == 'h': # TODO(unknown): check that 1-arg constructors are explicit. # How to tell it's a constructor? # (handled in CheckForNonStandardConstructs for now) # TODO(unknown): check that classes declare or disable copy/assign # (level 1 error) pass # Check if people are using the verboten C basic types. The only exception # we regularly allow is "unsigned short port" for port. if Search(r'\bshort port\b', line): if not Search(r'\bunsigned short port\b', line): error(filename, linenum, 'runtime/int', 4, 'Use "unsigned short" for ports, not "short"') else: match = Search(r'\b(short|long(?! +double)|long long)\b', line) if match: error(filename, linenum, 'runtime/int', 4, 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) # Check if some verboten operator overloading is going on # TODO(unknown): catch out-of-line unary operator&: # class X {}; # int operator&(const X& x) { return 42; } // unary operator& # The trick is it's hard to tell apart from binary operator&: # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& if Search(r'\boperator\s*&\s*\(\s*\)', line): error(filename, linenum, 'runtime/operator', 4, 'Unary operator& is dangerous. Do not use it.') # Check for suspicious usage of "if" like # } if (a == b) { if Search(r'\}\s*if\s*\(', line): error(filename, linenum, 'readability/braces', 4, 'Did you mean "else if"? If not, start a new line for "if".') # Check for potential format string bugs like printf(foo). # We constrain the pattern not to pick things like DocidForPrintf(foo). # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) # TODO(unknown): Catch the following case. Need to change the calling # convention of the whole function to process multiple line to handle it. # printf( # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') if printf_args: match = Match(r'([\w.\->()]+)$', printf_args) if match and match.group(1) != '__VA_ARGS__': function_name = re.search(r'\b((?:string)?printf)\s*\(', line, re.I).group(1) error(filename, linenum, 'runtime/printf', 4, 'Potential format string bug. Do %s("%%s", %s) instead.' % (function_name, match.group(1))) # Check for potential memset bugs like memset(buf, sizeof(buf), 0). match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): error(filename, linenum, 'runtime/memset', 4, 'Did you mean "memset(%s, 0, %s)"?' % (match.group(1), match.group(2))) if Search(r'\busing namespace\b', line): error(filename, linenum, 'build/namespaces', 5, 'Do not use namespace using-directives. ' 'Use using-declarations instead.') # Detect variable-length arrays. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) if (match and match.group(2) != 'return' and match.group(2) != 'delete' and match.group(3).find(']') == -1): # Split the size using space and arithmetic operators as delimiters. # If any of the resulting tokens are not compile time constants then # report the error. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) is_const = True skip_next = False for tok in tokens: if skip_next: skip_next = False continue if Search(r'sizeof\(.+\)', tok): continue if Search(r'arraysize\(\w+\)', tok): continue tok = tok.lstrip('(') tok = tok.rstrip(')') if not tok: continue if Match(r'\d+', tok): continue if Match(r'0[xX][0-9a-fA-F]+', tok): continue if Match(r'k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue # A catch all for tricky sizeof cases, including 'sizeof expression', # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' # requires skipping the next token because we split on ' ' and '*'. if tok.startswith('sizeof'): skip_next = True continue is_const = False break if not is_const: error(filename, linenum, 'runtime/arrays', 1, 'Do not use variable-length arrays. Use an appropriately named ' "('k' followed by CamelCase) compile-time constant for the size.") # Check for use of unnamed namespaces in header files. Registration # macros are typically OK, so we allow use of "namespace {" on lines # that end with backslashes. if (file_extension == 'h' and Search(r'\bnamespace\s*{', line) and line[-1] != '\\'): error(filename, linenum, 'build/namespaces', 4, 'Do not use unnamed namespaces in header files. See ' 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' ' for more information.') def CheckGlobalStatic(filename, clean_lines, linenum, error): """Check for unsafe global or static objects. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Match two lines at a time to support multiline declarations if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line): line += clean_lines.elided[linenum + 1].strip() # Check for people declaring static/global STL strings at the top level. # This is dangerous because the C++ language does not guarantee that # globals with constructors are initialized before the first access. match = Match( r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)', line) # Remove false positives: # - String pointers (as opposed to values). # string *pointer # const string *pointer # string const *pointer # string *const pointer # # - Functions and template specializations. # string Function<Type>(... # string Class<Type>::Method(... # # - Operators. These are matched separately because operator names # cross non-word boundaries, and trying to match both operators # and functions at the same time would decrease accuracy of # matching identifiers. # string Class::operator*() if (match and not Search(r'\bstring\b(\s+const)?\s*\*\s*(const\s+)?\w', line) and not Search(r'\boperator\W', line) and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(3))): error(filename, linenum, 'runtime/string', 4, 'For a static/global string constant, use a C style string instead: ' '"%schar %s[]".' % (match.group(1), match.group(2))) if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line): error(filename, linenum, 'runtime/init', 4, 'You seem to be initializing a member variable with itself.') def CheckPrintf(filename, clean_lines, linenum, error): """Check for printf related issues. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # When snprintf is used, the second argument shouldn't be a literal. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) if match and match.group(2) != '0': # If 2nd arg is zero, snprintf is used to calculate size. error(filename, linenum, 'runtime/printf', 3, 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' 'to snprintf.' % (match.group(1), match.group(2))) # Check if some verboten C functions are being used. if Search(r'\bsprintf\s*\(', line): error(filename, linenum, 'runtime/printf', 5, 'Never use sprintf. Use snprintf instead.') match = Search(r'\b(strcpy|strcat)\s*\(', line) if match: error(filename, linenum, 'runtime/printf', 4, 'Almost always, snprintf is better than %s' % match.group(1)) def IsDerivedFunction(clean_lines, linenum): """Check if current line contains an inherited function. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line contains a function with "override" virt-specifier. """ # Scan back a few lines for start of current function for i in xrange(linenum, max(-1, linenum - 10), -1): match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i]) if match: # Look for "override" after the matching closing parenthesis line, _, closing_paren = CloseExpression( clean_lines, i, len(match.group(1))) return (closing_paren >= 0 and Search(r'\boverride\b', line[closing_paren:])) return False def IsOutOfLineMethodDefinition(clean_lines, linenum): """Check if current line contains an out-of-line method definition. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line contains an out-of-line method definition. """ # Scan back a few lines for start of current function for i in xrange(linenum, max(-1, linenum - 10), -1): if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]): return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None return False def IsInitializerList(clean_lines, linenum): """Check if current line is inside constructor initializer list. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if current line appears to be inside constructor initializer list, False otherwise. """ for i in xrange(linenum, 1, -1): line = clean_lines.elided[i] if i == linenum: remove_function_body = Match(r'^(.*)\{\s*$', line) if remove_function_body: line = remove_function_body.group(1) if Search(r'\s:\s*\w+[({]', line): # A lone colon tend to indicate the start of a constructor # initializer list. It could also be a ternary operator, which # also tend to appear in constructor initializer lists as # opposed to parameter lists. return True if Search(r'\}\s*,\s*$', line): # A closing brace followed by a comma is probably the end of a # brace-initialized member in constructor initializer list. return True if Search(r'[{};]\s*$', line): # Found one of the following: # - A closing brace or semicolon, probably the end of the previous # function. # - An opening brace, probably the start of current class or namespace. # # Current line is probably not inside an initializer list since # we saw one of those things without seeing the starting colon. return False # Got to the beginning of the file without seeing the start of # constructor initializer list. return False def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error): """Check for non-const references. Separate from CheckLanguage since it scans backwards from current line, instead of scanning forward. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: The function to call with any errors found. """ # Do nothing if there is no '&' on current line. line = clean_lines.elided[linenum] if '&' not in line: return # If a function is inherited, current function doesn't have much of # a choice, so any non-const references should not be blamed on # derived function. if IsDerivedFunction(clean_lines, linenum): return # Don't warn on out-of-line method definitions, as we would warn on the # in-line declaration, if it isn't marked with 'override'. if IsOutOfLineMethodDefinition(clean_lines, linenum): return # Long type names may be broken across multiple lines, usually in one # of these forms: # LongType # ::LongTypeContinued &identifier # LongType:: # LongTypeContinued &identifier # LongType< # ...>::LongTypeContinued &identifier # # If we detected a type split across two lines, join the previous # line to current line so that we can match const references # accordingly. # # Note that this only scans back one line, since scanning back # arbitrary number of lines would be expensive. If you have a type # that spans more than 2 lines, please use a typedef. if linenum > 1: previous = None if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): # previous_line\n + ::current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', clean_lines.elided[linenum - 1]) elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): # previous_line::\n + current_line previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', clean_lines.elided[linenum - 1]) if previous: line = previous.group(1) + line.lstrip() else: # Check for templated parameter that is split across multiple lines endpos = line.rfind('>') if endpos > -1: (_, startline, startpos) = ReverseCloseExpression( clean_lines, linenum, endpos) if startpos > -1 and startline < linenum: # Found the matching < on an earlier line, collect all # pieces up to current line. line = '' for i in xrange(startline, linenum + 1): line += clean_lines.elided[i].strip() # Check for non-const references in function parameters. A single '&' may # found in the following places: # inside expression: binary & for bitwise AND # inside expression: unary & for taking the address of something # inside declarators: reference parameter # We will exclude the first two cases by checking that we are not inside a # function body, including one that was just introduced by a trailing '{'. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. if (nesting_state.previous_stack_top and not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): # Not at toplevel, not within a class, and not within a namespace return # Avoid initializer lists. We only need to scan back from the # current line for something that starts with ':'. # # We don't need to check the current line, since the '&' would # appear inside the second set of parentheses on the current line as # opposed to the first set. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 10), -1): previous_line = clean_lines.elided[i] if not Search(r'[),]\s*$', previous_line): break if Match(r'^\s*:\s+\S', previous_line): return # Avoid preprocessors if Search(r'\\\s*$', line): return # Avoid constructor initializer lists if IsInitializerList(clean_lines, linenum): return # We allow non-const references in a few standard places, like functions # called "swap()" or iostream operators like "<<" or ">>". Do not check # those function parameters. # # We also accept & in static_assert, which looks like a function but # it's actually a declaration expression. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' r'operator\s*[<>][<>]|' r'static_assert|COMPILE_ASSERT' r')\s*\(') if Search(whitelisted_functions, line): return elif not Search(r'\S+\([^)]*$', line): # Don't see a whitelisted function on this line. Actually we # didn't see any function name on this line, so this is likely a # multi-line parameter list. Try a bit harder to catch this case. for i in xrange(2): if (linenum > i and Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): return decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter): error(filename, linenum, 'runtime/references', 2, 'Is this a non-const reference? ' 'If so, make const or use a pointer: ' + ReplaceAll(' *<', '<', parameter)) def CheckCasts(filename, clean_lines, linenum, error): """Various cast related checks. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Check to see if they're using an conversion function cast. # I just try to capture the most common basic types, though there are more. # Parameterless conversion functions, such as bool(), are allowed as they are # probably a member operator declaration or default constructor. match = Search( r'(\bnew\s+|\S<\s*(?:const\s+)?)?\b' r'(int|float|double|bool|char|int32|uint32|int64|uint64)' r'(\([^)].*)', line) expecting_function = ExpectingFunctionArgs(clean_lines, linenum) if match and not expecting_function: matched_type = match.group(2) # matched_new_or_template is used to silence two false positives: # - New operators # - Template arguments with function types # # For template arguments, we match on types immediately following # an opening bracket without any spaces. This is a fast way to # silence the common case where the function type is the first # template argument. False negative with less-than comparison is # avoided because those operators are usually followed by a space. # # function<double(double)> // bracket + no space = false positive # value < double(42) // bracket + space = true positive matched_new_or_template = match.group(1) # Avoid arrays by looking for brackets that come after the closing # parenthesis. if Match(r'\([^()]+\)\s*\[', match.group(3)): return # Other things to ignore: # - Function pointers # - Casts to pointer types # - Placement new # - Alias declarations matched_funcptr = match.group(3) if (matched_new_or_template is None and not (matched_funcptr and (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', matched_funcptr) or matched_funcptr.startswith('(*)'))) and not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and not Search(r'new\(\S+\)\s*' + matched_type, line)): error(filename, linenum, 'readability/casting', 4, 'Using deprecated casting style. ' 'Use static_cast<%s>(...) instead' % matched_type) if not expecting_function: CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) # This doesn't catch all cases. Consider (const char * const)"hello". # # (char *) "foo" should always be a const_cast (reinterpret_cast won't # compile). if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): pass else: # Check pointer casts for other than string constants CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) # In addition, we look for people taking the address of a cast. This # is dangerous -- casts can assign to temporaries, so the pointer doesn't # point where you think. # # Some non-identifier character is required before the '&' for the # expression to be recognized as a cast. These are casts: # expression = &static_cast<int*>(temporary()); # function(&(int*)(temporary())); # # This is not a cast: # reference_type&(int* function_param); match = Search( r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) if match: # Try a better error message when the & is bound to something # dereferenced by the casted pointer, as opposed to the casted # pointer itself. parenthesis_error = False match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) if match: _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) if x1 >= 0 and clean_lines.elided[y1][x1] == '(': _, y2, x2 = CloseExpression(clean_lines, y1, x1) if x2 >= 0: extended_line = clean_lines.elided[y2][x2:] if y2 < clean_lines.NumLines() - 1: extended_line += clean_lines.elided[y2 + 1] if Match(r'\s*(?:->|\[)', extended_line): parenthesis_error = True if parenthesis_error: error(filename, linenum, 'readability/casting', 4, ('Are you taking an address of something dereferenced ' 'from a cast? Wrapping the dereferenced expression in ' 'parentheses will make the binding more obvious')) else: error(filename, linenum, 'runtime/casting', 4, ('Are you taking an address of a cast? ' 'This is dangerous: could be a temp var. ' 'Take the address before doing the cast, rather than after')) def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): """Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reinterpret_cast, static_cast, or const_cast, depending. pattern: The regular expression used to find C-style casts. error: The function to call with any errors found. Returns: True if an error was emitted. False otherwise. """ line = clean_lines.elided[linenum] match = Search(pattern, line) if not match: return False # Exclude lines with keywords that tend to look like casts context = line[0:match.start(1) - 1] if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): return False # Try expanding current context to see if we one level of # parentheses inside a macro. if linenum > 0: for i in xrange(linenum - 1, max(0, linenum - 5), -1): context = clean_lines.elided[i] + context if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): return False # operator++(int) and operator--(int) if context.endswith(' operator++') or context.endswith(' operator--'): return False # A single unnamed argument for a function tends to look like old # style cast. If we see those, don't issue warnings for deprecated # casts, instead issue warnings for unnamed arguments where # appropriate. # # These are things that we want warnings for, since the style guide # explicitly require all parameters to be named: # Function(int); # Function(int) { # ConstMember(int) const; # ConstMember(int) const { # ExceptionMember(int) throw (...); # ExceptionMember(int) throw (...) { # PureVirtual(int) = 0; # [](int) -> bool { # # These are functions of some sort, where the compiler would be fine # if they had named parameters, but people often omit those # identifiers to reduce clutter: # (FunctionPointer)(int); # (FunctionPointer)(int) = value; # Function((function_pointer_arg)(int)) # Function((function_pointer_arg)(int), int param) # <TemplateArgument(int)>; # <(FunctionPointerTemplateArgument)(int)>; remainder = line[match.end(0):] if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', remainder): # Looks like an unnamed parameter. # Don't warn on any kind of template arguments. if Match(r'^\s*>', remainder): return False # Don't warn on assignments to function pointers, but keep warnings for # unnamed parameters to pure virtual functions. Note that this pattern # will also pass on assignments of "0" to function pointers, but the # preferred values for those would be "nullptr" or "NULL". matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder) if matched_zero and matched_zero.group(1) != '0': return False # Don't warn on function pointer declarations. For this we need # to check what came before the "(type)" string. if Match(r'.*\)\s*$', line[0:match.start(0)]): return False # Don't warn if the parameter is named with block comments, e.g.: # Function(int /*unused_param*/); raw_line = clean_lines.raw_lines[linenum] if '/*' in raw_line: return False # Passed all filters, issue warning here. error(filename, linenum, 'readability/function', 3, 'All parameters should be named in a function') return True # At this point, all that should be left is actual casts. error(filename, linenum, 'readability/casting', 4, 'Using C-style cast. Use %s<%s>(...) instead' % (cast_type, match.group(1))) return True def ExpectingFunctionArgs(clean_lines, linenum): """Checks whether where function type arguments are expected. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. Returns: True if the line at 'linenum' is inside something that expects arguments of function types. """ line = clean_lines.elided[linenum] return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or (linenum >= 2 and (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', clean_lines.elided[linenum - 1]) or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', clean_lines.elided[linenum - 2]) or Search(r'\bstd::m?function\s*\<\s*$', clean_lines.elided[linenum - 1])))) _HEADERS_CONTAINING_TEMPLATES = ( ('<deque>', ('deque',)), ('<functional>', ('unary_function', 'binary_function', 'plus', 'minus', 'multiplies', 'divides', 'modulus', 'negate', 'equal_to', 'not_equal_to', 'greater', 'less', 'greater_equal', 'less_equal', 'logical_and', 'logical_or', 'logical_not', 'unary_negate', 'not1', 'binary_negate', 'not2', 'bind1st', 'bind2nd', 'pointer_to_unary_function', 'pointer_to_binary_function', 'ptr_fun', 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', 'mem_fun_ref_t', 'const_mem_fun_t', 'const_mem_fun1_t', 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', 'mem_fun_ref', )), ('<limits>', ('numeric_limits',)), ('<list>', ('list',)), ('<map>', ('map', 'multimap',)), ('<memory>', ('allocator',)), ('<queue>', ('queue', 'priority_queue',)), ('<set>', ('set', 'multiset',)), ('<stack>', ('stack',)), ('<string>', ('char_traits', 'basic_string',)), ('<tuple>', ('tuple',)), ('<utility>', ('pair',)), ('<vector>', ('vector',)), # gcc extensions. # Note: std::hash is their hash, ::hash is our hash ('<hash_map>', ('hash_map', 'hash_multimap',)), ('<hash_set>', ('hash_set', 'hash_multiset',)), ('<slist>', ('slist',)), ) _RE_PATTERN_STRING = re.compile(r'\bstring\b') _re_pattern_algorithm_header = [] for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap', 'transform'): # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or # type::max(). _re_pattern_algorithm_header.append( (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), _template, '<algorithm>')) _re_pattern_templates = [] for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: for _template in _templates: _re_pattern_templates.append( (re.compile(r'(\<|\b)' + _template + r'\s*\<'), _template + '<>', _header)) def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the .cc file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ if not filename_cc.endswith('.cc'): return (False, '') filename_cc = filename_cc[:-len('.cc')] if filename_cc.endswith('_unittest'): filename_cc = filename_cc[:-len('_unittest')] elif filename_cc.endswith('_test'): filename_cc = filename_cc[:-len('_test')] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') if not filename_h.endswith('.h'): return (False, '') filename_h = filename_h[:-len('.h')] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path def UpdateIncludeState(filename, include_dict, io=codecs): """Fill up the include_dict with new includes found from the file. Args: filename: the name of the header to read. include_dict: a dictionary in which the headers are inserted. io: The io factory to use to read the file. Provided for testability. Returns: True if a header was successfully added. False otherwise. """ headerfile = None try: headerfile = io.open(filename, 'r', 'utf8', 'replace') except IOError: return False linenum = 0 for line in headerfile: linenum += 1 clean_line = CleanseComments(line) match = _RE_PATTERN_INCLUDE.search(clean_line) if match: include = match.group(2) include_dict.setdefault(include, linenum) return True def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's flatten the include_state include_list and copy it into a dictionary. include_dict = dict([item for sublist in include_state.include_list for item in sublist]) # Did we find the header for this file (if any) and successfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_dict is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_dict.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_dict, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_dict: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template) _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): """Check that make_pair's template arguments are deduced. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are specified explicitly, and such use isn't intended in any case. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) if match: error(filename, linenum, 'build/explicit_make_pair', 4, # 4 = high confidence 'For C++11-compatibility, omit template arguments from make_pair' ' OR use pair directly OR if appropriate, construct a pair directly') def CheckDefaultLambdaCaptures(filename, clean_lines, linenum, error): """Check that default lambda captures are not used. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # A lambda introducer specifies a default capture if it starts with "[=" # or if it starts with "[&" _not_ followed by an identifier. match = Match(r'^(.*)\[\s*(?:=|&[^\w])', line) if match: # Found a potential error, check what comes after the lambda-introducer. # If it's not open parenthesis (for lambda-declarator) or open brace # (for compound-statement), it's not a lambda. line, _, pos = CloseExpression(clean_lines, linenum, len(match.group(1))) if pos >= 0 and Match(r'^\s*[{(]', line[pos:]): error(filename, linenum, 'build/c++11', 4, # 4 = high confidence 'Default lambda captures are an unapproved C++ feature.') def CheckRedundantVirtual(filename, clean_lines, linenum, error): """Check if line contains a redundant "virtual" function-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Look for "virtual" on current line. line = clean_lines.elided[linenum] virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line) if not virtual: return # Ignore "virtual" keywords that are near access-specifiers. These # are only used in class base-specifier and do not apply to member # functions. if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or Match(r'^\s+(public|protected|private)\b', virtual.group(3))): return # Ignore the "virtual" keyword from virtual base classes. Usually # there is a column on the same line in these cases (virtual base # classes are rare in google3 because multiple inheritance is rare). if Match(r'^.*[^:]:[^:].*$', line): return # Look for the next opening parenthesis. This is the start of the # parameter list (possibly on the next line shortly after virtual). # TODO(unknown): doesn't work if there are virtual functions with # decltype() or other things that use parentheses, but csearch suggests # that this is rare. end_col = -1 end_line = -1 start_col = len(virtual.group(2)) for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): line = clean_lines.elided[start_line][start_col:] parameter_list = Match(r'^([^(]*)\(', line) if parameter_list: # Match parentheses to find the end of the parameter list (_, end_line, end_col) = CloseExpression( clean_lines, start_line, start_col + len(parameter_list.group(1))) break start_col = 0 if end_col < 0: return # Couldn't find end of parameter list, give up # Look for "override" or "final" after the parameter list # (possibly on the next few lines). for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): line = clean_lines.elided[i][end_col:] match = Search(r'\b(override|final)\b', line) if match: error(filename, linenum, 'readability/inheritance', 4, ('"virtual" is redundant since function is ' 'already declared as "%s"' % match.group(1))) # Set end_col to check whole lines after we are done with the # first line. end_col = 0 if Search(r'[^\w]\s*$', line): break def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): """Check if line contains a redundant "override" or "final" virt-specifier. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Look for closing parenthesis nearby. We need one to confirm where # the declarator ends and where the virt-specifier starts to avoid # false positives. line = clean_lines.elided[linenum] declarator_end = line.rfind(')') if declarator_end >= 0: fragment = line[declarator_end:] else: if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0: fragment = line else: return # Check that at most one of "override" or "final" is present, not both if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment): error(filename, linenum, 'readability/inheritance', 4, ('"override" is redundant since function is ' 'already declared as "final"')) # Returns true if we are at a new block, and it is directly # inside of a namespace. def IsBlockInNameSpace(nesting_state, is_forward_declaration): """Checks that the new block is directly in a namespace. Args: nesting_state: The _NestingState object that contains info about our state. is_forward_declaration: If the class is a forward declared class. Returns: Whether or not the new block is directly in a namespace. """ if is_forward_declaration: if len(nesting_state.stack) >= 1 and ( isinstance(nesting_state.stack[-1], _NamespaceInfo)): return True else: return False return (len(nesting_state.stack) > 1 and nesting_state.stack[-1].check_namespace_indentation and isinstance(nesting_state.stack[-2], _NamespaceInfo)) def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, raw_lines_no_comments, linenum): """This method determines if we should apply our namespace indentation check. Args: nesting_state: The current nesting state. is_namespace_indent_item: If we just put a new class on the stack, True. If the top of the stack is not a class, or we did not recently add the class, False. raw_lines_no_comments: The lines without the comments. linenum: The current line number we are processing. Returns: True if we should apply our namespace indentation check. Currently, it only works for classes and namespaces inside of a namespace. """ is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, linenum) if not (is_namespace_indent_item or is_forward_declaration): return False # If we are in a macro, we do not want to check the namespace indentation. if IsMacroDefinition(raw_lines_no_comments, linenum): return False return IsBlockInNameSpace(nesting_state, is_forward_declaration) # Call this method if the line is directly inside of a namespace. # If the line above is blank (excluding comments) or the start of # an inner namespace, it cannot be indented. def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, error): line = raw_lines_no_comments[linenum] if Match(r'^\s+', line): error(filename, linenum, 'runtime/indentation_namespace', 4, 'Do not indent within a namespace') def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error) if nesting_state.InAsmBlock(): return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) CheckDefaultLambdaCaptures(filename, clean_lines, line, error) CheckRedundantVirtual(filename, clean_lines, line, error) CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error) def FlagCxx11Features(filename, clean_lines, linenum, error): """Flag those c++11 features that we only allow in certain places. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Flag unapproved C++11 headers. include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) if include and include.group(1) in ('cfenv', 'condition_variable', 'fenv.h', 'future', 'mutex', 'thread', 'chrono', 'ratio', 'regex', 'system_error', ): error(filename, linenum, 'build/c++11', 5, ('<%s> is an unapproved C++11 header.') % include.group(1)) # The only place where we need to worry about C++11 keywords and library # features in preprocessor directives is in macro definitions. if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return # These are classes and free functions. The classes are always # mentioned as std::*, but we only catch the free functions if # they're not found by ADL. They're alphabetical by header. for top_name in ( # type_traits 'alignment_of', 'aligned_union', ): if Search(r'\bstd::%s\b' % top_name, line): error(filename, linenum, 'build/c++11', 5, ('std::%s is an unapproved C++11 class or function. Send c-style ' 'an example of where it would make your code more readable, and ' 'they may let you use it.') % top_name) def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=[]): """Performs lint checks and reports any errors to the given error function. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. lines: An array of strings, each representing a line of the file, with the last element being empty if the file is terminated with a newline. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ lines = (['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way']) include_state = _IncludeState() function_state = _FunctionState() nesting_state = NestingState() ResetNolintSuppressions() CheckForCopyright(filename, lines, error) RemoveMultiLineComments(filename, lines, error) clean_lines = CleansedLines(lines) if file_extension == 'h': CheckForHeaderGuard(filename, clean_lines, error) for line in xrange(clean_lines.NumLines()): ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions) FlagCxx11Features(filename, clean_lines, line, error) nesting_state.CheckCompletedBlocks(filename, error) CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) # Check that the .cc file has included its header if it exists. if file_extension == 'cc': CheckHeaderFileIncluded(filename, include_state, error) # We check here rather than inside ProcessLine so that we see raw # lines rather than "cleaned" lines. CheckForBadCharacters(filename, lines, error) CheckForNewlineAtEOF(filename, lines, error) def ProcessConfigOverrides(filename): """ Loads the configuration files and processes the config overrides. Args: filename: The name of the file being processed by the linter. Returns: False if the current |filename| should not be processed further. """ abs_filename = os.path.abspath(filename) cfg_filters = [] keep_looking = True while keep_looking: abs_path, base_name = os.path.split(abs_filename) if not base_name: break # Reached the root directory. cfg_file = os.path.join(abs_path, "CPPLINT.cfg") abs_filename = abs_path if not os.path.isfile(cfg_file): continue try: with open(cfg_file) as file_handle: for line in file_handle: line, _, _ = line.partition('#') # Remove comments. if not line.strip(): continue name, _, val = line.partition('=') name = name.strip() val = val.strip() if name == 'set noparent': keep_looking = False elif name == 'filter': cfg_filters.append(val) elif name == 'exclude_files': # When matching exclude_files pattern, use the base_name of # the current file name or the directory name we are processing. # For example, if we are checking for lint errors in /foo/bar/baz.cc # and we found the .cfg file at /foo/CPPLINT.cfg, then the config # file's "exclude_files" filter is meant to be checked against "bar" # and not "baz" nor "bar/baz.cc". if base_name: pattern = re.compile(val) if pattern.match(base_name): sys.stderr.write('Ignoring "%s": file excluded by "%s". ' 'File path component "%s" matches ' 'pattern "%s"\n' % (filename, cfg_file, base_name, val)) return False elif name == 'linelength': global _line_length try: _line_length = int(val) except ValueError: sys.stderr.write('Line length must be numeric.') else: sys.stderr.write( 'Invalid configuration option (%s) in file %s\n' % (name, cfg_file)) except IOError: sys.stderr.write( "Skipping config file '%s': Can't open for reading\n" % cfg_file) keep_looking = False # Apply all the accumulated filters in reverse order (top-level directory # config options having the least priority). for filter in reversed(cfg_filters): _AddFilters(filter) return True def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) _BackupFilters() if not ProcessConfigOverrides(filename): _RestoreFilters() return lf_lines = [] crlf_lines = [] try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') # Remove trailing '\r'. # The -1 accounts for the extra trailing blank line we get from split() for linenum in range(len(lines) - 1): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') crlf_lines.append(linenum + 1) else: lf_lines.append(linenum + 1) except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) _RestoreFilters() return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in _valid_extensions: sys.stderr.write('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(_valid_extensions))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) # If end-of-line sequences are a mix of LF and CR-LF, issue # warnings on the lines with CR. # # Don't issue any warnings if all lines are uniformly LF or CR-LF, # since critique can handle these just fine, and the style guide # doesn't dictate a particular end of line sequence. # # We can't depend on os.linesep to determine what the desired # end-of-line sequence should be, since that will return the # server-side end-of-line sequence. if lf_lines and crlf_lines: # Warn on every line with CR. An alternative approach might be to # check whether the file is mostly CRLF or just LF, and warn on the # minority, we bias toward LF here since most tools prefer LF. for linenum in crlf_lines: Error(filename, linenum, 'whitespace/newline', 1, 'Unexpected \\r (^M) found; better to use only \\n') sys.stderr.write('Done processing %s\n' % filename) _RestoreFilters() def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1) def PrintCategories(): """Prints a list of all the error-categories used by error messages. These are the categories used to filter messages via --filter. """ sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) sys.exit(0) def ParseArguments(args): """Parses the command line arguments. This may set the output format and verbosity level as side-effects. Args: args: The command line arguments: Returns: The list of filenames to lint. """ try: (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', 'counting=', 'filter=', 'root=', 'linelength=', 'extensions=']) except getopt.GetoptError: PrintUsage('Invalid arguments.') verbosity = _VerboseLevel() output_format = _OutputFormat() filters = '' counting_style = '' for (opt, val) in opts: if opt == '--help': PrintUsage(None) elif opt == '--output': if val not in ('emacs', 'vs7', 'eclipse'): PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') output_format = val elif opt == '--verbose': verbosity = int(val) elif opt == '--filter': filters = val if not filters: PrintCategories() elif opt == '--counting': if val not in ('total', 'toplevel', 'detailed'): PrintUsage('Valid counting options are total, toplevel, and detailed') counting_style = val elif opt == '--root': global _root _root = val elif opt == '--linelength': global _line_length try: _line_length = int(val) except ValueError: PrintUsage('Line length must be digits.') elif opt == '--extensions': global _valid_extensions try: _valid_extensions = set(val.split(',')) except ValueError: PrintUsage('Extensions must be comma seperated list.') if not filenames: PrintUsage('No files were specified.') _SetOutputFormat(output_format) _SetVerboseLevel(verbosity) _SetFilters(filters) _SetCountingStyle(counting_style) return filenames def main(): filenames = ParseArguments(sys.argv[1:]) # Change stderr to write with replacement characters so we don't die # if we try to print something containing non-ASCII characters. sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') _cpplint_state.ResetErrorCounts() for filename in filenames: ProcessFile(filename, _cpplint_state.verbose_level) _cpplint_state.PrintErrorCounts() sys.exit(_cpplint_state.error_count > 0) if __name__ == '__main__': main()
bsd-3-clause
-4,940,472,272,440,915,000
37.256524
97
0.639118
false
kdahlhaus/manifest_generator
manifestgen/tests/test_convert_filenames_to_urls.py
1
1097
from manifestgen.app import convert_filenames_to_urls import unittest class TestConvertFilenamesToUrls(unittest.TestCase): def test_cannonical(self): result = convert_filenames_to_urls( [ '/usr/proj/index.html', '/usr/proj/js/util.js'], '/usr/proj', '/sample/static' ) self.assertEqual( result, [ '/sample/static/index.html', '/sample/static/js/util.js' ]) def test_no_url_prefix(self): result = convert_filenames_to_urls( [ '/usr/proj/index.html', '/usr/proj/js/util.js'], '/usr/proj') self.assertEqual( result, [ '/index.html', '/js/util.js' ]) def test_no_docroot(self): result = convert_filenames_to_urls( [ '/usr/proj/index.html', '/usr/proj/js/util.js'], url_prefix='/sample/static') self.assertEqual( result, [ '/sample/static/usr/proj/index.html', '/sample/static/usr/proj/js/util.js' ]) def test_no_docroot_no_url_prefix(self): result = convert_filenames_to_urls( [ '/usr/proj/index.html', '/usr/proj/js/util.js']) self.assertEqual( result, [ '/usr/proj/index.html', '/usr/proj/js/util.js' ])
gpl-3.0
-1,644,735,595,482,262,000
44.708333
126
0.649043
false
achawkins/Forsteri
forsteri/interface/sql.py
1
33446
""" SQLite Database Interface for Information Copyright (c) 2014, 2015 Andrew Hawkins 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 Declarations """ import datetime as dt import os import re import sqlite3 import sys from forsteri.interface import data as idata """ Constant Declarations """ if os.name == "nt": DATA = "J:\\" elif os.name == "posix": DATA = "/mnt/forecastdb/" MASTER = ''.join([DATA, "master.db"]) """ Product Information """ def getAttribute(attribute, connection=None): """ Get all values for a single attribute. Args: attribute (str): The attribute to pull from the database. connection (sqlite3.Connection, optional): A connection to the database. Returns: list of str: The attributes across all tuples. """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to retrieve all items under attribute. cursor.execute("""SELECT {a} FROM information;""".format(a=attribute)) # Fetch all rows. products = cursor.fetchall() # Close the cursor. cursor.close() # Close the connection. if flag: connection.close() return products def getAllData(connection=None): """ Get all data from the database. Args: connection (sqlite3.Connection, optional): A connection to the database. Returns: list of list of str: The data for all tuples and attributes. """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to retrieve all data. cursor.execute("""SELECT product, sku, account, class, category, subcategory FROM information;""") # Fetch all rows. productData = cursor.fetchall() # Convert all None values to be empty strings. productData = ['' if attribute is None else attribute for product in\ productData for attribute in product] productData = [productData[z : z + 6] for z in range(0, len(productData), 6)] # Close the cursor. cursor.close() # Close the connection. if flag: connection.close() return productData def getData(sieve, connection=None): """ Get the data after filtering with a sieve. Args: sieve (dict of str: str): connection (sqlite3.Connection, optional): Returns: list of list of str: The data for tuples and attributes satifying the filter. """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Define the sieve string. sieveStr = '' for (key, value) in sieve.items(): if value != '' and value is not None: if key == "product" or key == "sku": sieveStr = ''.join([sieveStr, " AND ", key, " LIKE '", value, "%'"]) else: sieveStr = ''.join([sieveStr, " AND ", key, "='", value, "'"]) # If the string is length zero, no sieve was input. if len(sieveStr) == 0: # Execute the statement to retrieve all data. cursor.execute("""SELECT product, sku, account, class, category, subcategory FROM information;""") else: # Cut the beginning of the string. sieveStr = sieveStr[5:] # Execute the statement to retrieve the sieve's information. cursor.execute("""SELECT product, sku, account, class, category, subcategory FROM information WHERE {s};""".format(s=sieveStr)) # Fetch all rows. productData = cursor.fetchall() # Convert all None values to be empty strings. productData = ['' if attr is None else attr for product in productData for\ attr in product] productData = [productData[z : z + 6] for z in range(0, len(productData), 6)] # Close the cursor. cursor.close() # Close the connection. if flag: connection.close() return productData def getProduct(product, connection=None): """ Get the data for a single product. Args: product (str): The name of the product. connection (sqlite3.Connection, optional): A connection to the database. Returns: list of str: The data for a single tuple. """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to retrieve the product's information. cursor.execute("""SELECT product, sku, account, class, category, subcategory FROM information WHERE product='{p}';""".format(p=product)) # Fetch the first responded row. productData = cursor.fetchone() # Change None to be an empty string. productData = ['' if attr is None else attr for attr in productData] # Close the cursor. cursor.close() # Close the connection. if flag: connection.close() return productData def addProduct(productData, connection=None): """ Add a product tuple to the database. Args: productData (dict of {str: str}): A tuple to add to the database. Must be of the form {"product": ?, "sku": ?, "account": ?, "class": ?, "category": ?, "subcategory": ?}. connection (sqlite3.Connection, optional): A connection to the database. Returns: bool: True if successful, false otherwise. """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Check if the product has been input or if it has already been added. if "product" not in productData.keys(): return False # Initlialize the attribute and value lists. attrs = [] values = [] # Iterate over the inputted values and extract attributes. for (key, value) in productData.items(): if value is None or value == '': continue else: attrs.append(key) values.append(value) # Convert to a valid string removing unnecessary characters. if len(attrs) == 1: attrs = re.sub("[',]", '', str(tuple(attrs))) values = re.sub(",", '', str(tuple(values))) else: attrs = re.sub("'", '', str(tuple(attrs))) values = str(tuple(values)) # Create a cursor from the connection. cursor = connection.cursor() # Execute the command to write the new data to the database. try: cursor.execute("""INSERT INTO information {a} VALUES {v}""".\ format(a=attrs, v=values)) except IntegrityError: print(productData["product"] + " already exists in the database.") # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def addProducts(newProducts, data, overwrite=False, connection=None): """ Add many product tuples to the database. Args: newProducts (list of str): The list of new products. data (list of dict of str: str): The list of new data housed in dictionaries in the form {"product": ?, "sku": ?, "account": ?, "class": ?, "category": ?, "subcategory": ?}. overwrite (bool, optional): True if data already in the database should be overwritten with the new data, false otherwise. connection (sqlite3.Connection, optional): A connection to the database. Returns: bool: True if successful, false otherwise. """ # Get the list of old products. oldProducts = getAttribute("product", connection) # Convert the new products to be a set. newProductsSet = set(newProducts) # Find the difference between the old and new data. addProducts = newProductsSet.difference(oldProducts) # Find the intersection of the old and new data. setProducts = newProductsSet.intersection(oldProducts) # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Iterate over the rows in the input data. for productData in data: if productData["product"] in addProducts: # Initlialize the attribute and value lists. attrs = [] values = [] # Iterate over the inputted values and extract attributes. for (key, value) in productData.items(): if value is None or value == '': continue else: attrs.append(key) values.append(value) # Convert to a valid string removing unnecessary characters. if len(attrs) == 1: attrs = re.sub("[',]", '', str(tuple(attrs))) values = re.sub(",", '', str(tuple(values))) else: attrs = re.sub("'", '', str(tuple(attrs))) values = str(tuple(values)) # Execute the command to write the new data to the database. cursor.execute("""INSERT INTO information {a} VALUES {v}""".\ format(a=attrs, v=values)) elif overwrite: # Set up the product for input productInput = "'" + productData["product"] + "'" # Iterate over the inputted values and update then in the database. for (key, value) in productData.items(): change = key + "='" + value + "'" cursor.execute("""UPDATE information SET {c} WHERE product={p} """.format(c=change, p=productInput)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def getProductData(product, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the command to select all information for a product. cursor.execute("""SELECT * FROM information WHERE product='{p}'""".\ format(p=product)) # Fetch the data. data = cursor.fetchone() # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() return data def getProductHash(connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the command to pull all products that do not have a null sku. cursor.execute("""SELECT product, sku FROM information WHERE sku IS NOT NULL""") # Fetch all of the returned data. data = cursor.fetchall() # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() # Convert the data to a dictionary. match = {x[1]: x[0] for x in data} return match def getProductNames(connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the command to pull all products that do not have a null sku. cursor.execute("""SELECT DISTINCT product FROM information""") # Fetch all of the returned data. data = cursor.fetchall() # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() # Get only the names of the products. products = [x[0] for x in data] return products def setProduct(product, productData, connection=None): """ Set a product's tuple in the database. Args: product (str): The product currently in the database. productData (dict of {str: str}): A tuple to add to the database. Must be of the form {"product": ?, "sku": ?, "account": ?, "class": ?, "category": ?, "subcategory": ?}. Use None to set attributes to be NULL. connection (sqlite3.Connection, optional): A connection to the database. Returns: bool: True if successful, false otherwise. """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Iterate over the input product data dictionary. for (key, value) in productData.items(): if value == '': change = key + "=NULL" else: change = key + "='" + value + "'" cursor.execute("""UPDATE information SET {c} WHERE product='{p}'""".\ format(c=change, p=product)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() # Change name if a new product is given. if "product" in productData: idata.changeName(product, productData["product"]) return True def setProducts(products, productData, connection=None): """ Set a group of product's to have the same tuple (except unique) in the database. Args: product (str): The product currently in the database. productData (dict of {str: str}): A tuple to add to the database. Must be of the form {"product": ?, "sku": ?, "account": ?, "class": ?, "category": ?, "subcategory": ?}. Use None to set attributes to be NULL. connection (sqlite3.Connection, optional): A connection to the database. Returns: bool: True if successful, false otherwise. """ # Check if product or sku is defined in the input data, if so return false. if productData["product"] != '' or productData["sku"] != '': return False # Define the input string for all products. change = '' for (key, value) in productData.items(): if value != '': change = ''.join([change, ", ", key, "='", value, "'"]) change = change[2:] # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Iterate over the inputted products and change the data. for product in products: cursor.execute("""UPDATE information SET {c} WHERE product='{p}'""".\ format(c=change, p=product)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def removeProduct(product, connection=None): """ Remove a product tuple from the database. Args: products (str): The product to be removed from the database. connection (sqlite3.Connection, optional): A connection to the database. Returns: bool: True if successful, false otherwise. """ # Convert to a valid string by adding or removing characters. product = "'" + product + "'" # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the command to remove the row of the given product. cursor.execute("""DELETE FROM information WHERE product={p}""".\ format(p=product)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True """ Hierarchy """ def addTitle(tier, title, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to add the title to the database. cursor.execute("""INSERT INTO hierarchy VALUES ('{tr}', '{te}')""".\ format(tr=tier, te=title)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def setTitle(tier, oldTitle, newTitle, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""UPDATE hierarchy SET title='{te2}' WHERE tier='{tr}' AND title='{te1}'""".format(tr=tier, te1=oldTitle, te2=newTitle)) # Execute the statement to change any names in the information table. cursor.execute("""UPDATE information SET {t}='{nt}' WHERE {t}='{ot}'""".\ format(t=tier, ot=oldTitle, nt=newTitle)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def removeTitle(tier, title, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""DELETE FROM hierarchy WHERE tier='{tr}' AND title='{te}' """.format(tr=tier, te=title)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def getTiers(connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""SELECT DISTINCT tier FROM hierarchy""") # Fetch the returned data. tiers = [tier[0] for tier in cursor.fetchall()] # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() return tiers def getForTier(tier, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""SELECT title FROM hierarchy WHERE tier='{t}'""".\ format(t=tier)) # Fetch the returned data. titles = [title[0] for title in cursor.fetchall()] # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() return titles """ Variable """ def addAlias(variable, alias, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to add the title to the database. cursor.execute("""INSERT INTO variable VALUES ('{v}', "{a}");""".\ format(v=variable, a=alias.lower())) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def setAlias(variable, oldAlias, newAlias, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""UPDATE variable SET alias="{a2}" WHERE variable='{v}' AND alias="{a1}";""".format(v=variable, a1=oldAlias, a2=newAlias)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def removeAlias(variable, alias, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""DELETE FROM variable WHERE variable='{v}' AND alias="{a}";""".format(v=variable, a=alias)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def getVariables(connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""SELECT DISTINCT variable FROM variable""") # Fetch the returned data. variables = [variable[0] for variable in cursor.fetchall()] # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() return variables def getForVariable(variable, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""SELECT alias FROM variable WHERE variable='{v}'""".\ format(v=variable)) # Fetch the returned data. aliases = [alias[0] for alias in cursor.fetchall()] # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() return aliases def getVariableHash(connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to remove the tier title combo from the database. cursor.execute("""SELECT alias, variable FROM variable""") # Fetch the returned data. lookup = {alias[0]: alias[1] for alias in cursor.fetchall()} # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() return lookup """ Missing Products """ def addMissing(basis, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the command to add a missing product. cursor.execute("""INSERT OR IGNORE INTO missing (basis) VALUES ('{b}')""".\ format(b=basis)) # Execute the command to get the id of the input basis. cursor.execute("""SELECT id FROM missing WHERE basis='{b}'""".\ format(b=basis)) # Fetch the returned id. basisID = cursor.fetchone()[0] # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return basisID def getMissing(connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the command to select all missing basis. cursor.execute("""SELECT id, basis FROM missing ORDER BY id""") # Fetch the returned data. missing = cursor.fetchall() # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return missing def assignMissing(product, sku, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Call the command to update the information of the product. setProduct(product, {"sku": sku}, connection) # Execute the statement to get the ID of the basis. cursor.execute("""SELECT id FROM missing WHERE basis='{b}'""".\ format(b=sku)) # Fetch the ID. count = fetchone()[0] # Reassign the data stored to the proper product. idata.changeName("TEMP-" + count, product) # Execute the command to delete the sku from the missing list. cursor.execute("""DELETE FROM missing WHERE basis='{b}'""".format(b=sku)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True """ Import Information """ def addImport(fileInfo, connection=None): """ """ # Put the inputs into the correct string form. columns = str(tuple(fileInfo.keys())).replace("'", '') values = str(tuple([x.encode() for x in fileInfo.values()])) # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to add the import information. cursor.execute("""INSERT INTO import {c} VALUES {v}""".format(c=columns, v=values)) # Execute the statement to get the id of the input. cursor.execute("""SELECT id FROM import WHERE date_of_import='{doi}'""".\ format(doi=fileInfo["date_of_import"])) # Fetch the returned id. importID = cursor.fetchone()[0] # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return importID """ Link Products """ def addLink(old, new, connection=None): """ """ # Create the string form for the values. values = str((old, new)) # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to add the link. cursor.execute("""INSERT OR REPLACE INTO link (old, new) VALUES {v}""".\ format(v=values)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def setLink(old, new, kind, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to add the link. if kind == 1: cursor.execute("""UPDATE link SET old='{o}' WHERE new='{n}'""".\ format(o=old, n=new)) elif kind == 2: cursor.execute("""UPDATE link SET new='{n}' WHERE old='{o}'""".\ format(o=old, n=new)) else: cursor.execute("""UPDATE link SET old='{o}', new='{n}' WHERE old='{o2}'""".format(o=old, n=new, o2=kind)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def removeLink(old, new, connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to delete the input link. cursor.execute("""DELETE FROM link WHERE old='{o}' AND new='{n}'""".\ format(o=old, n=new)) # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.commit() connection.close() return True def getLinks(connection=None): """ """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Execute the statement to add the link. cursor.execute("""SELECT old, new FROM link ORDER BY old""") # Fetch all of the returned data. links = cursor.fetchall() # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() return links def getLinksTo(product, connection=None): """ Assumes links are one to one. """ # Open the master database if it is not supplied. flag = False if connection is None: connection = sqlite3.connect(MASTER) flag = True # Create a cursor from the connection. cursor = connection.cursor() # Initialize links. links = [] # Execute the command to cursor.execute("""SELECT old FROM link WHERE new='{n}'""".\ format(n=product)) # Fetch all of the returned data. links = [x[0] for x in cursor.fetchall()] # Close the cursor. cursor.close() # Commit the change to the database and close the connection. if flag: connection.close() return links """ Helper Functions """ def text2date(text): """ SQL text date format is yyyy-mm-dd. """ # return dt.date(int(text[0 : 4]), int(text[5 : 7]), int(text[8 : 10]))
mit
-6,560,678,926,358,750,000
26.103728
79
0.631555
false
Sup3r-Us3r/HashCode
hashcode-en.py
1
12188
#!/usr/bin/env python #coding: utf-8 ''' HashCode ''' import hashlib from base64 import b64encode, b64decode import codecs import binascii import re from time import sleep import sys import os from platform import python_version Limpar = "clear" if sys.version_info[0] < 3: versao = python_version() print("\n\033[32m You are using python in the version\033[1;m \033[1m\033[31m%s\033[1;m \033[32mand it is lower than python3 onwards.\033[1;m" %(versao)) print("\033[32m Please run HashCode with a higher version than python2\033[1;m\n") exit(1) def Apresentacao(): os.system(Limpar) print("""\033[31m ▄ █ ██ ▄▄▄▄▄ ▄ █ ▄█▄ ████▄ ██▄ ▄███▄ █ █ █ █ █ ▀▄ █ █ █▀ ▀▄ █ █ █ █ █▀ ▀ ██▀▀█ █▄▄█ ▄ ▀▀▀▀▄ ██▀▀█ █ ▀ █ █ █ █ ██▄▄ █ █ █ █ ▀▄▄▄▄▀ █ █ █▄ ▄▀ ▀████ █ █ █▄ ▄▀ █ █ █ ▀███▀ ███▀ ▀███▀ ▀ █ ▀ ▀ \033[1mBy: Magno-Tutor\033[1;m """) def Again(frase, call): opcao1 = input(frase) if opcao1 == "y": call() elif opcao1 == "n": Escolha() else: Again(frase,call) def Escolha(): Apresentacao() print(""" [\033[1;32m*\033[1;m] CHOOSE ONE OF THE OPTIONS BELOW TO CONTINUE: \033[31mA\033[1;m) \033[31mENCODE\033[1;m - \033[32mMD5\033[1;m \033[31mB\033[1;m) \033[31mENCODE\033[1;m - \033[32mSHA1\033[1;m \033[31mC\033[1;m) \033[31mENCODE\033[1;m - \033[32mSHA224\033[1;m \033[31mD\033[1;m) \033[31mENCODE\033[1;m - \033[32mSHA256\033[1;m \033[31mE\033[1;m) \033[31mENCODE\033[1;m - \033[32mSHA384\033[1;m \033[31mF\033[1;m) \033[31mENCODE\033[1;m - \033[32mSHA512\033[1;m \033[31mG\033[1;m) \033[31mENCODE/DECODE\033[1;m - \033[32mBASE64\033[1;m \033[31mH\033[1;m) \033[31mENCODE/DECODE\033[1;m - \033[32mBINARY\033[1;m \033[31mI\033[1;m) \033[31mENCODE/DECODE\033[1;m - \033[32mHEXADECIMAL\033[1;m \033[31mJ\033[1;m) \033[31mENCODE/DECODE\033[1;m - \033[32mCIPHER OF CESAR\033[1;m \033[31mK\033[1;m) \033[31mREVERSE\033[1;m - \033[32mTEXT\033[1;m \033[31mL\033[1;m) \033[31mREVERSE\033[1;m - \033[32mWORDS\033[1;m \033[31mq\033[1;m) EXIT """) opcao1 = input("\n\033[1;36m⟫⟫⟫\033[1;m ") if opcao1 == "A" or opcao1 == "a": Md5() elif opcao1 == "B" or opcao1 == "b": Sha1() elif opcao1 == "C" or opcao1 == "c": Sha224() elif opcao1 == "D" or opcao1 == "d": Sha256() elif opcao1 == "E" or opcao1 == "e": Sha384() elif opcao1 == "F" or opcao1 == "f": Sha512() elif opcao1 == "G" or opcao1 == "g": Base64() elif opcao1 == "H" or opcao1 == "h": Binario() elif opcao1 == "I" or opcao1 == "i": Hexadecimal() elif opcao1 == "J" or opcao1 == "j": CifraDeCesar() elif opcao1 == "K" or opcao1 == "k": TextReverse() elif opcao1 == "L" or opcao1 == "l": WordsReverse() elif opcao1 == "q" or opcao1 == "q": exit(1) else: Escolha() def Md5(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO ENCRYPT IN MD5\033[1;m: ") hash_object = hashlib.md5(mystring.encode()) print("") print(hash_object.hexdigest()) print("") Again("\n\033[1;36mDESIRE TO DO ANOTHER ENCODE IN MD5 (y/n) ?:\033[1;m ", Md5) def Sha1(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO ENCRYPT IN SHA1\033[1;m: ") hash_object = hashlib.sha1(mystring.encode()) print("") print(hash_object.hexdigest()) print("") Again("\n\033[1;36mDESIRE TO DO ANOTHER ENCODE IN SHA1 (y/n) ?:\033[1;m ", Sha1) def Sha224(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO ENCRYPT IN SHA224\033[1;m: ") hash_object = hashlib.sha224(mystring.encode()) print("") print(hash_object.hexdigest()) print("") Again("\n\033[1;36mDESIRE TO DO ANOTHER ENCODE IN SHA224 (y/n) ?:\033[1;m ", Sha224) def Sha256(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO ENCRYPT IN SHA256\033[1;m: ") hash_object = hashlib.sha256(mystring.encode()) print("") print(hash_object.hexdigest()) print("") Again("\n\033[1;36mDESIRE TO DO ANOTHER ENCODE IN SHA256 (y/n) ?:\033[1;m ", Sha256) def Sha384(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO ENCRYPT IN SHA384\033[1;m: ") hash_object = hashlib.sha384(mystring.encode()) print("") print(hash_object.hexdigest()) print("") Again("\n\033[1;36mDESIRE TO DO ANOTHER ENCODE IN SHA384 (y/n) ?:\033[1;m ", Sha384) def Sha512(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO ENCRYPT IN SHA512\033[1;m: ") hash_object = hashlib.sha512(mystring.encode()) print("") print(hash_object.hexdigest()) print("") Again("\n\033[1;36mDESIRE TO DO ANOTHER ENCODE IN SHA512 (y/n) ?:\033[1;m ", Sha512) def Base64Encode(): Apresentacao() mystring = str(input("\033[32mPLACE THE TEXT YOU WANT TO TRANSFORM IN BASE64\033[1;m: ")) print("") encode = b64encode(mystring.encode('utf-8')) decode = encode.decode('utf-8') print(decode) print("") Again("\n\033[1;36mWOULD YOU LIKE TO TRANSFORM ANOTHER TEXT IN BASE64 (y/n) ?:\033[1;m ", Base64Encode) def Base64Decode(): Apresentacao() mystring = str(input("\033[32mPLACE THE TEXT YOU WANT TO UNCOVER IN BASE64\033[1;m: ")) print("") try: decode = b64decode(mystring).decode('utf-8') print(decode) print("") except: print("\n[\033[1;91m!\033[1;m] INCORRECT PADDING") sleep(3) Base64Decode() Again("\n\033[1;36mWISHES TO UNCOVER ANOTHER TEXT IN BASE64 (y/n) ?:\033[1;m ", Base64Decode) def Base64(): Apresentacao() print(""" [\033[1;32m*\033[1;m] CHOOSE ONE OF THE OPTIONS BELOW TO CONTINUE: \033[31m1\033[1;m) ENCODE - BASE64 \033[31m2\033[1;m) DECODE - BASE64 """) opcao1 = input("\n\033[1;36m⟫⟫⟫\033[1;m ") if opcao1 == "1": Base64Encode() elif opcao1 == "2": Base64Decode() else: Base64() def BinarioEncode(encoding='utf-8', errors='surrogatepass'): Apresentacao() try: mystring = input("\033[32mPLACE THE TEXT YOU WANT TO TRANSFORM IN BINÁRIO\033[1;m: ") print("") bits = bin(int(binascii.hexlify(mystring.encode(encoding, errors)), 16))[2:] print(bits.zfill(8 * ((len(bits) + 7) // 8))) print("") except: print("\n[\033[1;91m!\033[1;m] VALUE ERROR") sleep(3) BinarioEncode() Again("\n\033[1;36mWOULD YOU LIKE TO TRANSFORM ANOTHER TEXT IN BINÁRIO (y/n) ?:\033[1;m ", BinarioEncode) def BinarioDecode(encoding='utf-8', errors='surrogatepass'): Apresentacao() try: binario = input("\033[32mPLACE THE SEQUENCE OF NUMBERS YOU DESIRE TO UNCOVER IN BINARY\033[1;m: ") binario = binario.replace(" ", "") n = int(binario, 2) print("") print(int2bytes(n).decode(encoding, errors)) print("") except: print("\n\n[\033[1;91m!\033[1;m] VALUE ERROR") sleep(3) BinarioDecode() Again("\n\033[1;36mWISHES TO UNCOVER ANOTHER SEQUENCE IN BINARY (y/n) ?:\033[1;m ", BinarioDecode) def int2bytes(i): hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n & 1))) def Binario(): Apresentacao() print(""" [\033[1;32m*\033[1;m] CHOOSE ONE OF THE OPTIONS BELOW TO CONTINUE: \033[31m1\033[1;m) ENCODE - BINARY \033[31m2\033[1;m) DECODE - BINARY """) opcao1 = input("\n\033[1;36m⟫⟫⟫\033[1;m ") if opcao1 == "1": BinarioEncode() elif opcao1 == "2": BinarioDecode() else: Binario() def HexaEncode(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO TRANSFORM IN HEXADECIMAL\033[1;m: ") print("") encode = binascii.hexlify(bytes(mystring, "utf-8")) encode = str(encode).strip("b") encode = encode.strip("'") encode = re.sub(r'(..)', r'\1 ', encode).strip() print(encode) print("") Again("\n\033[1;36mWANT TO TRANSFORM ANOTHER TEXT IN HEXADECIMAL (y/n) ?:\033[1;m ", HexaEncode) def HexaDecode(): Apresentacao() try: mystring = input("\033[32mPLACE THE SEQUENCE OF CHARACTERS YOU DESIRE TO UNCOVER IN HEXADECIMAL\033[1;m: ") print("") decode = bytes.fromhex(mystring).decode('utf-8') print(decode) print("") except: print("\n[\033[1;91m!\033[1;m] VALUE ERROR") sleep(3) HexaDecode() Again("\n\033[1;36mWISHES TO UNCOVER ANOTHER SEQUENCE IN HEXADECIMAL (y/n) ?:\033[1;m ", HexaDecode) def Hexadecimal(): Apresentacao() print(""" [\033[1;32m*\033[1;m] CHOOSE ONE OF THE OPTIONS BELOW TO CONTINUE: \033[31m1\033[1;m) ENCODE - HEXADECIMAL \033[31m2\033[1;m) DECODE - HEXADECIMAL """) opcao1 = input("\n\033[1;36m⟫⟫⟫\033[1;m ") if opcao1 == "1": HexaEncode() elif opcao1 == "2": HexaDecode() else: Hexadecimal() def TextReverseEncode(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO REVERSE\033[1;m: ") print("") print(mystring[::-1]) print("") Again("\n\033[1;36mWANTS TO MAKE ANOTHER REVERSE (y/n) ?:\033[1;m ", TextReverseEncode) def TextReverseDecode(): Apresentacao() mystring = input("\033[32mPLACE TEXT YOU WANT TO UNCOVER THE REVERSE\033[1;m: ") print("") print(mystring[::-1]) print("") Again("\n\033[1;36mWANT TO UNCOVER ANOTHER REVERSE (y/n) ?:\033[1;m ", TextReverseDecode) def TextReverse(): Apresentacao() print(""" [\033[1;32m*\033[1;m] CHOOSE ONE OF THE OPTIONS BELOW TO CONTINUE: \033[31m1\033[1;m) ENCODE - REVERSE-TEXT \033[31m2\033[1;m) DECODE - REVERSE-TEXT """) opcao1 = input("\n\033[1;36m⟫⟫⟫\033[1;m ") if opcao1 == "1": TextReverseEncode() elif opcao1 == "2": TextReverseDecode() else: TextReverse() def WordsReverseEncode(): Apresentacao() mystring = input("\033[32mPLACE THE TEXT YOU WANT TO REVERSE\033[1;m: ") print("") print(' '.join(mystring.split()[::-1])) print("") Again("\n\033[1;36mWANTS TO MAKE ANOTHER REVERSE (y/n) ?:\033[1;m ", WordsReverseEncode) def WordsReverseDecode(): Apresentacao() mystring = input("\033[32mPLACE TEXT YOU WANT TO UNCOVER THE REVERSE\033[1;m: ") print("") print(' '.join(mystring.split()[::-1])) print("") Again("\n\033[1;36mWANT TO UNCOVER ANOTHER REVERSE (y/n) ?:\033[1;m ", WordsReverseDecode) def WordsReverse(): Apresentacao() print(""" [\033[1;32m*\033[1;m] CHOOSE ONE OF THE OPTIONS BELOW TO CONTINUE: \033[31m1\033[1;m) ENCODE - REVERSE-WORDS \033[31m2\033[1;m) DECODE - REVERSE-WORDS """) opcao1 = input("\n\033[1;36m⟫⟫⟫\033[1;m ") if opcao1 == "1": WordsReverseEncode() elif opcao1 == "2": WordsReverseDecode() else: WordsReverse() def CifraDeCesar(): Apresentacao() print(""" [\033[1;32m*\033[1;m] CHOOSE ONE OF THE OPTIONS BELOW TO CONTINUE: \033[31m1\033[1;m) ENCODE - CIPHER OF CESAR \033[31m2\033[1;m) DECODE - CIPHER OF CESAR """) opcao1 = input("\n\033[1;36m⟫⟫⟫\033[1;m ") if opcao1 == "1": ChamarBloco1() elif opcao1 == "2": ChamarBloco2() else: CifraDeCesar() def cifrar(palavras, chave): abc = "abcdefghijklmnopqrstuvwxyz " text_cifrado = '' for letra in palavras: soma = abc.find(letra) + chave modulo = int(soma) % len(abc) text_cifrado = text_cifrado + str(abc[modulo]) return text_cifrado def decifrar(palavras, chave): abc = "abcdefghijklmnopqrstuvwxyz " text_cifrado = '' for letra in palavras: soma = abc.find(letra) - chave modulo = int(soma) % len(abc) text_cifrado = text_cifrado + str(abc[modulo]) return text_cifrado def ChamarBloco1(): Apresentacao() try: c = str(input('\n\033[32mTEXT FOR CIPHER\033[1;m: ')).lower() n = int(input('\033[32mNUMERICAL KEY\033[1;m: ')) print("\033[32mRESULT\033[1;m:", cifrar(c, n)) print("") except: print("\n\n[\033[1;91m!\033[1;m] VALUE ERROR") sleep(3) ChamarBloco1() Again("\n\033[1;36mDESIRE TO DO ANOTHER ENCODE GIVES CIPHER OF CESAR (y/n) ?:\033[1;m ", ChamarBloco1) def ChamarBloco2(): Apresentacao() try: cc = str(input('\n\033[32mTEXT TO BE DECODE\033[1;m: ')).lower() cn = int(input('\033[32mNUMERICAL KEY\033[1;m: ')) print("\033[32mRESULT\033[1;m:", decifrar(cc, cn)) print("") except: print("\n\n[\033[1;91m!\033[1;m] VALUE ERROR") sleep(3) ChamarBloco2() Again("\n\033[1;36mDESIRE TO DO ANOTHER DECODE GIVES CIPHER OF CESAR (y/n) ?:\033[1;m ", ChamarBloco2) Escolha()
gpl-3.0
-8,936,845,709,316,746,000
26.985882
154
0.639146
false
chenbaihu/grpc
tools/run_tests/run_tests.py
1
10684
#!/usr/bin/python2.7 # Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Run tests in parallel.""" import argparse import glob import itertools import json import multiprocessing import os import re import sys import time import jobset import watch_dirs ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..')) os.chdir(ROOT) # SimpleConfig: just compile with CONFIG=config, and run the binary to test class SimpleConfig(object): def __init__(self, config, environ={}): self.build_config = config self.maxjobs = 2 * multiprocessing.cpu_count() self.allow_hashing = (config != 'gcov') self.environ = environ def job_spec(self, binary, hash_targets): return jobset.JobSpec(cmdline=[binary], environ=self.environ, hash_targets=hash_targets if self.allow_hashing else None) # ValgrindConfig: compile with some CONFIG=config, but use valgrind to run class ValgrindConfig(object): def __init__(self, config, tool, args=[]): self.build_config = config self.tool = tool self.args = args self.maxjobs = 2 * multiprocessing.cpu_count() self.allow_hashing = False def job_spec(self, binary, hash_targets): return jobset.JobSpec(cmdline=['valgrind', '--tool=%s' % self.tool] + self.args + [binary], shortname='valgrind %s' % binary, hash_targets=None) class CLanguage(object): def __init__(self, make_target, test_lang): self.make_target = make_target with open('tools/run_tests/tests.json') as f: js = json.load(f) self.binaries = [tgt for tgt in js if tgt['language'] == test_lang] def test_specs(self, config, travis): out = [] for target in self.binaries: if travis and target['flaky']: continue binary = 'bins/%s/%s' % (config.build_config, target['name']) out.append(config.job_spec(binary, [binary])) return out def make_targets(self): return ['buildtests_%s' % self.make_target] def build_steps(self): return [] class NodeLanguage(object): def test_specs(self, config, travis): return [config.job_spec('tools/run_tests/run_node.sh', None)] def make_targets(self): return ['static_c'] def build_steps(self): return [['tools/run_tests/build_node.sh']] class PhpLanguage(object): def test_specs(self, config, travis): return [config.job_spec('src/php/bin/run_tests.sh', None)] def make_targets(self): return ['static_c'] def build_steps(self): return [['tools/run_tests/build_php.sh']] class PythonLanguage(object): def test_specs(self, config, travis): return [config.job_spec('tools/run_tests/run_python.sh', None)] def make_targets(self): return[] def build_steps(self): return [['tools/run_tests/build_python.sh']] class RubyLanguage(object): def test_specs(self, config, travis): return [config.job_spec('tools/run_tests/run_ruby.sh', None)] def make_targets(self): return ['static_c'] def build_steps(self): return [['tools/run_tests/build_ruby.sh']] # different configurations we can run under _CONFIGS = { 'dbg': SimpleConfig('dbg'), 'opt': SimpleConfig('opt'), 'tsan': SimpleConfig('tsan', environ={ 'TSAN_OPTIONS': 'suppressions=tools/tsan_suppressions.txt'}), 'msan': SimpleConfig('msan'), 'ubsan': SimpleConfig('ubsan'), 'asan': SimpleConfig('asan', environ={ 'ASAN_OPTIONS': 'detect_leaks=1:color=always:suppressions=tools/tsan_suppressions.txt'}), 'gcov': SimpleConfig('gcov'), 'memcheck': ValgrindConfig('valgrind', 'memcheck', ['--leak-check=full']), 'helgrind': ValgrindConfig('dbg', 'helgrind') } _DEFAULT = ['dbg', 'opt'] _LANGUAGES = { 'c++': CLanguage('cxx', 'c++'), 'c': CLanguage('c', 'c'), 'node': NodeLanguage(), 'php': PhpLanguage(), 'python': PythonLanguage(), 'ruby': RubyLanguage() } # parse command line argp = argparse.ArgumentParser(description='Run grpc tests.') argp.add_argument('-c', '--config', choices=['all'] + sorted(_CONFIGS.keys()), nargs='+', default=_DEFAULT) argp.add_argument('-n', '--runs_per_test', default=1, type=int) argp.add_argument('-r', '--regex', default='.*', type=str) argp.add_argument('-j', '--jobs', default=1000, type=int) argp.add_argument('-s', '--slowdown', default=1.0, type=float) argp.add_argument('-f', '--forever', default=False, action='store_const', const=True) argp.add_argument('-t', '--travis', default=False, action='store_const', const=True) argp.add_argument('--newline_on_success', default=False, action='store_const', const=True) argp.add_argument('-l', '--language', choices=sorted(_LANGUAGES.keys()), nargs='+', default=sorted(_LANGUAGES.keys())) args = argp.parse_args() # grab config run_configs = set(_CONFIGS[cfg] for cfg in itertools.chain.from_iterable( _CONFIGS.iterkeys() if x == 'all' else [x] for x in args.config)) build_configs = set(cfg.build_config for cfg in run_configs) make_targets = [] languages = set(_LANGUAGES[l] for l in args.language) build_steps = [jobset.JobSpec(['make', '-j', '%d' % (multiprocessing.cpu_count() + 1), 'EXTRA_DEFINES=GRPC_TEST_SLOWDOWN_MACHINE_FACTOR=%f' % args.slowdown, 'CONFIG=%s' % cfg] + list(set( itertools.chain.from_iterable( l.make_targets() for l in languages)))) for cfg in build_configs] + list(set( jobset.JobSpec(cmdline) for l in languages for cmdline in l.build_steps())) one_run = set( spec for config in run_configs for language in args.language for spec in _LANGUAGES[language].test_specs(config, args.travis) if re.search(args.regex, spec.shortname)) runs_per_test = args.runs_per_test forever = args.forever class TestCache(object): """Cache for running tests.""" def __init__(self, use_cache_results): self._last_successful_run = {} self._use_cache_results = use_cache_results def should_run(self, cmdline, bin_hash): if cmdline not in self._last_successful_run: return True if self._last_successful_run[cmdline] != bin_hash: return True if not self._use_cache_results: return True return False def finished(self, cmdline, bin_hash): self._last_successful_run[cmdline] = bin_hash self.save() def dump(self): return [{'cmdline': k, 'hash': v} for k, v in self._last_successful_run.iteritems()] def parse(self, exdump): self._last_successful_run = dict((o['cmdline'], o['hash']) for o in exdump) def save(self): with open('.run_tests_cache', 'w') as f: f.write(json.dumps(self.dump())) def maybe_load(self): if os.path.exists('.run_tests_cache'): with open('.run_tests_cache') as f: self.parse(json.loads(f.read())) def _build_and_run(check_cancelled, newline_on_success, travis, cache): """Do one pass of building & running tests.""" # build latest sequentially if not jobset.run(build_steps, maxjobs=1, newline_on_success=newline_on_success, travis=travis): return 1 # run all the tests all_runs = itertools.chain.from_iterable( itertools.repeat(one_run, runs_per_test)) if not jobset.run(all_runs, check_cancelled, newline_on_success=newline_on_success, travis=travis, maxjobs=min(args.jobs, min(c.maxjobs for c in run_configs)), cache=cache): return 2 return 0 test_cache = TestCache(runs_per_test == 1) test_cache.maybe_load() if forever: success = True while True: dw = watch_dirs.DirWatcher(['src', 'include', 'test']) initial_time = dw.most_recent_change() have_files_changed = lambda: dw.most_recent_change() != initial_time previous_success = success success = _build_and_run(check_cancelled=have_files_changed, newline_on_success=False, cache=test_cache) == 0 if not previous_success and success: jobset.message('SUCCESS', 'All tests are now passing properly', do_newline=True) jobset.message('IDLE', 'No change detected') while not have_files_changed(): time.sleep(1) else: result = _build_and_run(check_cancelled=lambda: False, newline_on_success=args.newline_on_success, travis=args.travis, cache=test_cache) if result == 0: jobset.message('SUCCESS', 'All tests passed', do_newline=True) else: jobset.message('FAILED', 'Some tests failed', do_newline=True) sys.exit(result)
bsd-3-clause
5,858,742,370,812,202,000
31.975309
100
0.625234
false
pollitosabroson/idneo
src/catalogs/migrations/0001_initial.py
1
1867
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('public_id', models.CharField(verbose_name='public_id', unique=True, max_length=12, editable=False, db_index=True)), ('created_date', models.DateTimeField(auto_now_add=True, verbose_name='created date', null=True)), ('last_modified', models.DateTimeField(auto_now=True, auto_now_add=True, null=True, verbose_name='last modified')), ('name', models.CharField(max_length=80, verbose_name='name')), ], options={ 'abstract': False, 'get_latest_by': 'created', }, bases=(models.Model,), ), migrations.CreateModel( name='Type', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('public_id', models.CharField(verbose_name='public_id', unique=True, max_length=12, editable=False, db_index=True)), ('created_date', models.DateTimeField(auto_now_add=True, verbose_name='created date', null=True)), ('last_modified', models.DateTimeField(auto_now=True, auto_now_add=True, null=True, verbose_name='last modified')), ('name', models.CharField(max_length=80, verbose_name='name')), ], options={ 'abstract': False, 'get_latest_by': 'created', }, bases=(models.Model,), ), ]
apache-2.0
388,971,664,067,969,900
42.418605
133
0.559186
false
leggitta/mne-python
mne/tests/test_proj.py
1
11084
import os.path as op from nose.tools import assert_true, assert_raises import warnings import numpy as np from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_equal) import copy as cp import mne from mne.datasets import testing from mne import pick_types from mne.io import Raw from mne import compute_proj_epochs, compute_proj_evoked, compute_proj_raw from mne.io.proj import (make_projector, activate_proj, _needs_eeg_average_ref_proj) from mne.proj import (read_proj, write_proj, make_eeg_average_ref_proj, _has_eeg_average_ref_proj) from mne import read_events, Epochs, sensitivity_map, read_source_estimate from mne.utils import (_TempDir, run_tests_if_main, clean_warning_registry, slow_test) warnings.simplefilter('always') # enable b/c these tests throw warnings base_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data') raw_fname = op.join(base_dir, 'test_raw.fif') event_fname = op.join(base_dir, 'test-eve.fif') proj_fname = op.join(base_dir, 'test-proj.fif') proj_gz_fname = op.join(base_dir, 'test-proj.fif.gz') bads_fname = op.join(base_dir, 'test_bads.txt') sample_path = op.join(testing.data_path(download=False), 'MEG', 'sample') fwd_fname = op.join(sample_path, 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif') sensmap_fname = op.join(sample_path, 'sample_audvis_trunc-%s-oct-4-fwd-sensmap-%s.w') # sample dataset should be updated to reflect mne conventions eog_fname = op.join(sample_path, 'sample_audvis_eog_proj.fif') @testing.requires_testing_data def test_sensitivity_maps(): """Test sensitivity map computation""" fwd = mne.read_forward_solution(fwd_fname, surf_ori=True) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') proj_eog = read_proj(eog_fname) decim = 6 for ch_type in ['eeg', 'grad', 'mag']: w = read_source_estimate(sensmap_fname % (ch_type, 'lh')).data stc = sensitivity_map(fwd, projs=None, ch_type=ch_type, mode='free', exclude='bads') assert_array_almost_equal(stc.data, w, decim) assert_true(stc.subject == 'sample') # let's just make sure the others run if ch_type == 'grad': # fixed (2) w = read_source_estimate(sensmap_fname % (ch_type, '2-lh')).data stc = sensitivity_map(fwd, projs=None, mode='fixed', ch_type=ch_type, exclude='bads') assert_array_almost_equal(stc.data, w, decim) if ch_type == 'mag': # ratio (3) w = read_source_estimate(sensmap_fname % (ch_type, '3-lh')).data stc = sensitivity_map(fwd, projs=None, mode='ratio', ch_type=ch_type, exclude='bads') assert_array_almost_equal(stc.data, w, decim) if ch_type == 'eeg': # radiality (4), angle (5), remaining (6), and dampening (7) modes = ['radiality', 'angle', 'remaining', 'dampening'] ends = ['4-lh', '5-lh', '6-lh', '7-lh'] for mode, end in zip(modes, ends): w = read_source_estimate(sensmap_fname % (ch_type, end)).data stc = sensitivity_map(fwd, projs=proj_eog, mode=mode, ch_type=ch_type, exclude='bads') assert_array_almost_equal(stc.data, w, decim) # test corner case for EEG stc = sensitivity_map(fwd, projs=[make_eeg_average_ref_proj(fwd['info'])], ch_type='eeg', exclude='bads') def test_compute_proj_epochs(): """Test SSP computation on epochs""" tempdir = _TempDir() event_id, tmin, tmax = 1, -0.2, 0.3 raw = Raw(raw_fname, preload=True) events = read_events(event_fname) bad_ch = 'MEG 2443' picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False, exclude=[]) epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=None, proj=False) evoked = epochs.average() projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1) write_proj(op.join(tempdir, 'test-proj.fif.gz'), projs) for p_fname in [proj_fname, proj_gz_fname, op.join(tempdir, 'test-proj.fif.gz')]: projs2 = read_proj(p_fname) assert_true(len(projs) == len(projs2)) for p1, p2 in zip(projs, projs2): assert_true(p1['desc'] == p2['desc']) assert_true(p1['data']['col_names'] == p2['data']['col_names']) assert_true(p1['active'] == p2['active']) # compare with sign invariance p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0]) p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0]) if bad_ch in p1['data']['col_names']: bad = p1['data']['col_names'].index('MEG 2443') mask = np.ones(p1_data.size, dtype=np.bool) mask[bad] = False p1_data = p1_data[:, mask] p2_data = p2_data[:, mask] corr = np.corrcoef(p1_data, p2_data)[0, 1] assert_array_almost_equal(corr, 1.0, 5) # test that you can compute the projection matrix projs = activate_proj(projs) proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[]) assert_true(nproj == 2) assert_true(U.shape[1] == 2) # test that you can save them epochs.info['projs'] += projs evoked = epochs.average() evoked.save(op.join(tempdir, 'foo-ave.fif')) projs = read_proj(proj_fname) projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0) assert_true(len(projs_evoked) == 2) # XXX : test something # test parallelization projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=2, desc_prefix='foobar') assert_true(all('foobar' in x['desc'] for x in projs)) projs = activate_proj(projs) proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[]) assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16) # test warnings on bad filenames clean_warning_registry() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') proj_badname = op.join(tempdir, 'test-bad-name.fif.gz') write_proj(proj_badname, projs) read_proj(proj_badname) print([ww.message for ww in w]) assert_equal(len(w), 2) @slow_test def test_compute_proj_raw(): """Test SSP computation on raw""" tempdir = _TempDir() # Test that the raw projectors work raw_time = 2.5 # Do shorter amount for speed raw = Raw(raw_fname).crop(0, raw_time, False) raw.load_data() for ii in (0.25, 0.5, 1, 2): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') projs = compute_proj_raw(raw, duration=ii - 0.1, stop=raw_time, n_grad=1, n_mag=1, n_eeg=0) assert_true(len(w) == 1) # test that you can compute the projection matrix projs = activate_proj(projs) proj, nproj, U = make_projector(projs, raw.ch_names, bads=[]) assert_true(nproj == 2) assert_true(U.shape[1] == 2) # test that you can save them raw.info['projs'] += projs raw.save(op.join(tempdir, 'foo_%d_raw.fif' % ii), overwrite=True) # Test that purely continuous (no duration) raw projection works with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') projs = compute_proj_raw(raw, duration=None, stop=raw_time, n_grad=1, n_mag=1, n_eeg=0) assert_equal(len(w), 1) # test that you can compute the projection matrix projs = activate_proj(projs) proj, nproj, U = make_projector(projs, raw.ch_names, bads=[]) assert_true(nproj == 2) assert_true(U.shape[1] == 2) # test that you can save them raw.info['projs'] += projs raw.save(op.join(tempdir, 'foo_rawproj_continuous_raw.fif')) # test resampled-data projector, upsampling instead of downsampling # here to save an extra filtering (raw would have to be LP'ed to be equiv) raw_resamp = cp.deepcopy(raw) raw_resamp.resample(raw.info['sfreq'] * 2, n_jobs=2) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') projs = compute_proj_raw(raw_resamp, duration=None, stop=raw_time, n_grad=1, n_mag=1, n_eeg=0) projs = activate_proj(projs) proj_new, _, _ = make_projector(projs, raw.ch_names, bads=[]) assert_array_almost_equal(proj_new, proj, 4) # test with bads raw.load_bad_channels(bads_fname) # adds 2 bad mag channels with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') projs = compute_proj_raw(raw, n_grad=0, n_mag=0, n_eeg=1) # test that bad channels can be excluded proj, nproj, U = make_projector(projs, raw.ch_names, bads=raw.ch_names) assert_array_almost_equal(proj, np.eye(len(raw.ch_names))) def test_make_eeg_average_ref_proj(): """Test EEG average reference projection""" raw = Raw(raw_fname, add_eeg_ref=False, preload=True) eeg = mne.pick_types(raw.info, meg=False, eeg=True) # No average EEG reference assert_true(not np.all(raw._data[eeg].mean(axis=0) < 1e-19)) # Apply average EEG reference car = make_eeg_average_ref_proj(raw.info) reref = raw.copy() reref.add_proj(car) reref.apply_proj() assert_array_almost_equal(reref._data[eeg].mean(axis=0), 0, decimal=19) # Error when custom reference has already been applied raw.info['custom_ref_applied'] = True assert_raises(RuntimeError, make_eeg_average_ref_proj, raw.info) def test_has_eeg_average_ref_proj(): """Test checking whether an EEG average reference exists""" assert_true(not _has_eeg_average_ref_proj([])) raw = Raw(raw_fname, add_eeg_ref=True, preload=False) assert_true(_has_eeg_average_ref_proj(raw.info['projs'])) def test_needs_eeg_average_ref_proj(): """Test checking whether a recording needs an EEG average reference""" raw = Raw(raw_fname, add_eeg_ref=False, preload=False) assert_true(_needs_eeg_average_ref_proj(raw.info)) raw = Raw(raw_fname, add_eeg_ref=True, preload=False) assert_true(not _needs_eeg_average_ref_proj(raw.info)) # No EEG channels raw = Raw(raw_fname, add_eeg_ref=False, preload=True) eeg = [raw.ch_names[c] for c in pick_types(raw.info, meg=False, eeg=True)] raw.drop_channels(eeg) assert_true(not _needs_eeg_average_ref_proj(raw.info)) # Custom ref flag set raw = Raw(raw_fname, add_eeg_ref=False, preload=False) raw.info['custom_ref_applied'] = True assert_true(not _needs_eeg_average_ref_proj(raw.info)) run_tests_if_main()
bsd-3-clause
5,226,061,160,491,691,000
39.452555
78
0.607813
false
smallbigcake/PodcastSubmitter
podcast.py
1
2191
#!/usr/bin/env python # coding=utf-8 import os import time DEFAULT_AUTHOR = "大饼" DEFAULT_SUMMARY = "通过手机上传" URL_PREFIX = "http://www.42kr.com/podcast/" XML_FILE_PATH = "/home/Cake/site/42kr/feed.xml" SUBMIT_FOLDER = "/home/Cake/tool/podcast_submit/submit_folder/" PODCAST_FOLDER = "/home/Cake/site/42kr/podcast/" class Podcast(object): def __init__(self, filename, author, summary, url, mediaType = "audio/mpeg"): self.filename = filename self.title = time.strftime("%Y-%m-%d %H:%M:%S") self.author = author self.subtitle = filename[:-4] self.summary = summary self.url = url self.mediaType = mediaType self.pubDate = time.strftime("%a, %d %b %Y %H:%M:%S CST") def toRSS(self): self.content = "<item>\n" self.content += "<title>%s</title>\n" % self.title self.content += "<itunes:author>%s</itunes:author>\n" % self.author self.content += "<itunes:subtitle>%s</itunes:subtitle>\n" % self.subtitle self.content += "<itunes:summary>%s</itunes:summary>\n" % self.summary self.content += "<enclosure url=\"%s\" type=\"%s\" />\n" % (self.url, self.mediaType) self.content += "<pubDate>%s</pubDate>\n" % self.pubDate self.content += "</item>\n\n" def writeXML(self, xmlFilePath): xmlFile = open(xmlFilePath, "r") lines = xmlFile.readlines() xmlFile.close() lines.insert(-2, self.content) print lines xmlFile = open(xmlFilePath, "w") xmlFile.writelines(lines) xmlFile.close() def submitFile(self, submitPath, podcastPath): os.system("mv " + submitPath + self.filename + " " + podcastPath) def submit(submitPath, podcastPath): pcList = [] for filename in os.listdir(submitPath): if filename.endswith("mp3"): pcList.append(Podcast(filename, DEFAULT_AUTHOR, DEFAULT_SUMMARY, URL_PREFIX + filename)) for pc in pcList: pc.toRSS() pc.writeXML(XML_FILE_PATH) pc.submitFile(submitPath, podcastPath) print pcList def main(): submit(SUBMIT_FOLDER, PODCAST_FOLDER) if __name__ == "__main__": main()
gpl-2.0
8,360,900,979,805,299,000
32.984375
100
0.611494
false
vespa-engine/vespa
model-integration/src/test/models/tensorflow/external/train_embed.py
1
2319
# Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. import numpy as np import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras.layers import Input, Dense, concatenate, Embedding, Reshape from tensorflow.keras.models import Model input_user = Input(shape=(3,)) input_ad = Input(shape=(3,)) gender_samples = Input(shape=(1,), dtype='int32') gender_values = ['m', 'f', 'a'] gender_embeddings = Embedding(len(gender_values), 1)(gender_samples) reshape_gender = Reshape(target_shape=[1])(gender_embeddings) model2 = Model(inputs=[gender_samples], outputs=reshape_gender) model2.summary() merged = concatenate([input_user, input_ad, reshape_gender]) output_1 = Dense(64, activation='relu')(merged) output_2 = Dense(64, activation='relu')(output_1) predictions = Dense(1)(output_2) model = Model(inputs=[input_user, input_ad, gender_samples], outputs=predictions) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.summary() SAMPLES = 1000 user_data = np.random.rand(SAMPLES,3) ad_data = np.random.rand(SAMPLES,3) gender_data = np.random.randint(len(gender_values), size=SAMPLES) labels = np.random.rand(SAMPLES,1) print(user_data[:10]) print(ad_data[:10]) print(gender_data[:10]) print(labels[:10]) model.fit([user_data, ad_data, gender_data], labels, epochs=10, ) # starts training user_data_sample1 = np.random.rand(1, 3) ad_data_sample1 = np.random.rand(1, 3) gender_data_sample1 = np.random.randint(len(gender_values), size=1) print("predicting for:") print(user_data_sample1) print(ad_data_sample1) print(gender_data_sample1) predictions = model.predict([user_data_sample1, ad_data_sample1, gender_data_sample1]) print(predictions) signature = tf.saved_model.signature_def_utils.predict_signature_def( inputs={'input1': model.inputs[0],'input2': model.inputs[1], 'input3': model.inputs[2] }, outputs={'pctrx': model.outputs[0]}) builder = tf.saved_model.builder.SavedModelBuilder('modelv2') builder.add_meta_graph_and_variables( sess=K.get_session(), tags=[tf.saved_model.tag_constants.SERVING], signature_def_map={ tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature }) builder.save()
apache-2.0
-145,607,975,196,287,330
34.136364
130
0.725313
false
vladimir-ipatov/ganeti
lib/query.py
1
87866
# # # Copyright (C) 2010, 2011, 2012, 2013 Google Inc. # # This program 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 2 of the License, or # (at your option) any later version. # # This program 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 this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """Module for query operations How it works: - Add field definitions - See how L{NODE_FIELDS} is built - Each field gets: - Query field definition (L{objects.QueryFieldDefinition}, use L{_MakeField} for creating), containing: - Name, must be lowercase and match L{FIELD_NAME_RE} - Title for tables, must not contain whitespace and match L{TITLE_RE} - Value data type, e.g. L{constants.QFT_NUMBER} - Human-readable description, must not end with punctuation or contain newlines - Data request type, see e.g. C{NQ_*} - OR-ed flags, see C{QFF_*} - A retrieval function, see L{Query.__init__} for description - Pass list of fields through L{_PrepareFieldList} for preparation and checks - Instantiate L{Query} with prepared field list definition and selected fields - Call L{Query.RequestedData} to determine what data to collect/compute - Call L{Query.Query} or L{Query.OldStyleQuery} with collected data and use result - Data container must support iteration using C{__iter__} - Items are passed to retrieval functions and can have any format - Call L{Query.GetFields} to get list of definitions for selected fields @attention: Retrieval functions must be idempotent. They can be called multiple times, in any order and any number of times. """ import logging import operator import re from ganeti import constants from ganeti import errors from ganeti import utils from ganeti import compat from ganeti import objects from ganeti import ht from ganeti import runtime from ganeti import qlang from ganeti import jstore from ganeti.constants import (QFT_UNKNOWN, QFT_TEXT, QFT_BOOL, QFT_NUMBER, QFT_UNIT, QFT_TIMESTAMP, QFT_OTHER, RS_NORMAL, RS_UNKNOWN, RS_NODATA, RS_UNAVAIL, RS_OFFLINE) (NETQ_CONFIG, NETQ_GROUP, NETQ_STATS, NETQ_INST) = range(300, 304) # Constants for requesting data from the caller/data provider. Each property # collected/computed separately by the data provider should have its own to # only collect the requested data and not more. (NQ_CONFIG, NQ_INST, NQ_LIVE, NQ_GROUP, NQ_OOB) = range(1, 6) (IQ_CONFIG, IQ_LIVE, IQ_DISKUSAGE, IQ_CONSOLE, IQ_NODES, IQ_NETWORKS) = range(100, 106) (LQ_MODE, LQ_OWNER, LQ_PENDING) = range(10, 13) (GQ_CONFIG, GQ_NODE, GQ_INST, GQ_DISKPARAMS) = range(200, 204) (CQ_CONFIG, CQ_QUEUE_DRAINED, CQ_WATCHER_PAUSE) = range(300, 303) (JQ_ARCHIVED, ) = range(400, 401) # Query field flags QFF_HOSTNAME = 0x01 QFF_IP_ADDRESS = 0x02 QFF_JOB_ID = 0x04 QFF_SPLIT_TIMESTAMP = 0x08 # Next values: 0x10, 0x20, 0x40, 0x80, 0x100, 0x200 QFF_ALL = (QFF_HOSTNAME | QFF_IP_ADDRESS | QFF_JOB_ID | QFF_SPLIT_TIMESTAMP) FIELD_NAME_RE = re.compile(r"^[a-z0-9/._]+$") TITLE_RE = re.compile(r"^[^\s]+$") DOC_RE = re.compile(r"^[A-Z].*[^.,?!]$") #: Verification function for each field type _VERIFY_FN = { QFT_UNKNOWN: ht.TNone, QFT_TEXT: ht.TString, QFT_BOOL: ht.TBool, QFT_NUMBER: ht.TInt, QFT_UNIT: ht.TInt, QFT_TIMESTAMP: ht.TNumber, QFT_OTHER: lambda _: True, } # Unique objects for special field statuses _FS_UNKNOWN = object() _FS_NODATA = object() _FS_UNAVAIL = object() _FS_OFFLINE = object() #: List of all special status _FS_ALL = compat.UniqueFrozenset([ _FS_UNKNOWN, _FS_NODATA, _FS_UNAVAIL, _FS_OFFLINE, ]) #: VType to QFT mapping _VTToQFT = { # TODO: fix validation of empty strings constants.VTYPE_STRING: QFT_OTHER, # since VTYPE_STRINGs can be empty constants.VTYPE_MAYBE_STRING: QFT_OTHER, constants.VTYPE_BOOL: QFT_BOOL, constants.VTYPE_SIZE: QFT_UNIT, constants.VTYPE_INT: QFT_NUMBER, } _SERIAL_NO_DOC = "%s object serial number, incremented on each modification" def _GetUnknownField(ctx, item): # pylint: disable=W0613 """Gets the contents of an unknown field. """ return _FS_UNKNOWN def _GetQueryFields(fielddefs, selected): """Calculates the internal list of selected fields. Unknown fields are returned as L{constants.QFT_UNKNOWN}. @type fielddefs: dict @param fielddefs: Field definitions @type selected: list of strings @param selected: List of selected fields """ result = [] for name in selected: try: fdef = fielddefs[name] except KeyError: fdef = (_MakeField(name, name, QFT_UNKNOWN, "Unknown field '%s'" % name), None, 0, _GetUnknownField) assert len(fdef) == 4 result.append(fdef) return result def GetAllFields(fielddefs): """Extract L{objects.QueryFieldDefinition} from field definitions. @rtype: list of L{objects.QueryFieldDefinition} """ return [fdef for (fdef, _, _, _) in fielddefs] class _FilterHints: """Class for filter analytics. When filters are used, the user of the L{Query} class usually doesn't know exactly which items will be necessary for building the result. It therefore has to prepare and compute the input data for potentially returning everything. There are two ways to optimize this. The first, and simpler, is to assign each field a group of data, so that the caller can determine which computations are necessary depending on the data groups requested. The list of referenced groups must also be computed for fields referenced in the filter. The second is restricting the items based on a primary key. The primary key is usually a unique name (e.g. a node name). This class extracts all referenced names from a filter. If it encounters any filter condition which disallows such a list to be determined (e.g. a non-equality filter), all names will be requested. The end-effect is that any operation other than L{qlang.OP_OR} and L{qlang.OP_EQUAL} will make the query more expensive. """ def __init__(self, namefield): """Initializes this class. @type namefield: string @param namefield: Field caller is interested in """ self._namefield = namefield #: Whether all names need to be requested (e.g. if a non-equality operator #: has been used) self._allnames = False #: Which names to request self._names = None #: Data kinds referenced by the filter (used by L{Query.RequestedData}) self._datakinds = set() def RequestedNames(self): """Returns all requested values. Returns C{None} if list of values can't be determined (e.g. encountered non-equality operators). @rtype: list """ if self._allnames or self._names is None: return None return utils.UniqueSequence(self._names) def ReferencedData(self): """Returns all kinds of data referenced by the filter. """ return frozenset(self._datakinds) def _NeedAllNames(self): """Changes internal state to request all names. """ self._allnames = True self._names = None def NoteLogicOp(self, op): """Called when handling a logic operation. @type op: string @param op: Operator """ if op != qlang.OP_OR: self._NeedAllNames() def NoteUnaryOp(self, op, datakind): # pylint: disable=W0613 """Called when handling an unary operation. @type op: string @param op: Operator """ if datakind is not None: self._datakinds.add(datakind) self._NeedAllNames() def NoteBinaryOp(self, op, datakind, name, value): """Called when handling a binary operation. @type op: string @param op: Operator @type name: string @param name: Left-hand side of operator (field name) @param value: Right-hand side of operator """ if datakind is not None: self._datakinds.add(datakind) if self._allnames: return # If any operator other than equality was used, all names need to be # retrieved if op == qlang.OP_EQUAL and name == self._namefield: if self._names is None: self._names = [] self._names.append(value) else: self._NeedAllNames() def _WrapLogicOp(op_fn, sentences, ctx, item): """Wrapper for logic operator functions. """ return op_fn(fn(ctx, item) for fn in sentences) def _WrapUnaryOp(op_fn, inner, ctx, item): """Wrapper for unary operator functions. """ return op_fn(inner(ctx, item)) def _WrapBinaryOp(op_fn, retrieval_fn, value, ctx, item): """Wrapper for binary operator functions. """ return op_fn(retrieval_fn(ctx, item), value) def _WrapNot(fn, lhs, rhs): """Negates the result of a wrapped function. """ return not fn(lhs, rhs) def _PrepareRegex(pattern): """Compiles a regular expression. """ try: return re.compile(pattern) except re.error, err: raise errors.ParameterError("Invalid regex pattern (%s)" % err) def _PrepareSplitTimestamp(value): """Prepares a value for comparison by L{_MakeSplitTimestampComparison}. """ if ht.TNumber(value): return value else: return utils.MergeTime(value) def _MakeSplitTimestampComparison(fn): """Compares split timestamp values after converting to float. """ return lambda lhs, rhs: fn(utils.MergeTime(lhs), rhs) def _MakeComparisonChecks(fn): """Prepares flag-specific comparisons using a comparison function. """ return [ (QFF_SPLIT_TIMESTAMP, _MakeSplitTimestampComparison(fn), _PrepareSplitTimestamp), (QFF_JOB_ID, lambda lhs, rhs: fn(jstore.ParseJobId(lhs), rhs), jstore.ParseJobId), (None, fn, None), ] class _FilterCompilerHelper: """Converts a query filter to a callable usable for filtering. """ # String statement has no effect, pylint: disable=W0105 #: How deep filters can be nested _LEVELS_MAX = 10 # Unique identifiers for operator groups (_OPTYPE_LOGIC, _OPTYPE_UNARY, _OPTYPE_BINARY) = range(1, 4) """Functions for equality checks depending on field flags. List of tuples containing flags and a callable receiving the left- and right-hand side of the operator. The flags are an OR-ed value of C{QFF_*} (e.g. L{QFF_HOSTNAME} or L{QFF_SPLIT_TIMESTAMP}). Order matters. The first item with flags will be used. Flags are checked using binary AND. """ _EQUALITY_CHECKS = [ (QFF_HOSTNAME, lambda lhs, rhs: utils.MatchNameComponent(rhs, [lhs], case_sensitive=False), None), (QFF_SPLIT_TIMESTAMP, _MakeSplitTimestampComparison(operator.eq), _PrepareSplitTimestamp), (None, operator.eq, None), ] """Known operators Operator as key (C{qlang.OP_*}), value a tuple of operator group (C{_OPTYPE_*}) and a group-specific value: - C{_OPTYPE_LOGIC}: Callable taking any number of arguments; used by L{_HandleLogicOp} - C{_OPTYPE_UNARY}: Always C{None}; details handled by L{_HandleUnaryOp} - C{_OPTYPE_BINARY}: Callable taking exactly two parameters, the left- and right-hand side of the operator, used by L{_HandleBinaryOp} """ _OPS = { # Logic operators qlang.OP_OR: (_OPTYPE_LOGIC, compat.any), qlang.OP_AND: (_OPTYPE_LOGIC, compat.all), # Unary operators qlang.OP_NOT: (_OPTYPE_UNARY, None), qlang.OP_TRUE: (_OPTYPE_UNARY, None), # Binary operators qlang.OP_EQUAL: (_OPTYPE_BINARY, _EQUALITY_CHECKS), qlang.OP_NOT_EQUAL: (_OPTYPE_BINARY, [(flags, compat.partial(_WrapNot, fn), valprepfn) for (flags, fn, valprepfn) in _EQUALITY_CHECKS]), qlang.OP_LT: (_OPTYPE_BINARY, _MakeComparisonChecks(operator.lt)), qlang.OP_LE: (_OPTYPE_BINARY, _MakeComparisonChecks(operator.le)), qlang.OP_GT: (_OPTYPE_BINARY, _MakeComparisonChecks(operator.gt)), qlang.OP_GE: (_OPTYPE_BINARY, _MakeComparisonChecks(operator.ge)), qlang.OP_REGEXP: (_OPTYPE_BINARY, [ (None, lambda lhs, rhs: rhs.search(lhs), _PrepareRegex), ]), qlang.OP_CONTAINS: (_OPTYPE_BINARY, [ (None, operator.contains, None), ]), } def __init__(self, fields): """Initializes this class. @param fields: Field definitions (return value of L{_PrepareFieldList}) """ self._fields = fields self._hints = None self._op_handler = None def __call__(self, hints, qfilter): """Converts a query filter into a callable function. @type hints: L{_FilterHints} or None @param hints: Callbacks doing analysis on filter @type qfilter: list @param qfilter: Filter structure @rtype: callable @return: Function receiving context and item as parameters, returning boolean as to whether item matches filter """ self._op_handler = { self._OPTYPE_LOGIC: (self._HandleLogicOp, getattr(hints, "NoteLogicOp", None)), self._OPTYPE_UNARY: (self._HandleUnaryOp, getattr(hints, "NoteUnaryOp", None)), self._OPTYPE_BINARY: (self._HandleBinaryOp, getattr(hints, "NoteBinaryOp", None)), } try: filter_fn = self._Compile(qfilter, 0) finally: self._op_handler = None return filter_fn def _Compile(self, qfilter, level): """Inner function for converting filters. Calls the correct handler functions for the top-level operator. This function is called recursively (e.g. for logic operators). """ if not (isinstance(qfilter, (list, tuple)) and qfilter): raise errors.ParameterError("Invalid filter on level %s" % level) # Limit recursion if level >= self._LEVELS_MAX: raise errors.ParameterError("Only up to %s levels are allowed (filter" " nested too deep)" % self._LEVELS_MAX) # Create copy to be modified operands = qfilter[:] op = operands.pop(0) try: (kind, op_data) = self._OPS[op] except KeyError: raise errors.ParameterError("Unknown operator '%s'" % op) (handler, hints_cb) = self._op_handler[kind] return handler(hints_cb, level, op, op_data, operands) def _LookupField(self, name): """Returns a field definition by name. """ try: return self._fields[name] except KeyError: raise errors.ParameterError("Unknown field '%s'" % name) def _HandleLogicOp(self, hints_fn, level, op, op_fn, operands): """Handles logic operators. @type hints_fn: callable @param hints_fn: Callback doing some analysis on the filter @type level: integer @param level: Current depth @type op: string @param op: Operator @type op_fn: callable @param op_fn: Function implementing operator @type operands: list @param operands: List of operands """ if hints_fn: hints_fn(op) return compat.partial(_WrapLogicOp, op_fn, [self._Compile(op, level + 1) for op in operands]) def _HandleUnaryOp(self, hints_fn, level, op, op_fn, operands): """Handles unary operators. @type hints_fn: callable @param hints_fn: Callback doing some analysis on the filter @type level: integer @param level: Current depth @type op: string @param op: Operator @type op_fn: callable @param op_fn: Function implementing operator @type operands: list @param operands: List of operands """ assert op_fn is None if len(operands) != 1: raise errors.ParameterError("Unary operator '%s' expects exactly one" " operand" % op) if op == qlang.OP_TRUE: (_, datakind, _, retrieval_fn) = self._LookupField(operands[0]) if hints_fn: hints_fn(op, datakind) op_fn = operator.truth arg = retrieval_fn elif op == qlang.OP_NOT: if hints_fn: hints_fn(op, None) op_fn = operator.not_ arg = self._Compile(operands[0], level + 1) else: raise errors.ProgrammerError("Can't handle operator '%s'" % op) return compat.partial(_WrapUnaryOp, op_fn, arg) def _HandleBinaryOp(self, hints_fn, level, op, op_data, operands): """Handles binary operators. @type hints_fn: callable @param hints_fn: Callback doing some analysis on the filter @type level: integer @param level: Current depth @type op: string @param op: Operator @param op_data: Functions implementing operators @type operands: list @param operands: List of operands """ # Unused arguments, pylint: disable=W0613 try: (name, value) = operands except (ValueError, TypeError): raise errors.ParameterError("Invalid binary operator, expected exactly" " two operands") (fdef, datakind, field_flags, retrieval_fn) = self._LookupField(name) assert fdef.kind != QFT_UNKNOWN # TODO: Type conversions? verify_fn = _VERIFY_FN[fdef.kind] if not verify_fn(value): raise errors.ParameterError("Unable to compare field '%s' (type '%s')" " with '%s', expected %s" % (name, fdef.kind, value.__class__.__name__, verify_fn)) if hints_fn: hints_fn(op, datakind, name, value) for (fn_flags, fn, valprepfn) in op_data: if fn_flags is None or fn_flags & field_flags: # Prepare value if necessary (e.g. compile regular expression) if valprepfn: value = valprepfn(value) return compat.partial(_WrapBinaryOp, fn, retrieval_fn, value) raise errors.ProgrammerError("Unable to find operator implementation" " (op '%s', flags %s)" % (op, field_flags)) def _CompileFilter(fields, hints, qfilter): """Converts a query filter into a callable function. See L{_FilterCompilerHelper} for details. @rtype: callable """ return _FilterCompilerHelper(fields)(hints, qfilter) class Query: def __init__(self, fieldlist, selected, qfilter=None, namefield=None): """Initializes this class. The field definition is a dictionary with the field's name as a key and a tuple containing, in order, the field definition object (L{objects.QueryFieldDefinition}, the data kind to help calling code collect data and a retrieval function. The retrieval function is called with two parameters, in order, the data container and the item in container (see L{Query.Query}). Users of this class can call L{RequestedData} before preparing the data container to determine what data is needed. @type fieldlist: dictionary @param fieldlist: Field definitions @type selected: list of strings @param selected: List of selected fields """ assert namefield is None or namefield in fieldlist self._fields = _GetQueryFields(fieldlist, selected) self._filter_fn = None self._requested_names = None self._filter_datakinds = frozenset() if qfilter is not None: # Collect requested names if wanted if namefield: hints = _FilterHints(namefield) else: hints = None # Build filter function self._filter_fn = _CompileFilter(fieldlist, hints, qfilter) if hints: self._requested_names = hints.RequestedNames() self._filter_datakinds = hints.ReferencedData() if namefield is None: self._name_fn = None else: (_, _, _, self._name_fn) = fieldlist[namefield] def RequestedNames(self): """Returns all names referenced in the filter. If there is no filter or operators are preventing determining the exact names, C{None} is returned. """ return self._requested_names def RequestedData(self): """Gets requested kinds of data. @rtype: frozenset """ return (self._filter_datakinds | frozenset(datakind for (_, datakind, _, _) in self._fields if datakind is not None)) def GetFields(self): """Returns the list of fields for this query. Includes unknown fields. @rtype: List of L{objects.QueryFieldDefinition} """ return GetAllFields(self._fields) def Query(self, ctx, sort_by_name=True): """Execute a query. @param ctx: Data container passed to field retrieval functions, must support iteration using C{__iter__} @type sort_by_name: boolean @param sort_by_name: Whether to sort by name or keep the input data's ordering """ sort = (self._name_fn and sort_by_name) result = [] for idx, item in enumerate(ctx): if not (self._filter_fn is None or self._filter_fn(ctx, item)): continue row = [_ProcessResult(fn(ctx, item)) for (_, _, _, fn) in self._fields] # Verify result if __debug__: _VerifyResultRow(self._fields, row) if sort: (status, name) = _ProcessResult(self._name_fn(ctx, item)) assert status == constants.RS_NORMAL # TODO: Are there cases where we wouldn't want to use NiceSort? # Answer: if the name field is non-string... result.append((utils.NiceSortKey(name), idx, row)) else: result.append(row) if not sort: return result # TODO: Would "heapq" be more efficient than sorting? # Sorting in-place instead of using "sorted()" result.sort() assert not result or (len(result[0]) == 3 and len(result[-1]) == 3) return map(operator.itemgetter(2), result) def OldStyleQuery(self, ctx, sort_by_name=True): """Query with "old" query result format. See L{Query.Query} for arguments. """ unknown = set(fdef.name for (fdef, _, _, _) in self._fields if fdef.kind == QFT_UNKNOWN) if unknown: raise errors.OpPrereqError("Unknown output fields selected: %s" % (utils.CommaJoin(unknown), ), errors.ECODE_INVAL) return [[value for (_, value) in row] for row in self.Query(ctx, sort_by_name=sort_by_name)] def _ProcessResult(value): """Converts result values into externally-visible ones. """ if value is _FS_UNKNOWN: return (RS_UNKNOWN, None) elif value is _FS_NODATA: return (RS_NODATA, None) elif value is _FS_UNAVAIL: return (RS_UNAVAIL, None) elif value is _FS_OFFLINE: return (RS_OFFLINE, None) else: return (RS_NORMAL, value) def _VerifyResultRow(fields, row): """Verifies the contents of a query result row. @type fields: list @param fields: Field definitions for result @type row: list of tuples @param row: Row data """ assert len(row) == len(fields) errs = [] for ((status, value), (fdef, _, _, _)) in zip(row, fields): if status == RS_NORMAL: if not _VERIFY_FN[fdef.kind](value): errs.append("normal field %s fails validation (value is %s)" % (fdef.name, value)) elif value is not None: errs.append("abnormal field %s has a non-None value" % fdef.name) assert not errs, ("Failed validation: %s in row %s" % (utils.CommaJoin(errs), row)) def _FieldDictKey((fdef, _, flags, fn)): """Generates key for field dictionary. """ assert fdef.name and fdef.title, "Name and title are required" assert FIELD_NAME_RE.match(fdef.name) assert TITLE_RE.match(fdef.title) assert (DOC_RE.match(fdef.doc) and len(fdef.doc.splitlines()) == 1 and fdef.doc.strip() == fdef.doc), \ "Invalid description for field '%s'" % fdef.name assert callable(fn) assert (flags & ~QFF_ALL) == 0, "Unknown flags for field '%s'" % fdef.name return fdef.name def _PrepareFieldList(fields, aliases): """Prepares field list for use by L{Query}. Converts the list to a dictionary and does some verification. @type fields: list of tuples; (L{objects.QueryFieldDefinition}, data kind, retrieval function) @param fields: List of fields, see L{Query.__init__} for a better description @type aliases: list of tuples; (alias, target) @param aliases: list of tuples containing aliases; for each alias/target pair, a duplicate will be created in the field list @rtype: dict @return: Field dictionary for L{Query} """ if __debug__: duplicates = utils.FindDuplicates(fdef.title.lower() for (fdef, _, _, _) in fields) assert not duplicates, "Duplicate title(s) found: %r" % duplicates result = utils.SequenceToDict(fields, key=_FieldDictKey) for alias, target in aliases: assert alias not in result, "Alias %s overrides an existing field" % alias assert target in result, "Missing target %s for alias %s" % (target, alias) (fdef, k, flags, fn) = result[target] fdef = fdef.Copy() fdef.name = alias result[alias] = (fdef, k, flags, fn) assert len(result) == len(fields) + len(aliases) assert compat.all(name == fdef.name for (name, (fdef, _, _, _)) in result.items()) return result def GetQueryResponse(query, ctx, sort_by_name=True): """Prepares the response for a query. @type query: L{Query} @param ctx: Data container, see L{Query.Query} @type sort_by_name: boolean @param sort_by_name: Whether to sort by name or keep the input data's ordering """ return objects.QueryResponse(data=query.Query(ctx, sort_by_name=sort_by_name), fields=query.GetFields()).ToDict() def QueryFields(fielddefs, selected): """Returns list of available fields. @type fielddefs: dict @param fielddefs: Field definitions @type selected: list of strings @param selected: List of selected fields @return: List of L{objects.QueryFieldDefinition} """ if selected is None: # Client requests all fields, sort by name fdefs = utils.NiceSort(GetAllFields(fielddefs.values()), key=operator.attrgetter("name")) else: # Keep order as requested by client fdefs = Query(fielddefs, selected).GetFields() return objects.QueryFieldsResponse(fields=fdefs).ToDict() def _MakeField(name, title, kind, doc): """Wrapper for creating L{objects.QueryFieldDefinition} instances. @param name: Field name as a regular expression @param title: Human-readable title @param kind: Field type @param doc: Human-readable description """ return objects.QueryFieldDefinition(name=name, title=title, kind=kind, doc=doc) def _StaticValueInner(value, ctx, _): # pylint: disable=W0613 """Returns a static value. """ return value def _StaticValue(value): """Prepares a function to return a static value. """ return compat.partial(_StaticValueInner, value) def _GetNodeRole(node, master_uuid): """Determine node role. @type node: L{objects.Node} @param node: Node object @type master_uuid: string @param master_uuid: Master node UUID """ if node.uuid == master_uuid: return constants.NR_MASTER elif node.master_candidate: return constants.NR_MCANDIDATE elif node.drained: return constants.NR_DRAINED elif node.offline: return constants.NR_OFFLINE else: return constants.NR_REGULAR def _GetItemAttr(attr): """Returns a field function to return an attribute of the item. @param attr: Attribute name """ getter = operator.attrgetter(attr) return lambda _, item: getter(item) def _GetItemMaybeAttr(attr): """Returns a field function to return a not-None attribute of the item. If the value is None, then C{_FS_UNAVAIL} will be returned instead. @param attr: Attribute name """ def _helper(_, obj): val = getattr(obj, attr) if val is None: return _FS_UNAVAIL else: return val return _helper def _GetNDParam(name): """Return a field function to return an ND parameter out of the context. """ def _helper(ctx, _): if ctx.ndparams is None: return _FS_UNAVAIL else: return ctx.ndparams.get(name, None) return _helper def _BuildNDFields(is_group): """Builds all the ndparam fields. @param is_group: whether this is called at group or node level """ if is_group: field_kind = GQ_CONFIG else: field_kind = NQ_GROUP return [(_MakeField("ndp/%s" % name, constants.NDS_PARAMETER_TITLES.get(name, "ndp/%s" % name), _VTToQFT[kind], "The \"%s\" node parameter" % name), field_kind, 0, _GetNDParam(name)) for name, kind in constants.NDS_PARAMETER_TYPES.items()] def _ConvWrapInner(convert, fn, ctx, item): """Wrapper for converting values. @param convert: Conversion function receiving value as single parameter @param fn: Retrieval function """ value = fn(ctx, item) # Is the value an abnormal status? if compat.any(value is fs for fs in _FS_ALL): # Return right away return value # TODO: Should conversion function also receive context, item or both? return convert(value) def _ConvWrap(convert, fn): """Convenience wrapper for L{_ConvWrapInner}. @param convert: Conversion function receiving value as single parameter @param fn: Retrieval function """ return compat.partial(_ConvWrapInner, convert, fn) def _GetItemTimestamp(getter): """Returns function for getting timestamp of item. @type getter: callable @param getter: Function to retrieve timestamp attribute """ def fn(_, item): """Returns a timestamp of item. """ timestamp = getter(item) if timestamp is None: # Old configs might not have all timestamps return _FS_UNAVAIL else: return timestamp return fn def _GetItemTimestampFields(datatype): """Returns common timestamp fields. @param datatype: Field data type for use by L{Query.RequestedData} """ return [ (_MakeField("ctime", "CTime", QFT_TIMESTAMP, "Creation timestamp"), datatype, 0, _GetItemTimestamp(operator.attrgetter("ctime"))), (_MakeField("mtime", "MTime", QFT_TIMESTAMP, "Modification timestamp"), datatype, 0, _GetItemTimestamp(operator.attrgetter("mtime"))), ] class NodeQueryData: """Data container for node data queries. """ def __init__(self, nodes, live_data, master_uuid, node_to_primary, node_to_secondary, inst_uuid_to_inst_name, groups, oob_support, cluster): """Initializes this class. """ self.nodes = nodes self.live_data = live_data self.master_uuid = master_uuid self.node_to_primary = node_to_primary self.node_to_secondary = node_to_secondary self.inst_uuid_to_inst_name = inst_uuid_to_inst_name self.groups = groups self.oob_support = oob_support self.cluster = cluster # Used for individual rows self.curlive_data = None self.ndparams = None def __iter__(self): """Iterate over all nodes. This function has side-effects and only one instance of the resulting generator should be used at a time. """ for node in self.nodes: group = self.groups.get(node.group, None) if group is None: self.ndparams = None else: self.ndparams = self.cluster.FillND(node, group) if self.live_data: self.curlive_data = self.live_data.get(node.uuid, None) else: self.curlive_data = None yield node #: Fields that are direct attributes of an L{objects.Node} object _NODE_SIMPLE_FIELDS = { "drained": ("Drained", QFT_BOOL, 0, "Whether node is drained"), "master_candidate": ("MasterC", QFT_BOOL, 0, "Whether node is a master candidate"), "master_capable": ("MasterCapable", QFT_BOOL, 0, "Whether node can become a master candidate"), "name": ("Node", QFT_TEXT, QFF_HOSTNAME, "Node name"), "offline": ("Offline", QFT_BOOL, 0, "Whether node is marked offline"), "serial_no": ("SerialNo", QFT_NUMBER, 0, _SERIAL_NO_DOC % "Node"), "uuid": ("UUID", QFT_TEXT, 0, "Node UUID"), "vm_capable": ("VMCapable", QFT_BOOL, 0, "Whether node can host instances"), } #: Fields requiring talking to the node # Note that none of these are available for non-vm_capable nodes _NODE_LIVE_FIELDS = { "bootid": ("BootID", QFT_TEXT, "bootid", "Random UUID renewed for each system reboot, can be used" " for detecting reboots by tracking changes"), "cnodes": ("CNodes", QFT_NUMBER, "cpu_nodes", "Number of NUMA domains on node (if exported by hypervisor)"), "cnos": ("CNOs", QFT_NUMBER, "cpu_dom0", "Number of logical processors used by the node OS (dom0 for Xen)"), "csockets": ("CSockets", QFT_NUMBER, "cpu_sockets", "Number of physical CPU sockets (if exported by hypervisor)"), "ctotal": ("CTotal", QFT_NUMBER, "cpu_total", "Number of logical processors"), "dfree": ("DFree", QFT_UNIT, "storage_free", "Available storage space in storage unit"), "dtotal": ("DTotal", QFT_UNIT, "storage_size", "Total storage space in storage unit used for instance disk" " allocation"), "spfree": ("SpFree", QFT_NUMBER, "spindles_free", "Available spindles in volume group (exclusive storage only)"), "sptotal": ("SpTotal", QFT_NUMBER, "spindles_total", "Total spindles in volume group (exclusive storage only)"), "mfree": ("MFree", QFT_UNIT, "memory_free", "Memory available for instance allocations"), "mnode": ("MNode", QFT_UNIT, "memory_dom0", "Amount of memory used by node (dom0 for Xen)"), "mtotal": ("MTotal", QFT_UNIT, "memory_total", "Total amount of memory of physical machine"), } def _GetGroup(cb): """Build function for calling another function with an node group. @param cb: The callback to be called with the nodegroup """ def fn(ctx, node): """Get group data for a node. @type ctx: L{NodeQueryData} @type inst: L{objects.Node} @param inst: Node object """ ng = ctx.groups.get(node.group, None) if ng is None: # Nodes always have a group, or the configuration is corrupt return _FS_UNAVAIL return cb(ctx, node, ng) return fn def _GetNodeGroup(ctx, node, ng): # pylint: disable=W0613 """Returns the name of a node's group. @type ctx: L{NodeQueryData} @type node: L{objects.Node} @param node: Node object @type ng: L{objects.NodeGroup} @param ng: The node group this node belongs to """ return ng.name def _GetNodePower(ctx, node): """Returns the node powered state @type ctx: L{NodeQueryData} @type node: L{objects.Node} @param node: Node object """ if ctx.oob_support[node.uuid]: return node.powered return _FS_UNAVAIL def _GetNdParams(ctx, node, ng): """Returns the ndparams for this node. @type ctx: L{NodeQueryData} @type node: L{objects.Node} @param node: Node object @type ng: L{objects.NodeGroup} @param ng: The node group this node belongs to """ return ctx.cluster.SimpleFillND(ng.FillND(node)) def _GetLiveNodeField(field, kind, ctx, node): """Gets the value of a "live" field from L{NodeQueryData}. @param field: Live field name @param kind: Data kind, one of L{constants.QFT_ALL} @type ctx: L{NodeQueryData} @type node: L{objects.Node} @param node: Node object """ if node.offline: return _FS_OFFLINE if not node.vm_capable: return _FS_UNAVAIL if not ctx.curlive_data: return _FS_NODATA return _GetStatsField(field, kind, ctx.curlive_data) def _GetStatsField(field, kind, data): """Gets a value from live statistics. If the value is not found, L{_FS_UNAVAIL} is returned. If the field kind is numeric a conversion to integer is attempted. If that fails, L{_FS_UNAVAIL} is returned. @param field: Live field name @param kind: Data kind, one of L{constants.QFT_ALL} @type data: dict @param data: Statistics """ try: value = data[field] except KeyError: return _FS_UNAVAIL if kind == QFT_TEXT: return value assert kind in (QFT_NUMBER, QFT_UNIT) # Try to convert into number try: return int(value) except (ValueError, TypeError): logging.exception("Failed to convert node field '%s' (value %r) to int", field, value) return _FS_UNAVAIL def _GetNodeHvState(_, node): """Converts node's hypervisor state for query result. """ hv_state = node.hv_state if hv_state is None: return _FS_UNAVAIL return dict((name, value.ToDict()) for (name, value) in hv_state.items()) def _GetNodeDiskState(_, node): """Converts node's disk state for query result. """ disk_state = node.disk_state if disk_state is None: return _FS_UNAVAIL return dict((disk_kind, dict((name, value.ToDict()) for (name, value) in kind_state.items())) for (disk_kind, kind_state) in disk_state.items()) def _BuildNodeFields(): """Builds list of fields for node queries. """ fields = [ (_MakeField("pip", "PrimaryIP", QFT_TEXT, "Primary IP address"), NQ_CONFIG, 0, _GetItemAttr("primary_ip")), (_MakeField("sip", "SecondaryIP", QFT_TEXT, "Secondary IP address"), NQ_CONFIG, 0, _GetItemAttr("secondary_ip")), (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), NQ_CONFIG, 0, lambda ctx, node: list(node.GetTags())), (_MakeField("master", "IsMaster", QFT_BOOL, "Whether node is master"), NQ_CONFIG, 0, lambda ctx, node: node.uuid == ctx.master_uuid), (_MakeField("group", "Group", QFT_TEXT, "Node group"), NQ_GROUP, 0, _GetGroup(_GetNodeGroup)), (_MakeField("group.uuid", "GroupUUID", QFT_TEXT, "UUID of node group"), NQ_CONFIG, 0, _GetItemAttr("group")), (_MakeField("powered", "Powered", QFT_BOOL, "Whether node is thought to be powered on"), NQ_OOB, 0, _GetNodePower), (_MakeField("ndparams", "NodeParameters", QFT_OTHER, "Merged node parameters"), NQ_GROUP, 0, _GetGroup(_GetNdParams)), (_MakeField("custom_ndparams", "CustomNodeParameters", QFT_OTHER, "Custom node parameters"), NQ_GROUP, 0, _GetItemAttr("ndparams")), (_MakeField("hv_state", "HypervisorState", QFT_OTHER, "Hypervisor state"), NQ_CONFIG, 0, _GetNodeHvState), (_MakeField("disk_state", "DiskState", QFT_OTHER, "Disk state"), NQ_CONFIG, 0, _GetNodeDiskState), ] fields.extend(_BuildNDFields(False)) # Node role role_values = (constants.NR_MASTER, constants.NR_MCANDIDATE, constants.NR_REGULAR, constants.NR_DRAINED, constants.NR_OFFLINE) role_doc = ("Node role; \"%s\" for master, \"%s\" for master candidate," " \"%s\" for regular, \"%s\" for drained, \"%s\" for offline" % role_values) fields.append((_MakeField("role", "Role", QFT_TEXT, role_doc), NQ_CONFIG, 0, lambda ctx, node: _GetNodeRole(node, ctx.master_uuid))) assert set(role_values) == constants.NR_ALL def _GetLength(getter): return lambda ctx, node: len(getter(ctx)[node.uuid]) def _GetList(getter): return lambda ctx, node: utils.NiceSort( [ctx.inst_uuid_to_inst_name[uuid] for uuid in getter(ctx)[node.uuid]]) # Add fields operating on instance lists for prefix, titleprefix, docword, getter in \ [("p", "Pri", "primary", operator.attrgetter("node_to_primary")), ("s", "Sec", "secondary", operator.attrgetter("node_to_secondary"))]: # TODO: Allow filterting by hostname in list fields.extend([ (_MakeField("%sinst_cnt" % prefix, "%sinst" % prefix.upper(), QFT_NUMBER, "Number of instances with this node as %s" % docword), NQ_INST, 0, _GetLength(getter)), (_MakeField("%sinst_list" % prefix, "%sInstances" % titleprefix, QFT_OTHER, "List of instances with this node as %s" % docword), NQ_INST, 0, _GetList(getter)), ]) # Add simple fields fields.extend([ (_MakeField(name, title, kind, doc), NQ_CONFIG, flags, _GetItemAttr(name)) for (name, (title, kind, flags, doc)) in _NODE_SIMPLE_FIELDS.items()]) # Add fields requiring live data fields.extend([ (_MakeField(name, title, kind, doc), NQ_LIVE, 0, compat.partial(_GetLiveNodeField, nfield, kind)) for (name, (title, kind, nfield, doc)) in _NODE_LIVE_FIELDS.items()]) # Add timestamps fields.extend(_GetItemTimestampFields(NQ_CONFIG)) return _PrepareFieldList(fields, []) class InstanceQueryData: """Data container for instance data queries. """ def __init__(self, instances, cluster, disk_usage, offline_node_uuids, bad_node_uuids, live_data, wrongnode_inst, console, nodes, groups, networks): """Initializes this class. @param instances: List of instance objects @param cluster: Cluster object @type disk_usage: dict; instance UUID as key @param disk_usage: Per-instance disk usage @type offline_node_uuids: list of strings @param offline_node_uuids: List of offline nodes @type bad_node_uuids: list of strings @param bad_node_uuids: List of faulty nodes @type live_data: dict; instance UUID as key @param live_data: Per-instance live data @type wrongnode_inst: set @param wrongnode_inst: Set of instances running on wrong node(s) @type console: dict; instance UUID as key @param console: Per-instance console information @type nodes: dict; node UUID as key @param nodes: Node objects @type networks: dict; net_uuid as key @param networks: Network objects """ assert len(set(bad_node_uuids) & set(offline_node_uuids)) == \ len(offline_node_uuids), \ "Offline nodes not included in bad nodes" assert not (set(live_data.keys()) & set(bad_node_uuids)), \ "Found live data for bad or offline nodes" self.instances = instances self.cluster = cluster self.disk_usage = disk_usage self.offline_nodes = offline_node_uuids self.bad_nodes = bad_node_uuids self.live_data = live_data self.wrongnode_inst = wrongnode_inst self.console = console self.nodes = nodes self.groups = groups self.networks = networks # Used for individual rows self.inst_hvparams = None self.inst_beparams = None self.inst_osparams = None self.inst_nicparams = None def __iter__(self): """Iterate over all instances. This function has side-effects and only one instance of the resulting generator should be used at a time. """ for inst in self.instances: self.inst_hvparams = self.cluster.FillHV(inst, skip_globals=True) self.inst_beparams = self.cluster.FillBE(inst) self.inst_osparams = self.cluster.SimpleFillOS(inst.os, inst.osparams) self.inst_nicparams = [self.cluster.SimpleFillNIC(nic.nicparams) for nic in inst.nics] yield inst def _GetInstOperState(ctx, inst): """Get instance's operational status. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ # Can't use RS_OFFLINE here as it would describe the instance to # be offline when we actually don't know due to missing data if inst.primary_node in ctx.bad_nodes: return _FS_NODATA else: return bool(ctx.live_data.get(inst.uuid)) def _GetInstLiveData(name): """Build function for retrieving live data. @type name: string @param name: Live data field name """ def fn(ctx, inst): """Get live data for an instance. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ if (inst.primary_node in ctx.bad_nodes or inst.primary_node in ctx.offline_nodes): # Can't use RS_OFFLINE here as it would describe the instance to be # offline when we actually don't know due to missing data return _FS_NODATA if inst.uuid in ctx.live_data: data = ctx.live_data[inst.uuid] if name in data: return data[name] return _FS_UNAVAIL return fn def _GetInstStatus(ctx, inst): """Get instance status. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ if inst.primary_node in ctx.offline_nodes: return constants.INSTST_NODEOFFLINE if inst.primary_node in ctx.bad_nodes: return constants.INSTST_NODEDOWN if bool(ctx.live_data.get(inst.uuid)): if inst.uuid in ctx.wrongnode_inst: return constants.INSTST_WRONGNODE elif inst.admin_state == constants.ADMINST_UP: return constants.INSTST_RUNNING else: return constants.INSTST_ERRORUP if inst.admin_state == constants.ADMINST_UP: return constants.INSTST_ERRORDOWN elif inst.admin_state == constants.ADMINST_DOWN: return constants.INSTST_ADMINDOWN return constants.INSTST_ADMINOFFLINE def _GetInstDisk(index, cb): """Build function for calling another function with an instance Disk. @type index: int @param index: Disk index @type cb: callable @param cb: Callback """ def fn(ctx, inst): """Call helper function with instance Disk. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ try: nic = inst.disks[index] except IndexError: return _FS_UNAVAIL return cb(ctx, index, nic) return fn def _GetInstDiskSize(ctx, _, disk): # pylint: disable=W0613 """Get a Disk's size. @type ctx: L{InstanceQueryData} @type disk: L{objects.Disk} @param disk: The Disk object """ if disk.size is None: return _FS_UNAVAIL else: return disk.size def _GetInstDiskSpindles(ctx, _, disk): # pylint: disable=W0613 """Get a Disk's spindles. @type disk: L{objects.Disk} @param disk: The Disk object """ if disk.spindles is None: return _FS_UNAVAIL else: return disk.spindles def _GetInstDeviceName(ctx, _, device): # pylint: disable=W0613 """Get a Device's Name. @type ctx: L{InstanceQueryData} @type device: L{objects.NIC} or L{objects.Disk} @param device: The NIC or Disk object """ if device.name is None: return _FS_UNAVAIL else: return device.name def _GetInstDeviceUUID(ctx, _, device): # pylint: disable=W0613 """Get a Device's UUID. @type ctx: L{InstanceQueryData} @type device: L{objects.NIC} or L{objects.Disk} @param device: The NIC or Disk object """ if device.uuid is None: return _FS_UNAVAIL else: return device.uuid def _GetInstNic(index, cb): """Build function for calling another function with an instance NIC. @type index: int @param index: NIC index @type cb: callable @param cb: Callback """ def fn(ctx, inst): """Call helper function with instance NIC. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ try: nic = inst.nics[index] except IndexError: return _FS_UNAVAIL return cb(ctx, index, nic) return fn def _GetInstNicNetworkName(ctx, _, nic): # pylint: disable=W0613 """Get a NIC's Network. @type ctx: L{InstanceQueryData} @type nic: L{objects.NIC} @param nic: NIC object """ if nic.network is None: return _FS_UNAVAIL else: return ctx.networks[nic.network].name def _GetInstNicNetwork(ctx, _, nic): # pylint: disable=W0613 """Get a NIC's Network. @type ctx: L{InstanceQueryData} @type nic: L{objects.NIC} @param nic: NIC object """ if nic.network is None: return _FS_UNAVAIL else: return nic.network def _GetInstNicIp(ctx, _, nic): # pylint: disable=W0613 """Get a NIC's IP address. @type ctx: L{InstanceQueryData} @type nic: L{objects.NIC} @param nic: NIC object """ if nic.ip is None: return _FS_UNAVAIL else: return nic.ip def _GetInstNicBridge(ctx, index, _): """Get a NIC's bridge. @type ctx: L{InstanceQueryData} @type index: int @param index: NIC index """ assert len(ctx.inst_nicparams) >= index nicparams = ctx.inst_nicparams[index] if nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED: return nicparams[constants.NIC_LINK] else: return _FS_UNAVAIL def _GetInstNicVLan(ctx, index, _): """Get a NIC's VLAN. @type ctx: L{InstanceQueryData} @type index: int @param index: NIC index """ assert len(ctx.inst_nicparams) >= index nicparams = ctx.inst_nicparams[index] if nicparams[constants.NIC_MODE] == constants.NIC_MODE_OVS: return nicparams[constants.NIC_VLAN] else: return _FS_UNAVAIL def _GetInstAllNicNetworkNames(ctx, inst): """Get all network names for an instance. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ result = [] for nic in inst.nics: name = None if nic.network: name = ctx.networks[nic.network].name result.append(name) assert len(result) == len(inst.nics) return result def _GetInstAllNicBridges(ctx, inst): """Get all network bridges for an instance. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ assert len(ctx.inst_nicparams) == len(inst.nics) result = [] for nicp in ctx.inst_nicparams: if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED: result.append(nicp[constants.NIC_LINK]) else: result.append(None) assert len(result) == len(inst.nics) return result def _GetInstAllNicVlans(ctx, inst): """Get all network VLANs of an instance. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ assert len(ctx.inst_nicparams) == len(inst.nics) result = [] for nicp in ctx.inst_nicparams: if nicp[constants.NIC_MODE] == constants.NIC_MODE_OVS: result.append(nicp[constants.NIC_VLAN]) else: result.append(None) assert len(result) == len(inst.nics) return result def _GetInstNicParam(name): """Build function for retrieving a NIC parameter. @type name: string @param name: Parameter name """ def fn(ctx, index, _): """Get a NIC's bridge. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object @type nic: L{objects.NIC} @param nic: NIC object """ assert len(ctx.inst_nicparams) >= index return ctx.inst_nicparams[index][name] return fn def _GetInstanceNetworkFields(): """Get instance fields involving network interfaces. @return: Tuple containing list of field definitions used as input for L{_PrepareFieldList} and a list of aliases """ nic_mac_fn = lambda ctx, _, nic: nic.mac nic_mode_fn = _GetInstNicParam(constants.NIC_MODE) nic_link_fn = _GetInstNicParam(constants.NIC_LINK) fields = [ # All NICs (_MakeField("nic.count", "NICs", QFT_NUMBER, "Number of network interfaces"), IQ_CONFIG, 0, lambda ctx, inst: len(inst.nics)), (_MakeField("nic.macs", "NIC_MACs", QFT_OTHER, "List containing each network interface's MAC address"), IQ_CONFIG, 0, lambda ctx, inst: [nic.mac for nic in inst.nics]), (_MakeField("nic.ips", "NIC_IPs", QFT_OTHER, "List containing each network interface's IP address"), IQ_CONFIG, 0, lambda ctx, inst: [nic.ip for nic in inst.nics]), (_MakeField("nic.names", "NIC_Names", QFT_OTHER, "List containing each network interface's name"), IQ_CONFIG, 0, lambda ctx, inst: [nic.name for nic in inst.nics]), (_MakeField("nic.uuids", "NIC_UUIDs", QFT_OTHER, "List containing each network interface's UUID"), IQ_CONFIG, 0, lambda ctx, inst: [nic.uuid for nic in inst.nics]), (_MakeField("nic.modes", "NIC_modes", QFT_OTHER, "List containing each network interface's mode"), IQ_CONFIG, 0, lambda ctx, inst: [nicp[constants.NIC_MODE] for nicp in ctx.inst_nicparams]), (_MakeField("nic.links", "NIC_links", QFT_OTHER, "List containing each network interface's link"), IQ_CONFIG, 0, lambda ctx, inst: [nicp[constants.NIC_LINK] for nicp in ctx.inst_nicparams]), (_MakeField("nic.vlans", "NIC_VLANs", QFT_OTHER, "List containing each network interface's VLAN"), IQ_CONFIG, 0, _GetInstAllNicVlans), (_MakeField("nic.bridges", "NIC_bridges", QFT_OTHER, "List containing each network interface's bridge"), IQ_CONFIG, 0, _GetInstAllNicBridges), (_MakeField("nic.networks", "NIC_networks", QFT_OTHER, "List containing each interface's network"), IQ_CONFIG, 0, lambda ctx, inst: [nic.network for nic in inst.nics]), (_MakeField("nic.networks.names", "NIC_networks_names", QFT_OTHER, "List containing each interface's network"), IQ_NETWORKS, 0, _GetInstAllNicNetworkNames) ] # NICs by number for i in range(constants.MAX_NICS): numtext = utils.FormatOrdinal(i + 1) fields.extend([ (_MakeField("nic.ip/%s" % i, "NicIP/%s" % i, QFT_TEXT, "IP address of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, _GetInstNicIp)), (_MakeField("nic.mac/%s" % i, "NicMAC/%s" % i, QFT_TEXT, "MAC address of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, nic_mac_fn)), (_MakeField("nic.name/%s" % i, "NicName/%s" % i, QFT_TEXT, "Name address of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, _GetInstDeviceName)), (_MakeField("nic.uuid/%s" % i, "NicUUID/%s" % i, QFT_TEXT, "UUID address of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, _GetInstDeviceUUID)), (_MakeField("nic.mode/%s" % i, "NicMode/%s" % i, QFT_TEXT, "Mode of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, nic_mode_fn)), (_MakeField("nic.link/%s" % i, "NicLink/%s" % i, QFT_TEXT, "Link of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, nic_link_fn)), (_MakeField("nic.bridge/%s" % i, "NicBridge/%s" % i, QFT_TEXT, "Bridge of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, _GetInstNicBridge)), (_MakeField("nic.vlan/%s" % i, "NicVLAN/%s" % i, QFT_TEXT, "VLAN of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, _GetInstNicVLan)), (_MakeField("nic.network/%s" % i, "NicNetwork/%s" % i, QFT_TEXT, "Network of %s network interface" % numtext), IQ_CONFIG, 0, _GetInstNic(i, _GetInstNicNetwork)), (_MakeField("nic.network.name/%s" % i, "NicNetworkName/%s" % i, QFT_TEXT, "Network name of %s network interface" % numtext), IQ_NETWORKS, 0, _GetInstNic(i, _GetInstNicNetworkName)), ]) aliases = [ # Legacy fields for first NIC ("ip", "nic.ip/0"), ("mac", "nic.mac/0"), ("bridge", "nic.bridge/0"), ("nic_mode", "nic.mode/0"), ("nic_link", "nic.link/0"), ("nic_network", "nic.network/0"), ] return (fields, aliases) def _GetInstDiskUsage(ctx, inst): """Get disk usage for an instance. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ usage = ctx.disk_usage[inst.uuid] if usage is None: usage = 0 return usage def _GetInstanceConsole(ctx, inst): """Get console information for instance. @type ctx: L{InstanceQueryData} @type inst: L{objects.Instance} @param inst: Instance object """ consinfo = ctx.console[inst.uuid] if consinfo is None: return _FS_UNAVAIL return consinfo def _GetInstanceDiskFields(): """Get instance fields involving disks. @return: List of field definitions used as input for L{_PrepareFieldList} """ fields = [ (_MakeField("disk_usage", "DiskUsage", QFT_UNIT, "Total disk space used by instance on each of its nodes;" " this is not the disk size visible to the instance, but" " the usage on the node"), IQ_DISKUSAGE, 0, _GetInstDiskUsage), (_MakeField("disk.count", "Disks", QFT_NUMBER, "Number of disks"), IQ_CONFIG, 0, lambda ctx, inst: len(inst.disks)), (_MakeField("disk.sizes", "Disk_sizes", QFT_OTHER, "List of disk sizes"), IQ_CONFIG, 0, lambda ctx, inst: [disk.size for disk in inst.disks]), (_MakeField("disk.spindles", "Disk_spindles", QFT_OTHER, "List of disk spindles"), IQ_CONFIG, 0, lambda ctx, inst: [disk.spindles for disk in inst.disks]), (_MakeField("disk.names", "Disk_names", QFT_OTHER, "List of disk names"), IQ_CONFIG, 0, lambda ctx, inst: [disk.name for disk in inst.disks]), (_MakeField("disk.uuids", "Disk_UUIDs", QFT_OTHER, "List of disk UUIDs"), IQ_CONFIG, 0, lambda ctx, inst: [disk.uuid for disk in inst.disks]), ] # Disks by number for i in range(constants.MAX_DISKS): numtext = utils.FormatOrdinal(i + 1) fields.extend([ (_MakeField("disk.size/%s" % i, "Disk/%s" % i, QFT_UNIT, "Disk size of %s disk" % numtext), IQ_CONFIG, 0, _GetInstDisk(i, _GetInstDiskSize)), (_MakeField("disk.spindles/%s" % i, "DiskSpindles/%s" % i, QFT_NUMBER, "Spindles of %s disk" % numtext), IQ_CONFIG, 0, _GetInstDisk(i, _GetInstDiskSpindles)), (_MakeField("disk.name/%s" % i, "DiskName/%s" % i, QFT_TEXT, "Name of %s disk" % numtext), IQ_CONFIG, 0, _GetInstDisk(i, _GetInstDeviceName)), (_MakeField("disk.uuid/%s" % i, "DiskUUID/%s" % i, QFT_TEXT, "UUID of %s disk" % numtext), IQ_CONFIG, 0, _GetInstDisk(i, _GetInstDeviceUUID))]) return fields def _GetInstanceParameterFields(): """Get instance fields involving parameters. @return: List of field definitions used as input for L{_PrepareFieldList} """ fields = [ # Filled parameters (_MakeField("hvparams", "HypervisorParameters", QFT_OTHER, "Hypervisor parameters (merged)"), IQ_CONFIG, 0, lambda ctx, _: ctx.inst_hvparams), (_MakeField("beparams", "BackendParameters", QFT_OTHER, "Backend parameters (merged)"), IQ_CONFIG, 0, lambda ctx, _: ctx.inst_beparams), (_MakeField("osparams", "OpSysParameters", QFT_OTHER, "Operating system parameters (merged)"), IQ_CONFIG, 0, lambda ctx, _: ctx.inst_osparams), # Unfilled parameters (_MakeField("custom_hvparams", "CustomHypervisorParameters", QFT_OTHER, "Custom hypervisor parameters"), IQ_CONFIG, 0, _GetItemAttr("hvparams")), (_MakeField("custom_beparams", "CustomBackendParameters", QFT_OTHER, "Custom backend parameters",), IQ_CONFIG, 0, _GetItemAttr("beparams")), (_MakeField("custom_osparams", "CustomOpSysParameters", QFT_OTHER, "Custom operating system parameters",), IQ_CONFIG, 0, _GetItemAttr("osparams")), (_MakeField("custom_nicparams", "CustomNicParameters", QFT_OTHER, "Custom network interface parameters"), IQ_CONFIG, 0, lambda ctx, inst: [nic.nicparams for nic in inst.nics]), ] # HV params def _GetInstHvParam(name): return lambda ctx, _: ctx.inst_hvparams.get(name, _FS_UNAVAIL) fields.extend([ (_MakeField("hv/%s" % name, constants.HVS_PARAMETER_TITLES.get(name, "hv/%s" % name), _VTToQFT[kind], "The \"%s\" hypervisor parameter" % name), IQ_CONFIG, 0, _GetInstHvParam(name)) for name, kind in constants.HVS_PARAMETER_TYPES.items() if name not in constants.HVC_GLOBALS]) # BE params def _GetInstBeParam(name): return lambda ctx, _: ctx.inst_beparams.get(name, None) fields.extend([ (_MakeField("be/%s" % name, constants.BES_PARAMETER_TITLES.get(name, "be/%s" % name), _VTToQFT[kind], "The \"%s\" backend parameter" % name), IQ_CONFIG, 0, _GetInstBeParam(name)) for name, kind in constants.BES_PARAMETER_TYPES.items()]) return fields _INST_SIMPLE_FIELDS = { "disk_template": ("Disk_template", QFT_TEXT, 0, "Instance disk template"), "hypervisor": ("Hypervisor", QFT_TEXT, 0, "Hypervisor name"), "name": ("Instance", QFT_TEXT, QFF_HOSTNAME, "Instance name"), # Depending on the hypervisor, the port can be None "network_port": ("Network_port", QFT_OTHER, 0, "Instance network port if available (e.g. for VNC console)"), "os": ("OS", QFT_TEXT, 0, "Operating system"), "serial_no": ("SerialNo", QFT_NUMBER, 0, _SERIAL_NO_DOC % "Instance"), "uuid": ("UUID", QFT_TEXT, 0, "Instance UUID"), } def _GetNodeName(ctx, default, node_uuid): """Gets node name of a node. @type ctx: L{InstanceQueryData} @param default: Default value @type node_uuid: string @param node_uuid: Node UUID """ try: node = ctx.nodes[node_uuid] except KeyError: return default else: return node.name def _GetInstNodeGroup(ctx, default, node_uuid): """Gets group UUID of an instance node. @type ctx: L{InstanceQueryData} @param default: Default value @type node_uuid: string @param node_uuid: Node UUID """ try: node = ctx.nodes[node_uuid] except KeyError: return default else: return node.group def _GetInstNodeGroupName(ctx, default, node_uuid): """Gets group name of an instance node. @type ctx: L{InstanceQueryData} @param default: Default value @type node_uuid: string @param node_uuid: Node UUID """ try: node = ctx.nodes[node_uuid] except KeyError: return default try: group = ctx.groups[node.group] except KeyError: return default return group.name def _BuildInstanceFields(): """Builds list of fields for instance queries. """ fields = [ (_MakeField("pnode", "Primary_node", QFT_TEXT, "Primary node"), IQ_NODES, QFF_HOSTNAME, lambda ctx, inst: _GetNodeName(ctx, None, inst.primary_node)), (_MakeField("pnode.group", "PrimaryNodeGroup", QFT_TEXT, "Primary node's group"), IQ_NODES, 0, lambda ctx, inst: _GetInstNodeGroupName(ctx, _FS_UNAVAIL, inst.primary_node)), (_MakeField("pnode.group.uuid", "PrimaryNodeGroupUUID", QFT_TEXT, "Primary node's group UUID"), IQ_NODES, 0, lambda ctx, inst: _GetInstNodeGroup(ctx, _FS_UNAVAIL, inst.primary_node)), # TODO: Allow filtering by secondary node as hostname (_MakeField("snodes", "Secondary_Nodes", QFT_OTHER, "Secondary nodes; usually this will just be one node"), IQ_NODES, 0, lambda ctx, inst: map(compat.partial(_GetNodeName, ctx, None), inst.secondary_nodes)), (_MakeField("snodes.group", "SecondaryNodesGroups", QFT_OTHER, "Node groups of secondary nodes"), IQ_NODES, 0, lambda ctx, inst: map(compat.partial(_GetInstNodeGroupName, ctx, None), inst.secondary_nodes)), (_MakeField("snodes.group.uuid", "SecondaryNodesGroupsUUID", QFT_OTHER, "Node group UUIDs of secondary nodes"), IQ_NODES, 0, lambda ctx, inst: map(compat.partial(_GetInstNodeGroup, ctx, None), inst.secondary_nodes)), (_MakeField("admin_state", "InstanceState", QFT_TEXT, "Desired state of instance"), IQ_CONFIG, 0, _GetItemAttr("admin_state")), (_MakeField("admin_up", "Autostart", QFT_BOOL, "Desired state of instance"), IQ_CONFIG, 0, lambda ctx, inst: inst.admin_state == constants.ADMINST_UP), (_MakeField("disks_active", "DisksActive", QFT_BOOL, "Desired state of instance disks"), IQ_CONFIG, 0, _GetItemAttr("disks_active")), (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), IQ_CONFIG, 0, lambda ctx, inst: list(inst.GetTags())), (_MakeField("console", "Console", QFT_OTHER, "Instance console information"), IQ_CONSOLE, 0, _GetInstanceConsole), ] # Add simple fields fields.extend([ (_MakeField(name, title, kind, doc), IQ_CONFIG, flags, _GetItemAttr(name)) for (name, (title, kind, flags, doc)) in _INST_SIMPLE_FIELDS.items()]) # Fields requiring talking to the node fields.extend([ (_MakeField("oper_state", "Running", QFT_BOOL, "Actual state of instance"), IQ_LIVE, 0, _GetInstOperState), (_MakeField("oper_ram", "Memory", QFT_UNIT, "Actual memory usage as seen by hypervisor"), IQ_LIVE, 0, _GetInstLiveData("memory")), (_MakeField("oper_vcpus", "VCPUs", QFT_NUMBER, "Actual number of VCPUs as seen by hypervisor"), IQ_LIVE, 0, _GetInstLiveData("vcpus")), ]) # Status field status_values = (constants.INSTST_RUNNING, constants.INSTST_ADMINDOWN, constants.INSTST_WRONGNODE, constants.INSTST_ERRORUP, constants.INSTST_ERRORDOWN, constants.INSTST_NODEDOWN, constants.INSTST_NODEOFFLINE, constants.INSTST_ADMINOFFLINE) status_doc = ("Instance status; \"%s\" if instance is set to be running" " and actually is, \"%s\" if instance is stopped and" " is not running, \"%s\" if instance running, but not on its" " designated primary node, \"%s\" if instance should be" " stopped, but is actually running, \"%s\" if instance should" " run, but doesn't, \"%s\" if instance's primary node is down," " \"%s\" if instance's primary node is marked offline," " \"%s\" if instance is offline and does not use dynamic" " resources" % status_values) fields.append((_MakeField("status", "Status", QFT_TEXT, status_doc), IQ_LIVE, 0, _GetInstStatus)) assert set(status_values) == constants.INSTST_ALL, \ "Status documentation mismatch" (network_fields, network_aliases) = _GetInstanceNetworkFields() fields.extend(network_fields) fields.extend(_GetInstanceParameterFields()) fields.extend(_GetInstanceDiskFields()) fields.extend(_GetItemTimestampFields(IQ_CONFIG)) aliases = [ ("vcpus", "be/vcpus"), ("be/memory", "be/maxmem"), ("sda_size", "disk.size/0"), ("sdb_size", "disk.size/1"), ] + network_aliases return _PrepareFieldList(fields, aliases) class LockQueryData: """Data container for lock data queries. """ def __init__(self, lockdata): """Initializes this class. """ self.lockdata = lockdata def __iter__(self): """Iterate over all locks. """ return iter(self.lockdata) def _GetLockOwners(_, data): """Returns a sorted list of a lock's current owners. """ (_, _, owners, _) = data if owners: owners = utils.NiceSort(owners) return owners def _GetLockPending(_, data): """Returns a sorted list of a lock's pending acquires. """ (_, _, _, pending) = data if pending: pending = [(mode, utils.NiceSort(names)) for (mode, names) in pending] return pending def _BuildLockFields(): """Builds list of fields for lock queries. """ return _PrepareFieldList([ # TODO: Lock names are not always hostnames. Should QFF_HOSTNAME be used? (_MakeField("name", "Name", QFT_TEXT, "Lock name"), None, 0, lambda ctx, (name, mode, owners, pending): name), (_MakeField("mode", "Mode", QFT_OTHER, "Mode in which the lock is currently acquired" " (exclusive or shared)"), LQ_MODE, 0, lambda ctx, (name, mode, owners, pending): mode), (_MakeField("owner", "Owner", QFT_OTHER, "Current lock owner(s)"), LQ_OWNER, 0, _GetLockOwners), (_MakeField("pending", "Pending", QFT_OTHER, "Threads waiting for the lock"), LQ_PENDING, 0, _GetLockPending), ], []) class GroupQueryData: """Data container for node group data queries. """ def __init__(self, cluster, groups, group_to_nodes, group_to_instances, want_diskparams): """Initializes this class. @param cluster: Cluster object @param groups: List of node group objects @type group_to_nodes: dict; group UUID as key @param group_to_nodes: Per-group list of nodes @type group_to_instances: dict; group UUID as key @param group_to_instances: Per-group list of (primary) instances @type want_diskparams: bool @param want_diskparams: Whether diskparamters should be calculated """ self.groups = groups self.group_to_nodes = group_to_nodes self.group_to_instances = group_to_instances self.cluster = cluster self.want_diskparams = want_diskparams # Used for individual rows self.group_ipolicy = None self.ndparams = None self.group_dp = None def __iter__(self): """Iterate over all node groups. This function has side-effects and only one instance of the resulting generator should be used at a time. """ for group in self.groups: self.group_ipolicy = self.cluster.SimpleFillIPolicy(group.ipolicy) self.ndparams = self.cluster.SimpleFillND(group.ndparams) if self.want_diskparams: self.group_dp = self.cluster.SimpleFillDP(group.diskparams) else: self.group_dp = None yield group _GROUP_SIMPLE_FIELDS = { "alloc_policy": ("AllocPolicy", QFT_TEXT, "Allocation policy for group"), "name": ("Group", QFT_TEXT, "Group name"), "serial_no": ("SerialNo", QFT_NUMBER, _SERIAL_NO_DOC % "Group"), "uuid": ("UUID", QFT_TEXT, "Group UUID"), } def _BuildGroupFields(): """Builds list of fields for node group queries. """ # Add simple fields fields = [(_MakeField(name, title, kind, doc), GQ_CONFIG, 0, _GetItemAttr(name)) for (name, (title, kind, doc)) in _GROUP_SIMPLE_FIELDS.items()] def _GetLength(getter): return lambda ctx, group: len(getter(ctx)[group.uuid]) def _GetSortedList(getter): return lambda ctx, group: utils.NiceSort(getter(ctx)[group.uuid]) group_to_nodes = operator.attrgetter("group_to_nodes") group_to_instances = operator.attrgetter("group_to_instances") # Add fields for nodes fields.extend([ (_MakeField("node_cnt", "Nodes", QFT_NUMBER, "Number of nodes"), GQ_NODE, 0, _GetLength(group_to_nodes)), (_MakeField("node_list", "NodeList", QFT_OTHER, "List of nodes"), GQ_NODE, 0, _GetSortedList(group_to_nodes)), ]) # Add fields for instances fields.extend([ (_MakeField("pinst_cnt", "Instances", QFT_NUMBER, "Number of primary instances"), GQ_INST, 0, _GetLength(group_to_instances)), (_MakeField("pinst_list", "InstanceList", QFT_OTHER, "List of primary instances"), GQ_INST, 0, _GetSortedList(group_to_instances)), ]) # Other fields fields.extend([ (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), GQ_CONFIG, 0, lambda ctx, group: list(group.GetTags())), (_MakeField("ipolicy", "InstancePolicy", QFT_OTHER, "Instance policy limitations (merged)"), GQ_CONFIG, 0, lambda ctx, _: ctx.group_ipolicy), (_MakeField("custom_ipolicy", "CustomInstancePolicy", QFT_OTHER, "Custom instance policy limitations"), GQ_CONFIG, 0, _GetItemAttr("ipolicy")), (_MakeField("custom_ndparams", "CustomNDParams", QFT_OTHER, "Custom node parameters"), GQ_CONFIG, 0, _GetItemAttr("ndparams")), (_MakeField("ndparams", "NDParams", QFT_OTHER, "Node parameters"), GQ_CONFIG, 0, lambda ctx, _: ctx.ndparams), (_MakeField("diskparams", "DiskParameters", QFT_OTHER, "Disk parameters (merged)"), GQ_DISKPARAMS, 0, lambda ctx, _: ctx.group_dp), (_MakeField("custom_diskparams", "CustomDiskParameters", QFT_OTHER, "Custom disk parameters"), GQ_CONFIG, 0, _GetItemAttr("diskparams")), ]) # ND parameters fields.extend(_BuildNDFields(True)) fields.extend(_GetItemTimestampFields(GQ_CONFIG)) return _PrepareFieldList(fields, []) class OsInfo(objects.ConfigObject): __slots__ = [ "name", "valid", "hidden", "blacklisted", "variants", "api_versions", "parameters", "node_status", ] def _BuildOsFields(): """Builds list of fields for operating system queries. """ fields = [ (_MakeField("name", "Name", QFT_TEXT, "Operating system name"), None, 0, _GetItemAttr("name")), (_MakeField("valid", "Valid", QFT_BOOL, "Whether operating system definition is valid"), None, 0, _GetItemAttr("valid")), (_MakeField("hidden", "Hidden", QFT_BOOL, "Whether operating system is hidden"), None, 0, _GetItemAttr("hidden")), (_MakeField("blacklisted", "Blacklisted", QFT_BOOL, "Whether operating system is blacklisted"), None, 0, _GetItemAttr("blacklisted")), (_MakeField("variants", "Variants", QFT_OTHER, "Operating system variants"), None, 0, _ConvWrap(utils.NiceSort, _GetItemAttr("variants"))), (_MakeField("api_versions", "ApiVersions", QFT_OTHER, "Operating system API versions"), None, 0, _ConvWrap(sorted, _GetItemAttr("api_versions"))), (_MakeField("parameters", "Parameters", QFT_OTHER, "Operating system parameters"), None, 0, _ConvWrap(compat.partial(utils.NiceSort, key=compat.fst), _GetItemAttr("parameters"))), (_MakeField("node_status", "NodeStatus", QFT_OTHER, "Status from node"), None, 0, _GetItemAttr("node_status")), ] return _PrepareFieldList(fields, []) class ExtStorageInfo(objects.ConfigObject): __slots__ = [ "name", "node_status", "nodegroup_status", "parameters", ] def _BuildExtStorageFields(): """Builds list of fields for extstorage provider queries. """ fields = [ (_MakeField("name", "Name", QFT_TEXT, "ExtStorage provider name"), None, 0, _GetItemAttr("name")), (_MakeField("node_status", "NodeStatus", QFT_OTHER, "Status from node"), None, 0, _GetItemAttr("node_status")), (_MakeField("nodegroup_status", "NodegroupStatus", QFT_OTHER, "Overall Nodegroup status"), None, 0, _GetItemAttr("nodegroup_status")), (_MakeField("parameters", "Parameters", QFT_OTHER, "ExtStorage provider parameters"), None, 0, _GetItemAttr("parameters")), ] return _PrepareFieldList(fields, []) def _JobUnavailInner(fn, ctx, (job_id, job)): # pylint: disable=W0613 """Return L{_FS_UNAVAIL} if job is None. When listing specifc jobs (e.g. "gnt-job list 1 2 3"), a job may not be found, in which case this function converts it to L{_FS_UNAVAIL}. """ if job is None: return _FS_UNAVAIL else: return fn(job) def _JobUnavail(inner): """Wrapper for L{_JobUnavailInner}. """ return compat.partial(_JobUnavailInner, inner) def _PerJobOpInner(fn, job): """Executes a function per opcode in a job. """ return map(fn, job.ops) def _PerJobOp(fn): """Wrapper for L{_PerJobOpInner}. """ return _JobUnavail(compat.partial(_PerJobOpInner, fn)) def _JobTimestampInner(fn, job): """Converts unavailable timestamp to L{_FS_UNAVAIL}. """ timestamp = fn(job) if timestamp is None: return _FS_UNAVAIL else: return timestamp def _JobTimestamp(fn): """Wrapper for L{_JobTimestampInner}. """ return _JobUnavail(compat.partial(_JobTimestampInner, fn)) def _BuildJobFields(): """Builds list of fields for job queries. """ fields = [ (_MakeField("id", "ID", QFT_NUMBER, "Job ID"), None, QFF_JOB_ID, lambda _, (job_id, job): job_id), (_MakeField("status", "Status", QFT_TEXT, "Job status"), None, 0, _JobUnavail(lambda job: job.CalcStatus())), (_MakeField("priority", "Priority", QFT_NUMBER, ("Current job priority (%s to %s)" % (constants.OP_PRIO_LOWEST, constants.OP_PRIO_HIGHEST))), None, 0, _JobUnavail(lambda job: job.CalcPriority())), (_MakeField("archived", "Archived", QFT_BOOL, "Whether job is archived"), JQ_ARCHIVED, 0, lambda _, (job_id, job): job.archived), (_MakeField("ops", "OpCodes", QFT_OTHER, "List of all opcodes"), None, 0, _PerJobOp(lambda op: op.input.__getstate__())), (_MakeField("opresult", "OpCode_result", QFT_OTHER, "List of opcodes results"), None, 0, _PerJobOp(operator.attrgetter("result"))), (_MakeField("opstatus", "OpCode_status", QFT_OTHER, "List of opcodes status"), None, 0, _PerJobOp(operator.attrgetter("status"))), (_MakeField("oplog", "OpCode_log", QFT_OTHER, "List of opcode output logs"), None, 0, _PerJobOp(operator.attrgetter("log"))), (_MakeField("opstart", "OpCode_start", QFT_OTHER, "List of opcode start timestamps (before acquiring locks)"), None, 0, _PerJobOp(operator.attrgetter("start_timestamp"))), (_MakeField("opexec", "OpCode_exec", QFT_OTHER, "List of opcode execution start timestamps (after acquiring" " locks)"), None, 0, _PerJobOp(operator.attrgetter("exec_timestamp"))), (_MakeField("opend", "OpCode_end", QFT_OTHER, "List of opcode execution end timestamps"), None, 0, _PerJobOp(operator.attrgetter("end_timestamp"))), (_MakeField("oppriority", "OpCode_prio", QFT_OTHER, "List of opcode priorities"), None, 0, _PerJobOp(operator.attrgetter("priority"))), (_MakeField("summary", "Summary", QFT_OTHER, "List of per-opcode summaries"), None, 0, _PerJobOp(lambda op: op.input.Summary())), ] # Timestamp fields for (name, attr, title, desc) in [ ("received_ts", "received_timestamp", "Received", "Timestamp of when job was received"), ("start_ts", "start_timestamp", "Start", "Timestamp of job start"), ("end_ts", "end_timestamp", "End", "Timestamp of job end"), ]: getter = operator.attrgetter(attr) fields.extend([ (_MakeField(name, title, QFT_OTHER, "%s (tuple containing seconds and microseconds)" % desc), None, QFF_SPLIT_TIMESTAMP, _JobTimestamp(getter)), ]) return _PrepareFieldList(fields, []) def _GetExportName(_, (node_name, expname)): # pylint: disable=W0613 """Returns an export name if available. """ if expname is None: return _FS_NODATA else: return expname def _BuildExportFields(): """Builds list of fields for exports. """ fields = [ (_MakeField("node", "Node", QFT_TEXT, "Node name"), None, QFF_HOSTNAME, lambda _, (node_name, expname): node_name), (_MakeField("export", "Export", QFT_TEXT, "Export name"), None, 0, _GetExportName), ] return _PrepareFieldList(fields, []) _CLUSTER_VERSION_FIELDS = { "software_version": ("SoftwareVersion", QFT_TEXT, constants.RELEASE_VERSION, "Software version"), "protocol_version": ("ProtocolVersion", QFT_NUMBER, constants.PROTOCOL_VERSION, "RPC protocol version"), "config_version": ("ConfigVersion", QFT_NUMBER, constants.CONFIG_VERSION, "Configuration format version"), "os_api_version": ("OsApiVersion", QFT_NUMBER, max(constants.OS_API_VERSIONS), "API version for OS template scripts"), "export_version": ("ExportVersion", QFT_NUMBER, constants.EXPORT_VERSION, "Import/export file format version"), "vcs_version": ("VCSVersion", QFT_TEXT, constants.VCS_VERSION, "VCS version"), } _CLUSTER_SIMPLE_FIELDS = { "cluster_name": ("Name", QFT_TEXT, QFF_HOSTNAME, "Cluster name"), "volume_group_name": ("VgName", QFT_TEXT, 0, "LVM volume group name"), } class ClusterQueryData: def __init__(self, cluster, nodes, drain_flag, watcher_pause): """Initializes this class. @type cluster: L{objects.Cluster} @param cluster: Instance of cluster object @type nodes: dict; node UUID as key @param nodes: Node objects @type drain_flag: bool @param drain_flag: Whether job queue is drained @type watcher_pause: number @param watcher_pause: Until when watcher is paused (Unix timestamp) """ self._cluster = cluster self.nodes = nodes self.drain_flag = drain_flag self.watcher_pause = watcher_pause def __iter__(self): return iter([self._cluster]) def _ClusterWatcherPause(ctx, _): """Returns until when watcher is paused (if available). """ if ctx.watcher_pause is None: return _FS_UNAVAIL else: return ctx.watcher_pause def _BuildClusterFields(): """Builds list of fields for cluster information. """ fields = [ (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), CQ_CONFIG, 0, lambda ctx, cluster: list(cluster.GetTags())), (_MakeField("architecture", "ArchInfo", QFT_OTHER, "Architecture information"), None, 0, lambda ctx, _: runtime.GetArchInfo()), (_MakeField("drain_flag", "QueueDrained", QFT_BOOL, "Flag whether job queue is drained"), CQ_QUEUE_DRAINED, 0, lambda ctx, _: ctx.drain_flag), (_MakeField("watcher_pause", "WatcherPause", QFT_TIMESTAMP, "Until when watcher is paused"), CQ_WATCHER_PAUSE, 0, _ClusterWatcherPause), (_MakeField("master_node", "Master", QFT_TEXT, "Master node name"), CQ_CONFIG, QFF_HOSTNAME, lambda ctx, cluster: _GetNodeName(ctx, None, cluster.master_node)), ] # Simple fields fields.extend([ (_MakeField(name, title, kind, doc), CQ_CONFIG, flags, _GetItemAttr(name)) for (name, (title, kind, flags, doc)) in _CLUSTER_SIMPLE_FIELDS.items() ],) # Version fields fields.extend([ (_MakeField(name, title, kind, doc), None, 0, _StaticValue(value)) for (name, (title, kind, value, doc)) in _CLUSTER_VERSION_FIELDS.items()]) # Add timestamps fields.extend(_GetItemTimestampFields(CQ_CONFIG)) return _PrepareFieldList(fields, [ ("name", "cluster_name")]) class NetworkQueryData: """Data container for network data queries. """ def __init__(self, networks, network_to_groups, network_to_instances, stats): """Initializes this class. @param networks: List of network objects @type network_to_groups: dict; network UUID as key @param network_to_groups: Per-network list of groups @type network_to_instances: dict; network UUID as key @param network_to_instances: Per-network list of instances @type stats: dict; network UUID as key @param stats: Per-network usage statistics """ self.networks = networks self.network_to_groups = network_to_groups self.network_to_instances = network_to_instances self.stats = stats def __iter__(self): """Iterate over all networks. """ for net in self.networks: if self.stats: self.curstats = self.stats.get(net.uuid, None) else: self.curstats = None yield net _NETWORK_SIMPLE_FIELDS = { "name": ("Network", QFT_TEXT, 0, "Name"), "network": ("Subnet", QFT_TEXT, 0, "IPv4 subnet"), "gateway": ("Gateway", QFT_OTHER, 0, "IPv4 gateway"), "network6": ("IPv6Subnet", QFT_OTHER, 0, "IPv6 subnet"), "gateway6": ("IPv6Gateway", QFT_OTHER, 0, "IPv6 gateway"), "mac_prefix": ("MacPrefix", QFT_OTHER, 0, "MAC address prefix"), "serial_no": ("SerialNo", QFT_NUMBER, 0, _SERIAL_NO_DOC % "Network"), "uuid": ("UUID", QFT_TEXT, 0, "Network UUID"), } _NETWORK_STATS_FIELDS = { "free_count": ("FreeCount", QFT_NUMBER, 0, "Number of available addresses"), "reserved_count": ("ReservedCount", QFT_NUMBER, 0, "Number of reserved addresses"), "map": ("Map", QFT_TEXT, 0, "Actual mapping"), "external_reservations": ("ExternalReservations", QFT_TEXT, 0, "External reservations"), } def _GetNetworkStatsField(field, kind, ctx, _): """Gets the value of a "stats" field from L{NetworkQueryData}. @param field: Field name @param kind: Data kind, one of L{constants.QFT_ALL} @type ctx: L{NetworkQueryData} """ return _GetStatsField(field, kind, ctx.curstats) def _BuildNetworkFields(): """Builds list of fields for network queries. """ fields = [ (_MakeField("tags", "Tags", QFT_OTHER, "Tags"), IQ_CONFIG, 0, lambda ctx, inst: list(inst.GetTags())), ] # Add simple fields fields.extend([ (_MakeField(name, title, kind, doc), NETQ_CONFIG, 0, _GetItemMaybeAttr(name)) for (name, (title, kind, _, doc)) in _NETWORK_SIMPLE_FIELDS.items()]) def _GetLength(getter): return lambda ctx, network: len(getter(ctx)[network.uuid]) def _GetSortedList(getter): return lambda ctx, network: utils.NiceSort(getter(ctx)[network.uuid]) network_to_groups = operator.attrgetter("network_to_groups") network_to_instances = operator.attrgetter("network_to_instances") # Add fields for node groups fields.extend([ (_MakeField("group_cnt", "NodeGroups", QFT_NUMBER, "Number of nodegroups"), NETQ_GROUP, 0, _GetLength(network_to_groups)), (_MakeField("group_list", "GroupList", QFT_OTHER, "List of nodegroups (group name, NIC mode, NIC link)"), NETQ_GROUP, 0, lambda ctx, network: network_to_groups(ctx)[network.uuid]), ]) # Add fields for instances fields.extend([ (_MakeField("inst_cnt", "Instances", QFT_NUMBER, "Number of instances"), NETQ_INST, 0, _GetLength(network_to_instances)), (_MakeField("inst_list", "InstanceList", QFT_OTHER, "List of instances"), NETQ_INST, 0, _GetSortedList(network_to_instances)), ]) # Add fields for usage statistics fields.extend([ (_MakeField(name, title, kind, doc), NETQ_STATS, 0, compat.partial(_GetNetworkStatsField, name, kind)) for (name, (title, kind, _, doc)) in _NETWORK_STATS_FIELDS.items()]) # Add timestamps fields.extend(_GetItemTimestampFields(IQ_NETWORKS)) return _PrepareFieldList(fields, []) #: Fields for cluster information CLUSTER_FIELDS = _BuildClusterFields() #: Fields available for node queries NODE_FIELDS = _BuildNodeFields() #: Fields available for instance queries INSTANCE_FIELDS = _BuildInstanceFields() #: Fields available for lock queries LOCK_FIELDS = _BuildLockFields() #: Fields available for node group queries GROUP_FIELDS = _BuildGroupFields() #: Fields available for operating system queries OS_FIELDS = _BuildOsFields() #: Fields available for extstorage provider queries EXTSTORAGE_FIELDS = _BuildExtStorageFields() #: Fields available for job queries JOB_FIELDS = _BuildJobFields() #: Fields available for exports EXPORT_FIELDS = _BuildExportFields() #: Fields available for network queries NETWORK_FIELDS = _BuildNetworkFields() #: All available resources ALL_FIELDS = { constants.QR_CLUSTER: CLUSTER_FIELDS, constants.QR_INSTANCE: INSTANCE_FIELDS, constants.QR_NODE: NODE_FIELDS, constants.QR_LOCK: LOCK_FIELDS, constants.QR_GROUP: GROUP_FIELDS, constants.QR_OS: OS_FIELDS, constants.QR_EXTSTORAGE: EXTSTORAGE_FIELDS, constants.QR_JOB: JOB_FIELDS, constants.QR_EXPORT: EXPORT_FIELDS, constants.QR_NETWORK: NETWORK_FIELDS, } #: All available field lists ALL_FIELD_LISTS = ALL_FIELDS.values()
gpl-2.0
-1,335,705,262,583,527,400
29.329997
80
0.642228
false
zjutjsj1004/third
boost/tools/build/src/tools/symlink.py
1
4071
# Status: ported. # Base revision: 64488. # Copyright 2003 Dave Abrahams # Copyright 2002, 2003 Rene Rivera # Copyright 2002, 2003, 2004, 2005 Vladimir Prus # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) # Defines the "symlink" special target. 'symlink' targets make symbolic links # to the sources. import b2.build.feature as feature import b2.build.targets as targets import b2.build.property_set as property_set import b2.build.virtual_target as virtual_target import b2.build.targets from b2.manager import get_manager import bjam import os feature.feature("symlink-location", ["project-relative", "build-relative"], ["incidental"]) class SymlinkTarget(targets.BasicTarget): _count = 0 def __init__(self, project, targets, sources): # Generate a fake name for now. Need unnamed targets eventually. fake_name = "symlink#%s" % SymlinkTarget._count SymlinkTarget._count = SymlinkTarget._count + 1 b2.build.targets.BasicTarget.__init__(self, fake_name, project, sources) # Remember the targets to map the sources onto. Pad or truncate # to fit the sources given. assert len(targets) <= len(sources) self.targets = targets[:] + sources[len(targets):] # The virtual targets corresponding to the given targets. self.virtual_targets = [] def construct(self, name, source_targets, ps): i = 0 for t in source_targets: s = self.targets[i] a = virtual_target.Action(self.manager(), [t], "symlink.ln", ps) vt = virtual_target.FileTarget(os.path.basename(s), t.type(), self.project(), a) # Place the symlink in the directory relative to the project # location, instead of placing it in the build directory. if not ps.get('symlink-location') == "project-relative": vt.set_path(os.path.join(self.project().get('location'), os.path.dirname(s))) vt = get_manager().virtual_targets().register(vt) self.virtual_targets.append(vt) i = i + 1 return (property_set.empty(), self.virtual_targets) # Creates a symbolic link from a set of targets to a set of sources. # The targets and sources map one to one. The symlinks generated are # limited to be the ones given as the sources. That is, the targets # are either padded or trimmed to equate to the sources. The padding # is done with the name of the corresponding source. For example:: # # symlink : one two ; # # Is equal to:: # # symlink one two : one two ; # # Names for symlink are relative to the project location. They cannot # include ".." path components. def symlink(targets, sources): from b2.manager import get_manager t = get_manager().targets() p = get_manager().projects().current() return t.main_target_alternative( SymlinkTarget(p, targets, # Note: inline targets are not supported for symlink, intentionally, # since it's used to linking existing non-local targets. sources)) def setup_ln(targets, sources, ps): source_path = bjam.call("get-target-variable", sources[0], "LOCATE")[0] target_path = bjam.call("get-target-variable", targets[0], "LOCATE")[0] rel = os.path.relpath(source_path, target_path) if rel == ".": bjam.call("set-target-variable", targets, "PATH_TO_SOURCE", "") else: bjam.call("set-target-variable", targets, "PATH_TO_SOURCE", rel) if os.name == 'nt': ln_action = """echo "NT symlinks not supported yet, making copy" del /f /q "$(<)" 2>nul >nul copy "$(>)" "$(<)" $(NULL_OUT)""" else: ln_action = "ln -f -s '$(>:D=:R=$(PATH_TO_SOURCE))' '$(<)'" get_manager().engine().register_action("symlink.ln", ln_action, function=setup_ln) get_manager().projects().add_rule("symlink", symlink)
mit
-5,131,955,878,686,185,000
34.348214
93
0.634733
false
Esri/mdcs-py
scripts/CreateRefMD/CreateRefMD.py
1
12899
#------------------------------------------------------------------------------ # Copyright 2013 Esri # 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. #------------------------------------------------------------------------------ # Name: CreateRefMD.py # Description: Creates referenced mosaic datasets. # Version: 20201230 # Requirements: ArcGIS 10.1 SP1 # Author: Esri Imagery Workflows team #------------------------------------------------------------------------------ #!/usr/bin/env python import arcpy import os import sys sys.path.append('../SetMDProperties/') import SetMDProperties import Base from xml.dom import minidom class CreateReferencedMD(Base.Base): def __init__(self, base): self.srs = '' self.pixel_type = '' self.dic_derive_lst = {} self.dic_ref_info = {} self.m_numBands = '' self.setLog(base.m_log) self.m_base = base def createReferencedMD(self): self.log("Creating reference mosaic datasets:", self.const_general_text) for k in self.dic_derive_lst.keys(): for r in self.dic_derive_lst[k]['ref'].keys(): try: mdPath = os.path.join(self.m_base.m_geoPath, r) inMosaic = self.dic_derive_lst[k]['key'] refMosaic = os.path.join(self.m_base.m_geoPath, r) self.log("Creating MD:" + r, self.const_general_text) if not arcpy.Exists(mdPath): try: if (len(self.dic_ref_info) > 0): in_dataset = self.m_base.getInternalPropValue(self.dic_ref_info, 'in_dataset') _p, _f = os.path.split(in_dataset) if (_p == '' and _f != ''): in_dataset = os.path.join(self.m_base.m_geoPath, _f) arcpy.CreateReferencedMosaicDataset_management( in_dataset, refMosaic, self.srs, self.m_numBands, self.pixel_type, self.m_base.getInternalPropValue(self.dic_ref_info, 'where_clause'), self.m_base.getInternalPropValue(self.dic_ref_info, 'in_template_dataset'), self.m_base.getInternalPropValue(self.dic_ref_info, 'extent'), self.m_base.getInternalPropValue(self.dic_ref_info, 'select_using_features'), self.m_base.getInternalPropValue(self.dic_ref_info, 'lod_field'), self.m_base.getInternalPropValue(self.dic_ref_info, 'minPS_field>'), self.m_base.getInternalPropValue(self.dic_ref_info, 'maxPS_field>'), self.m_base.getInternalPropValue(self.dic_ref_info, 'pixelSize'), self.m_base.getInternalPropValue(self.dic_ref_info, 'build_boundary') ) else: arcpy.CreateReferencedMosaicDataset_management(inMosaic, refMosaic, self.srs, "", self.pixel_type, "", "", "", "", "", "", "", "", "NO_BOUNDARY") except: self.log("\tFailed to create refrence MD " + r, self.const_warning_text) self.log(arcpy.GetMessages(), self.const_warning_text) first_time = True for fnc in self.dic_derive_lst[k]['ref'][r]: self.log("\t\tAdding raster function: " + r + '->' + os.path.basename(fnc), self.const_general_text) try: arcpy.EditRasterFunction_management(refMosaic, "EDIT_MOSAIC_DATASET", "REPLACE" if first_time else "INSERT", fnc) first_time = False except: self.log("\t\t\tFailed to add raster function " + fnc, self.const_warning_text) self.log(arcpy.GetMessages(), self.const_warning_text) except Exception as inst: self.log("Failed to create/edit raster function reference mosaic dataset: " + r, self.const_critical_text) self.log(arcpy.GetMessages(), self.const_critical_text) return False return True def setMDProperties(self, config): setMDProps = SetMDProperties.SetMDProperties() if (setMDProps.init(config) == False): return False for k in self.dic_derive_lst.keys(): for r in self.dic_derive_lst[k]['ref'].keys(): mdPath = os.path.join(self.m_base.m_geoPath, r) refMosaic = os.path.join(self.m_base.m_geoPath, r) setMDProps.setMDProperties(refMosaic) return True def init(self, config): self.srs = self.getXMLNodeValue(self.m_base.m_doc, "SRS") # workspace/location on filesystem where the .gdb is created. self.pixel_type = self.getXMLNodeValue(self.m_base.m_doc, "pixel_type") self.m_numBands = self.getXMLNodeValue(self.m_base.m_doc, "num_bands") Nodelist = self.m_base.m_doc.getElementsByTagName("MosaicDataset") if (Nodelist.length == 0): self.log("Error: MosaicDatasets node not found! Invalid schema.", self.const_critical_text) return False dListEmpty = len(self.dic_derive_lst) == 0 refMD = self.m_base.m_mdName dName = '' try: for node in Nodelist[0].childNodes: node = node.nextSibling if (node is not None and node.nodeType == minidom.Node.ELEMENT_NODE): if (node.nodeName == 'CreateReferencedMosaicDataset'): for node in node.childNodes: if (node is not None and node.nodeType == minidom.Node.ELEMENT_NODE): nodeName = node.nodeName.lower() if (node.childNodes.length > 0): if ((nodeName in self.dic_ref_info.keys()) == False): if (nodeName.lower() == 'in_dataset'): if (self.m_base.m_sources == ''): in_dataset = node.firstChild.nodeValue else: in_dataset = self.m_base.m_sources self.dic_derive_lst[in_dataset] = {'ref': {}} functions = [] self.dic_derive_lst[in_dataset]['ref'][refMD] = functions self.dic_derive_lst[in_dataset]['key'] = in_dataset self.dic_ref_info[nodeName] = in_dataset continue self.dic_ref_info[nodeName] = node.firstChild.nodeValue elif(node.nodeName == 'AddRasters'): if (len(self.dic_derive_lst) > 0): # if CreateReferencedMosaicDataset is found, addRaster info gets ignored. continue if (len(refMD) == 0): self.log("Error: <MosaicDataset/Name> should be defined first.", self.const_critical_text) return False for node in node.childNodes: if (node is not None and node.nodeType == minidom.Node.ELEMENT_NODE): nodeName = node.nodeName.lower() if (nodeName == 'addraster'): for node in node.childNodes: if (node is not None and node.nodeType == minidom.Node.ELEMENT_NODE): nodeName = node.nodeName.lower() if (nodeName == 'sources'): # if (self.m_base.m_sources != ''): for node in node.childNodes: if (node.nodeName.lower() == 'data_path'): try: dNameVal = self.m_base.m_sources if (dNameVal == ''): dNameVal = node.firstChild.nodeValue dName = dNameVal.upper() arydNameVal = dNameVal.split(';') arydName = dName.split(';') maxRange = len(arydName) for indx in range(0, maxRange): _file = arydName[indx].strip() if (_file == ''): continue _p, _f = os.path.split(_file) if (_p == ''): arydNameVal[indx] = os.path.join(self.m_base.m_geoPath, _f) _file = arydNameVal[indx].upper() if (dListEmpty or (_file in self.dic_derive_lst.keys()) == False): self.dic_derive_lst[_file] = {'ref': {}} dListEmpty = False prev_indx = refMD in self.dic_derive_lst[_file]['ref'].keys() if (prev_indx == False): functions = [] self.dic_derive_lst[_file]['ref'][refMD] = functions self.dic_derive_lst[_file]['key'] = arydNameVal[indx] except: Error = True elif(node.nodeName == 'Functions'): if (refMD == '' and dName == ''): self.log("Warning/Internal: refMD/dName empty!", self.const_warning_text) break for node in node.childNodes: if (node.nodeName == 'function_path'): if (node.childNodes.length > 0): rftNode = self.m_base.getAbsPath(node.firstChild.nodeValue.strip()) if (len(rftNode) != 0): rft = self.prefixFolderPath(rftNode, self.m_base.const_raster_function_templates_path_) if (os.path.exists(rft) == False): rft = rftNode for md in self.dic_derive_lst.keys(): self.dic_derive_lst[md]['ref'][refMD].append(rft) except: self.log("Error: reading MosaicDataset nodes.", self.const_critical_text) return False return True
apache-2.0
3,505,991,447,788,889,000
51.864754
177
0.41856
false
puttarajubr/commcare-hq
corehq/apps/reminders/models.py
1
70624
import pytz from pytz import timezone from datetime import timedelta, datetime, date, time import re from corehq.apps.casegroups.models import CommCareCaseGroup from corehq.apps.hqcase.dbaccessors import get_case_ids_in_domain from corehq.apps.reminders.dbaccessors import get_surveys_in_domain from dimagi.ext.couchdbkit import * from casexml.apps.case.models import CommCareCase from corehq.apps.sms.models import CommConnectCase from corehq.apps.users.cases import get_owner_id, get_wrapped_owner from corehq.apps.users.models import CouchUser from corehq.apps.groups.models import Group from dimagi.utils.parsing import string_to_datetime, json_format_datetime from dateutil.parser import parse from corehq.apps.reminders.util import get_form_name, enqueue_reminder_directly from couchdbkit.exceptions import ResourceConflict from couchdbkit.resource import ResourceNotFound from corehq.apps.sms.util import create_task, close_task, update_task from corehq.apps.smsforms.app import submit_unfinished_form from dimagi.utils.couch import LockableMixIn, CriticalSection from dimagi.utils.couch.cache.cache_core import get_redis_client from dimagi.utils.multithreading import process_fast from dimagi.utils.logging import notify_exception from random import randint from django.conf import settings from dimagi.utils.couch.database import iter_docs class IllegalModelStateException(Exception): pass METHOD_SMS = "sms" METHOD_SMS_CALLBACK = "callback" METHOD_SMS_SURVEY = "survey" METHOD_IVR_SURVEY = "ivr_survey" METHOD_EMAIL = "email" METHOD_STRUCTURED_SMS = "structured_sms" METHOD_CHOICES = [ METHOD_SMS, METHOD_SMS_CALLBACK, METHOD_SMS_SURVEY, METHOD_IVR_SURVEY, METHOD_EMAIL, ] # The Monday - Sunday constants are meant to match the result from # date.weekday() DAY_ANY = -1 DAY_MON = 0 DAY_TUE = 1 DAY_WED = 2 DAY_THU = 3 DAY_FRI = 4 DAY_SAT = 5 DAY_SUN = 6 DAY_OF_WEEK_CHOICES = [ DAY_ANY, DAY_MON, DAY_TUE, DAY_WED, DAY_THU, DAY_FRI, DAY_SAT, DAY_SUN, ] REPEAT_SCHEDULE_INDEFINITELY = -1 EVENT_AS_SCHEDULE = "SCHEDULE" EVENT_AS_OFFSET = "OFFSET" EVENT_INTERPRETATIONS = [EVENT_AS_SCHEDULE, EVENT_AS_OFFSET] UI_SIMPLE_FIXED = "SIMPLE_FIXED" UI_COMPLEX = "COMPLEX" UI_CHOICES = [UI_SIMPLE_FIXED, UI_COMPLEX] RECIPIENT_SENDER = "SENDER" RECIPIENT_USER = "USER" RECIPIENT_OWNER = "OWNER" RECIPIENT_CASE = "CASE" RECIPIENT_PARENT_CASE = "PARENT_CASE" RECIPIENT_ALL_SUBCASES = "ALL_SUBCASES" RECIPIENT_SUBCASE = "SUBCASE" RECIPIENT_SURVEY_SAMPLE = "SURVEY_SAMPLE" RECIPIENT_USER_GROUP = "USER_GROUP" RECIPIENT_CHOICES = [ RECIPIENT_USER, RECIPIENT_OWNER, RECIPIENT_CASE, RECIPIENT_SURVEY_SAMPLE, RECIPIENT_PARENT_CASE, RECIPIENT_SUBCASE, RECIPIENT_USER_GROUP, ] KEYWORD_RECIPIENT_CHOICES = [RECIPIENT_SENDER, RECIPIENT_OWNER, RECIPIENT_USER_GROUP] KEYWORD_ACTION_CHOICES = [METHOD_SMS, METHOD_SMS_SURVEY, METHOD_STRUCTURED_SMS] FIRE_TIME_DEFAULT = "DEFAULT" FIRE_TIME_CASE_PROPERTY = "CASE_PROPERTY" FIRE_TIME_RANDOM = "RANDOM" FIRE_TIME_CHOICES = [FIRE_TIME_DEFAULT, FIRE_TIME_CASE_PROPERTY, FIRE_TIME_RANDOM] MATCH_EXACT = "EXACT" MATCH_REGEX = "REGEX" MATCH_ANY_VALUE = "ANY_VALUE" MATCH_TYPE_CHOICES = [MATCH_EXACT, MATCH_REGEX, MATCH_ANY_VALUE] CASE_CRITERIA = "CASE_CRITERIA" ON_DATETIME = "ON_DATETIME" START_CONDITION_TYPES = [CASE_CRITERIA, ON_DATETIME] SURVEY_METHOD_LIST = ["SMS","CATI"] UI_FREQUENCY_ADVANCED = "ADVANCED" UI_FREQUENCY_CHOICES = [UI_FREQUENCY_ADVANCED] QUESTION_RETRY_CHOICES = [1, 2, 3, 4, 5] FORM_TYPE_ONE_BY_ONE = "ONE_BY_ONE" # Answer each question one at a time FORM_TYPE_ALL_AT_ONCE = "ALL_AT_ONCE" # Complete the entire form with just one sms using the delimiter to separate answers FORM_TYPE_CHOICES = [FORM_TYPE_ONE_BY_ONE, FORM_TYPE_ALL_AT_ONCE] REMINDER_TYPE_ONE_TIME = "ONE_TIME" REMINDER_TYPE_KEYWORD_INITIATED = "KEYWORD_INITIATED" REMINDER_TYPE_DEFAULT = "DEFAULT" REMINDER_TYPE_SURVEY_MANAGEMENT = "SURVEY_MANAGEMENT" REMINDER_TYPE_CHOICES = [REMINDER_TYPE_DEFAULT, REMINDER_TYPE_ONE_TIME, REMINDER_TYPE_KEYWORD_INITIATED, REMINDER_TYPE_SURVEY_MANAGEMENT] SEND_NOW = "NOW" SEND_LATER = "LATER" # This time is used when the case property used to specify the reminder time isn't a valid time # TODO: Decide whether to keep this or retire the reminder DEFAULT_REMINDER_TIME = time(12, 0) def is_true_value(val): return val == 'ok' or val == 'OK' def looks_like_timestamp(value): try: regex = re.compile("^\d\d\d\d-\d\d-\d\d.*$") return (regex.match(value) is not None) except Exception: return False def property_references_parent(case_property): return isinstance(case_property, basestring) and case_property.startswith("parent/") def get_case_property(case, case_property): """ case the case case_property the name of the case property (can be 'parent/property' to lookup on the parent, or 'property' to lookup on the case) """ if case_property is None or case is None: return None elif property_references_parent(case_property): parent_case = case.parent if parent_case is None: return None else: return parent_case.get_case_property(case_property[7:]) else: return case.get_case_property(case_property) def case_matches_criteria(case, match_type, case_property, value_to_match): result = False case_property_value = get_case_property(case, case_property) if match_type == MATCH_EXACT: result = (case_property_value == value_to_match) and (value_to_match is not None) elif match_type == MATCH_ANY_VALUE: result = case_property_value is not None elif match_type == MATCH_REGEX: try: regex = re.compile(value_to_match) result = regex.match(str(case_property_value)) is not None except Exception: result = False return result def get_events_scheduling_info(events): """ Return a list of events as dictionaries, only with information pertinent to scheduling changes. """ result = [] for e in events: result.append({ "day_num": e.day_num, "fire_time": e.fire_time, "fire_time_aux": e.fire_time_aux, "fire_time_type": e.fire_time_type, "time_window_length": e.time_window_length, "callback_timeout_intervals": e.callback_timeout_intervals, "form_unique_id": e.form_unique_id, }) return result class MessageVariable(object): def __init__(self, variable): self.variable = variable def __unicode__(self): return unicode(self.variable) @property def days_until(self): try: variable = string_to_datetime(self.variable) except Exception: return "(?)" else: # add 12 hours and then floor == round to the nearest day return (variable - datetime.utcnow() + timedelta(hours=12)).days def __getattr__(self, item): try: return super(MessageVariable, self).__getattribute__(item) except Exception: pass try: return MessageVariable(getattr(self.variable, item)) except Exception: pass try: return MessageVariable(self.variable[item]) except Exception: pass return "(?)" class Message(object): def __init__(self, template, **params): self.template = template self.params = {} for key, value in params.items(): self.params[key] = MessageVariable(value) def __unicode__(self): return self.template.format(**self.params) @classmethod def render(cls, template, **params): if isinstance(template, str): template = unicode(template, encoding='utf-8') return unicode(cls(template, **params)) class CaseReminderEvent(DocumentSchema): """ A CaseReminderEvent is the building block for representing reminder schedules in a CaseReminderHandler (see CaseReminderHandler.events). day_num See CaseReminderHandler, depends on event_interpretation. fire_time See CaseReminderHandler, depends on event_interpretation. fire_time_aux Usage depends on fire_time_type. fire_time_type FIRE_TIME_DEFAULT: the event will be scheduled at the time specified by fire_time. FIRE_TIME_CASE_PROPERTY: the event will be scheduled at the time specified by the case property named in fire_time_aux. FIRE_TIME_RANDOM: the event will be scheduled at a random minute on the interval that starts with fire_time and lasts for time_window_length minutes time_window_length Used in FIRE_TIME_RANDOM to define a time interval that starts at fire_time and lasts for this many minutes message The text to send along with language to send it, represented as a dictionary: {"en": "Hello, {user.full_name}, you're having issues."} callback_timeout_intervals For CaseReminderHandlers whose method is "callback", a list of timeout intervals (in minutes). The message is resent based on the number of entries in this list until the callback is received, or the number of timeouts is exhausted. form_unique_id For CaseReminderHandlers whose method is "survey", this the unique id of the form to play as a survey. """ day_num = IntegerProperty() fire_time = TimeProperty() fire_time_aux = StringProperty() fire_time_type = StringProperty(choices=FIRE_TIME_CHOICES, default=FIRE_TIME_DEFAULT) time_window_length = IntegerProperty() message = DictProperty() callback_timeout_intervals = ListProperty(IntegerProperty) form_unique_id = StringProperty() def run_rule(case_id, handler, schedule_changed, prev_definition): case = CommCareCase.get(case_id) try: handler.case_changed(case, schedule_changed=schedule_changed, prev_definition=prev_definition) except ResourceConflict: # Sometimes the reminder fires in the middle of reprocessing # the scheduling. handler.case_changed(case, schedule_changed=schedule_changed, prev_definition=prev_definition) try: client = get_redis_client() client.incr("reminder-rule-processing-current-%s" % handler._id) except: pass def retire_reminder(reminder_id): r = CaseReminder.get(reminder_id) r.retire() def get_case_ids(domain): """ Had to add this because this query kept intermittently raising "NoMoreData: Can't parse headers" exceptions. """ max_tries = 5 for i in range(max_tries): try: return get_case_ids_in_domain(domain) except Exception: if i == (max_tries - 1): raise class CaseReminderHandler(Document): """ A CaseReminderHandler defines the rules and schedule which govern how messages should go out. The "start" and "until" attributes will spawn and deactivate a CaseReminder for a CommCareCase, respectively, when their conditions are reached. Below both are described in more detail: start This defines when the reminder schedule kicks off. Examples: start="edd" - The reminder schedule kicks off for a CommCareCase on the date defined by the CommCareCase's "edd" property. start="form_started" - The reminder schedule kicks off for a CommCareCase when the CommCareCase's "form_started" property equals "ok". until This defines when the reminders should stop being sent. Once this condition is reached, the CaseReminder is deactivated. Examples: until="followup_1_complete" - The reminders will stop being sent for a CommCareCase when the CommCareCase's "followup_1_complete" property equals "ok". Once a CaseReminder is spawned (i.e., when the "start" condition is met for a CommCareCase), the intervals at which reminders are sent and the messages sent are defined by the "events" attribute on the CaseReminderHandler. One complete cycle through all events is considered to be an "iteration", and the attribute that defines the maximum number of iterations for this schedule is "max_iteration_count". Reminder messages will continue to be sent until the events cycle has occurred "max_iteration_count" times, or until the "until" condition is met, whichever comes first. To ignore the "max_iteration_count", it can be set to REPEAT_SCHEDULE_INDEFINITELY, in which case only the "until" condition stops the reminder messages. The events can either be interpreted as offsets from each other and from the original "start" condition, or as fixed schedule times from the original "start" condition: Example of "event_interpretation" == EVENT_AS_OFFSET: start = "form1_completed" start_offset = 1 events = [ CaseReminderEvent( day_num = 0 ,fire_time = time(hour=1) ,message = {"en": "Form not yet completed."} ) ] schedule_length = 0 event_interpretation = EVENT_AS_OFFSET max_iteration_count = REPEAT_SCHEDULE_INDEFINITELY until = "form2_completed" This CaseReminderHandler can be used to send an hourly message starting one day (start_offset=1) after "form1_completed", and will keep sending the message every hour until "form2_completed". So, if "form1_completed" is reached on January 1, 2012, at 9:46am, the reminders will begin being sent at January 2, 2012, at 10:46am and every hour subsequently until "form2_completed". Specifically, when "event_interpretation" is EVENT_AS_OFFSET: day_num is interpreted to be a number of days after the last fire fire_time is interpreted to be a number of hours, minutes, and seconds after the last fire schedule_length is interpreted to be a number of days between the last event and the beginning of a new iteration Example of "event_interpretation" == EVENT_AS_SCHEDULE: start = "regimen_started" start_offset = 1 events = [ CaseReminderEvent( day_num = 1 ,fire_time = time(11,00) ,message = {"en": "Form not yet completed."} ) ,CaseReminderEvent( day_num = 4 ,fire_time = time(11,00) ,message = {"en": "Form not yet completed."} ) ] schedule_length = 7 event_interpretation = EVENT_AS_SCHEDULE max_iteration_count = 4 until = "ignore_this_attribute" This CaseReminderHandler can be used to send reminders at 11:00am on days 2 and 5 of a weekly schedule (schedule_length=7), for 4 weeks (max_iteration_count=4). "Day 1" of the weekly schedule is considered to be one day (start_offset=1) after "regimen_started". So, if "regimen_started" is reached on a Sunday, the days of the week will be Monday=1, Tuesday=2, etc., and the reminders will be sent on Tuesday and Friday of each week, for 4 weeks. Specifically, when "event_interpretation" is EVENT_AS_SCHEDULE: day_num is interpreted to be a the number of days since the current event cycle began fire_time is interpreted to be the time of day to fire the reminder schedule_length is interpreted to be the length of the event cycle, in days Below is a description of the remaining attributes for a CaseReminderHandler: domain The domain to which this CaseReminderHandler belongs. Only CommCareCases belonging to this domain will be checked for the "start" and "until" conditions. case_type Only CommCareCases whose "type" attribute matches this attribute will be checked for the "start" and "until" conditions. nickname A simple name used to describe this CaseReminderHandler. default_lang Default language to use in case no translation is found for the recipient's language. method Set to "sms" to send simple sms reminders at the proper intervals. Set to "callback" to send sms reminders and to enable the checked of "callback_timeout_intervals" on each event. ui_type The type of UI to use for editing this CaseReminderHandler (see UI_CHOICES) """ domain = StringProperty() last_modified = DateTimeProperty() active = BooleanProperty(default=True) case_type = StringProperty() nickname = StringProperty() default_lang = StringProperty() method = StringProperty(choices=METHOD_CHOICES, default="sms") ui_type = StringProperty(choices=UI_CHOICES, default=UI_SIMPLE_FIXED) recipient = StringProperty(choices=RECIPIENT_CHOICES, default=RECIPIENT_USER) ui_frequency = StringProperty(choices=UI_FREQUENCY_CHOICES, default=UI_FREQUENCY_ADVANCED) # This will be used to simplify the scheduling process in the ui sample_id = StringProperty() user_group_id = StringProperty() user_id = StringProperty() case_id = StringProperty() reminder_type = StringProperty(choices=REMINDER_TYPE_CHOICES, default=REMINDER_TYPE_DEFAULT) locked = BooleanProperty(default=False) # Only used when recipient is RECIPIENT_SUBCASE. # All subcases matching the given criteria will be the recipients. recipient_case_match_property = StringProperty() recipient_case_match_type = StringProperty(choices=MATCH_TYPE_CHOICES) recipient_case_match_value = StringProperty() # Only applies when method is "survey". # If this is True, on the last survey timeout, instead of resending the current question, # it will submit the form for the recipient with whatever is completed up to that point. submit_partial_forms = BooleanProperty(default=False) # Only applies when submit_partial_forms is True. # If this is True, partial form submissions will be allowed to create / update / close cases. # If this is False, partial form submissions will just submit the form without case create / update / close. include_case_side_effects = BooleanProperty(default=False) # Only applies for method = "ivr_survey" right now. # This is the maximum number of times that it will retry asking a question with an invalid response before hanging # up. This is meant to prevent long running calls. max_question_retries = IntegerProperty(choices=QUESTION_RETRY_CHOICES, default=QUESTION_RETRY_CHOICES[-1]) survey_incentive = StringProperty() # start condition start_condition_type = StringProperty(choices=START_CONDITION_TYPES, default=CASE_CRITERIA) # used when start_condition_type == ON_DATETIME start_datetime = DateTimeProperty() # used when start_condition_type == CASE_CRITERIA start_property = StringProperty() start_value = StringProperty() start_date = StringProperty() start_offset = IntegerProperty() start_match_type = StringProperty(choices=MATCH_TYPE_CHOICES) start_day_of_week = IntegerProperty(choices=DAY_OF_WEEK_CHOICES, default=DAY_ANY) # reminder schedule events = SchemaListProperty(CaseReminderEvent) schedule_length = IntegerProperty() event_interpretation = StringProperty(choices=EVENT_INTERPRETATIONS, default=EVENT_AS_OFFSET) max_iteration_count = IntegerProperty() # stop condition until = StringProperty() # If present, references an entry in settings.ALLOWED_CUSTOM_CONTENT_HANDLERS, which maps to a function # that should be called to retrieve the sms content to send in an sms reminder. # The signature of a custom content handler should be function(reminder, handler, recipient) custom_content_handler = StringProperty() # If a subcase triggers an SMS survey, but we're sending it to the parent case, # we sometimes want the subcase to be the one on which we execute case actions # during form submission. This option will allow for that. # Note that this option only makes a difference if a case is filling out the SMS survey, # and if a case other than that case triggered the reminder. force_surveys_to_use_triggered_case = BooleanProperty(default=False) @property def uses_parent_case_property(self): events_use_parent_case_property = False for event in self.events: if event.fire_time_type == FIRE_TIME_CASE_PROPERTY and property_references_parent(event.fire_time_aux): events_use_parent_case_property = True break return ( events_use_parent_case_property or property_references_parent(self.recipient_case_match_property) or property_references_parent(self.start_property) or property_references_parent(self.start_date) or property_references_parent(self.until) ) @property def uses_time_case_property(self): for event in self.events: if event.fire_time_type == FIRE_TIME_CASE_PROPERTY: return True return False @classmethod def get_now(cls): try: # for testing purposes only! return getattr(cls, 'now') except Exception: return datetime.utcnow() def schedule_has_changed(self, old_definition): """ Returns True if the scheduling information in self is different from the scheduling information in old_definition. old_definition - the CaseReminderHandler to compare to """ return ( get_events_scheduling_info(old_definition.events) != get_events_scheduling_info(self.events) or old_definition.start_offset != self.start_offset or old_definition.schedule_length != self.schedule_length or old_definition.max_iteration_count != self.max_iteration_count ) def get_reminder(self, case): domain = self.domain handler_id = self._id case_id = case._id return CaseReminder.view('reminders/by_domain_handler_case', key=[domain, handler_id, case_id], include_docs=True, ).one() def get_reminders(self, ids_only=False): domain = self.domain handler_id = self._id include_docs = not ids_only result = CaseReminder.view('reminders/by_domain_handler_case', startkey=[domain, handler_id], endkey=[domain, handler_id, {}], include_docs=include_docs, ).all() if ids_only: return [entry["id"] for entry in result] else: return result def get_day_of_week_offset(self, dt, day_of_week): offset = 0 while dt.weekday() != day_of_week: offset += 1 dt = dt + timedelta(days=1) return offset # For use with event_interpretation = EVENT_AS_SCHEDULE def get_current_reminder_event_timestamp(self, reminder, recipient, case): event = self.events[reminder.current_event_sequence_num] additional_minute_offset = 0 if event.fire_time_type == FIRE_TIME_DEFAULT: fire_time = event.fire_time elif event.fire_time_type == FIRE_TIME_CASE_PROPERTY: fire_time = get_case_property(case, event.fire_time_aux) try: fire_time = parse(fire_time).time() except Exception: fire_time = DEFAULT_REMINDER_TIME elif event.fire_time_type == FIRE_TIME_RANDOM: additional_minute_offset = randint(0, event.time_window_length - 1) + (event.fire_time.hour * 60) + event.fire_time.minute fire_time = time(0, 0) else: fire_time = DEFAULT_REMINDER_TIME day_offset = self.start_offset + (self.schedule_length * (reminder.schedule_iteration_num - 1)) + event.day_num start_date = reminder.start_date + timedelta(days=day_offset) day_of_week_offset = 0 if self.start_day_of_week != DAY_ANY: day_of_week_offset = self.get_day_of_week_offset(start_date, self.start_day_of_week) timestamp = (datetime.combine(start_date, fire_time) + timedelta(days=day_of_week_offset) + timedelta(minutes=additional_minute_offset)) return CaseReminderHandler.timestamp_to_utc(recipient, timestamp) def spawn_reminder(self, case, now, recipient=None): """ Creates a CaseReminder. case The CommCareCase for which to create the CaseReminder. now The date and time to kick off the CaseReminder. This is the date and time from which all offsets are calculated. return The CaseReminder """ if recipient is None: if self.recipient == RECIPIENT_USER: recipient = CouchUser.get_by_user_id(case.user_id) elif self.recipient == RECIPIENT_CASE: recipient = CommConnectCase.get(case._id) elif self.recipient == RECIPIENT_PARENT_CASE: if case is not None and case.parent is not None: recipient = CommConnectCase.wrap_as_commconnect_case(case.parent) local_now = CaseReminderHandler.utc_to_local(recipient, now) case_id = case._id if case is not None else None user_id = recipient._id if self.recipient == RECIPIENT_USER and recipient is not None else None sample_id = recipient._id if self.recipient == RECIPIENT_SURVEY_SAMPLE else None reminder = CaseReminder( domain=self.domain, case_id=case_id, handler_id=self._id, user_id=user_id, method=self.method, active=True, start_date=date(now.year, now.month, now.day) if (now.hour == 0 and now.minute == 0 and now.second == 0 and now.microsecond == 0) else date(local_now.year,local_now.month,local_now.day), schedule_iteration_num=1, current_event_sequence_num=0, callback_try_count=0, skip_remaining_timeouts=False, sample_id=sample_id, xforms_session_ids=[], ) # Set the first fire time appropriately if self.event_interpretation == EVENT_AS_OFFSET: # EVENT_AS_OFFSET day_offset = self.start_offset + self.events[0].day_num time_offset = self.events[0].fire_time reminder.next_fire = now + timedelta(days=day_offset, hours=time_offset.hour, minutes=time_offset.minute, seconds=time_offset.second) else: # EVENT_AS_SCHEDULE reminder.next_fire = self.get_current_reminder_event_timestamp(reminder, recipient, case) return reminder @classmethod def utc_to_local(cls, contact, timestamp): """ Converts the given naive datetime from UTC to the contact's time zone. contact The contact whose time zone to use (must be an instance of CommCareMobileContactMixin). timestamp The naive datetime. return The converted timestamp, as a naive datetime. """ try: time_zone = timezone(str(contact.get_time_zone())) utc_datetime = pytz.utc.localize(timestamp) local_datetime = utc_datetime.astimezone(time_zone) naive_local_datetime = local_datetime.replace(tzinfo=None) return naive_local_datetime except Exception: return timestamp @classmethod def timestamp_to_utc(cls, contact, timestamp): """ Converts the given naive datetime from the contact's time zone to UTC. contact The contact whose time zone to use (must be an instance of CommCareMobileContactMixin). timestamp The naive datetime. return The converted timestamp, as a naive datetime. """ try: time_zone = timezone(str(contact.get_time_zone())) local_datetime = time_zone.localize(timestamp) utc_datetime = local_datetime.astimezone(pytz.utc) naive_utc_datetime = utc_datetime.replace(tzinfo=None) return naive_utc_datetime except Exception: return timestamp def move_to_next_event(self, reminder): """ Moves the given CaseReminder to the next event specified by its CaseReminderHandler. If the CaseReminder is on the last event in the cycle, it moves to the first event in the cycle. If the CaseReminderHandler's max_iteration_count is not REPEAT_SCHEDULE_INDEFINITELY and the CaseReminder is on the last event in the event cycle, the CaseReminder is also deactivated. reminder The CaseReminder to move to the next event. return void """ reminder.current_event_sequence_num += 1 reminder.callback_try_count = 0 reminder.skip_remaining_timeouts = False reminder.xforms_session_ids = [] reminder.event_initiation_timestamp = None if reminder.current_event_sequence_num >= len(self.events): reminder.current_event_sequence_num = 0 reminder.schedule_iteration_num += 1 def set_next_fire(self, reminder, now): """ Sets reminder.next_fire to the next allowable date after now by continuously moving the given CaseReminder to the next event (using move_to_next_event() above) and setting the CaseReminder's next_fire attribute accordingly until the next_fire > the now parameter. This is done to skip reminders that were never sent (such as when reminders are deactivated for a while), instead of sending one reminder every minute until they're all made up for. reminder The CaseReminder whose next_fire to set. now The date and time after which reminder.next_fire must be before returning. return void """ case = reminder.case recipient = reminder.recipient iteration = 0 reminder.error_retry_count = 0 # Reset next_fire to its last scheduled fire time in case there were any error retries if reminder.last_scheduled_fire_time is not None: reminder.next_fire = reminder.last_scheduled_fire_time while now >= reminder.next_fire and reminder.active: iteration += 1 # If it is a callback reminder, check the callback_timeout_intervals if (self.method in [METHOD_SMS_CALLBACK, METHOD_SMS_SURVEY, METHOD_IVR_SURVEY] and len(reminder.current_event.callback_timeout_intervals) > 0): if reminder.skip_remaining_timeouts or reminder.callback_try_count >= len(reminder.current_event.callback_timeout_intervals): if self.method == METHOD_SMS_SURVEY and self.submit_partial_forms and iteration > 1: # This is to make sure we submit the unfinished forms even when fast-forwarding to the next event after system downtime for session_id in reminder.xforms_session_ids: submit_unfinished_form(session_id, self.include_case_side_effects) else: reminder.next_fire = reminder.next_fire + timedelta(minutes = reminder.current_event.callback_timeout_intervals[reminder.callback_try_count]) reminder.callback_try_count += 1 continue # Move to the next event in the cycle self.move_to_next_event(reminder) # Set the next fire time if self.event_interpretation == EVENT_AS_OFFSET: # EVENT_AS_OFFSET next_event = reminder.current_event day_offset = next_event.day_num if reminder.current_event_sequence_num == 0: day_offset += self.schedule_length time_offset = next_event.fire_time reminder.next_fire += timedelta(days=day_offset, hours=time_offset.hour, minutes=time_offset.minute, seconds=time_offset.second) else: # EVENT_AS_SCHEDULE reminder.next_fire = self.get_current_reminder_event_timestamp(reminder, recipient, case) # Set whether or not the reminder should still be active reminder.active = self.get_active(reminder, reminder.next_fire, case) # Preserve the current next fire time since next_fire can be manipulated for error retries reminder.last_scheduled_fire_time = reminder.next_fire def recalculate_schedule(self, reminder, prev_definition=None): """ Recalculates which iteration / event number a schedule-based reminder should be on. Only meant to be called on schedule-based reminders. """ if reminder.callback_try_count > 0 and prev_definition is not None and len(prev_definition.events) > reminder.current_event_sequence_num: preserve_current_session_ids = True old_form_unique_id = prev_definition.events[reminder.current_event_sequence_num].form_unique_id old_xforms_session_ids = reminder.xforms_session_ids else: preserve_current_session_ids = False case = reminder.case reminder.last_fired = None reminder.error_retry_count = 0 reminder.event_initiation_timestamp = None reminder.active = True reminder.schedule_iteration_num = 1 reminder.current_event_sequence_num = 0 reminder.callback_try_count = 0 reminder.skip_remaining_timeouts = False reminder.last_scheduled_fire_time = None reminder.xforms_session_ids = [] reminder.next_fire = self.get_current_reminder_event_timestamp(reminder, reminder.recipient, case) reminder.active = self.get_active(reminder, reminder.next_fire, case) self.set_next_fire(reminder, self.get_now()) if preserve_current_session_ids: if reminder.callback_try_count > 0 and self.events[reminder.current_event_sequence_num].form_unique_id == old_form_unique_id and self.method == METHOD_SMS_SURVEY: reminder.xforms_session_ids = old_xforms_session_ids elif prev_definition is not None and prev_definition.submit_partial_forms: for session_id in old_xforms_session_ids: submit_unfinished_form(session_id, prev_definition.include_case_side_effects) def get_active(self, reminder, now, case): schedule_not_finished = not (self.max_iteration_count != REPEAT_SCHEDULE_INDEFINITELY and reminder.schedule_iteration_num > self.max_iteration_count) if case is not None: until_not_reached = (not self.condition_reached(case, self.until, now)) return until_not_reached and schedule_not_finished else: return schedule_not_finished def should_fire(self, reminder, now): return now > reminder.next_fire def fire(self, reminder): """ Sends the message associated with the given CaseReminder's current event. reminder The CaseReminder which to fire. return True on success, False on failure """ # Prevent circular import from .event_handlers import EVENT_HANDLER_MAP if self.deleted(): reminder.retire() return False # Retrieve the list of individual recipients recipient = reminder.recipient if isinstance(recipient, list) and len(recipient) > 0: recipients = recipient elif isinstance(recipient, CouchUser) or isinstance(recipient, CommCareCase): recipients = [recipient] elif isinstance(recipient, Group): recipients = recipient.get_users(is_active=True, only_commcare=False) elif isinstance(recipient, CommCareCaseGroup): recipients = [CommConnectCase.get(case_id) for case_id in recipient.cases] else: from corehq.apps.reminders.event_handlers import raise_error, ERROR_NO_RECIPIENTS raise_error(reminder, ERROR_NO_RECIPIENTS) return False # Retrieve the corresponding verified number entries for all individual recipients verified_numbers = {} for r in recipients: if hasattr(r, "get_verified_numbers"): contact_verified_numbers = r.get_verified_numbers(False) if len(contact_verified_numbers) > 0: verified_number = sorted(contact_verified_numbers.iteritems())[0][1] else: verified_number = None else: verified_number = None verified_numbers[r.get_id] = verified_number # Set the event initiation timestamp if we're not on any timeouts if reminder.callback_try_count == 0: reminder.event_initiation_timestamp = self.get_now() # Call the appropriate event handler event_handler = EVENT_HANDLER_MAP.get(self.method) last_fired = self.get_now() # Store the timestamp right before firing to ensure continuity in the callback lookups result = event_handler(reminder, self, recipients, verified_numbers) reminder.last_fired = last_fired return result @classmethod def condition_reached(cls, case, case_property, now): """ Checks to see if the condition specified by case_property on case has been reached. If case[case_property] is a timestamp and it is later than now, then the condition is reached. If case[case_property] equals "ok", then the condition is reached. case The CommCareCase to check. case_property The property on CommCareCase to check. now The timestamp to use when comparing, if case.case_property is a timestamp. return True if the condition is reached, False if not. """ condition = get_case_property(case, case_property) if isinstance(condition, datetime): pass elif isinstance(condition, date): condition = datetime.combine(condition, time(0,0)) elif looks_like_timestamp(condition): try: condition = parse(condition) except Exception: pass if isinstance(condition, datetime) and getattr(condition, "tzinfo") is not None: condition = condition.astimezone(pytz.utc) condition = condition.replace(tzinfo=None) if (isinstance(condition, datetime) and now > condition) or is_true_value(condition): return True else: return False def case_changed(self, case, now=None, schedule_changed=False, prev_definition=None): key = "rule-update-definition-%s-case-%s" % (self._id, case._id) with CriticalSection([key]): self._case_changed(case, now, schedule_changed, prev_definition) def _case_changed(self, case, now, schedule_changed, prev_definition): """ This method is used to manage updates to CaseReminderHandler's whose start_condition_type == CASE_CRITERIA. This method is also called every time a CommCareCase is saved and matches this CaseReminderHandler's domain and case_type. It's used to check for the "start" and "until" conditions in order to spawn or deactivate a CaseReminder for the CommCareCase. case The case that is being updated. now The current date and time to use; if not specified, datetime.utcnow() is used. return void """ now = now or self.get_now() reminder = self.get_reminder(case) if case and case.user_id and (case.user_id != case._id): try: user = CouchUser.get_by_user_id(case.user_id) except KeyError: user = None else: user = None if (case.closed or case.type != self.case_type or case.doc_type.endswith("-Deleted") or self.deleted() or (self.recipient == RECIPIENT_USER and not user)): if reminder: reminder.retire() else: start_condition_reached = case_matches_criteria(case, self.start_match_type, self.start_property, self.start_value) start_date = get_case_property(case, self.start_date) if (not isinstance(start_date, date)) and not (isinstance(start_date, datetime)): try: start_date = parse(start_date) except Exception: start_date = None if isinstance(start_date, datetime): start_condition_datetime = start_date start = start_date elif isinstance(start_date, date): start_condition_datetime = datetime(start_date.year, start_date.month, start_date.day, 0, 0, 0) start = start_condition_datetime else: start_condition_datetime = None start = now # Retire the reminder if the start condition is no longer valid if reminder is not None: if not start_condition_reached: # The start condition is no longer valid, so retire the reminder reminder.retire() reminder = None elif reminder.start_condition_datetime != start_condition_datetime: # The start date has changed, so retire the reminder and it will be spawned again in the next block reminder.retire() reminder = None # Spawn a reminder if need be just_spawned = False if reminder is None: if start_condition_reached: reminder = self.spawn_reminder(case, start) reminder.start_condition_datetime = start_condition_datetime self.set_next_fire(reminder, now) # This will fast-forward to the next event that does not occur in the past just_spawned = True # Check to see if the reminder should still be active if reminder is not None: if schedule_changed and self.event_interpretation == EVENT_AS_SCHEDULE and not just_spawned: self.recalculate_schedule(reminder, prev_definition) else: active = self.get_active(reminder, reminder.next_fire, case) if active and not reminder.active: reminder.active = True self.set_next_fire(reminder, now) # This will fast-forward to the next event that does not occur in the past else: reminder.active = active reminder.active = self.active and reminder.active reminder.save() def datetime_definition_changed(self, send_immediately=False): """ This method is used to manage updates to CaseReminderHandler's whose start_condition_type == ON_DATETIME. Set send_immediately to True to send the first event right away, regardless of whether it may occur in the past. """ reminder = CaseReminder.view('reminders/by_domain_handler_case', startkey=[self.domain, self._id], endkey=[self.domain, self._id, {}], include_docs=True ).one() now = self.get_now() if self.recipient == RECIPIENT_SURVEY_SAMPLE: recipient = CommCareCaseGroup.get(self.sample_id) elif self.recipient == RECIPIENT_USER_GROUP: recipient = Group.get(self.user_group_id) elif self.recipient == RECIPIENT_USER: recipient = CouchUser.get_by_user_id(self.user_id) elif self.recipient == RECIPIENT_CASE: recipient = CommCareCase.get(self.case_id) else: recipient = None if reminder is not None and (reminder.start_condition_datetime != self.start_datetime or not self.active): reminder.retire() reminder = None if reminder is None and self.active: if self.recipient == RECIPIENT_CASE: case = recipient elif self.case_id is not None: case = CommCareCase.get(self.case_id) else: case = None reminder = self.spawn_reminder(case, self.start_datetime, recipient) reminder.start_condition_datetime = self.start_datetime if settings.REMINDERS_QUEUE_ENABLED: reminder.save() if send_immediately: enqueue_reminder_directly(reminder) else: sent = False if send_immediately: try: sent = self.fire(reminder) except Exception: # An exception could happen here, for example, if # touchforms is down. So just pass, and let the reminder # be saved below so that the framework will pick it up # and try again. notify_exception(None, message="Error sending immediately for handler %s" % self._id) if sent or not send_immediately: self.set_next_fire(reminder, now) reminder.save() def check_state(self): """ Double-checks the model for any inconsistencies and raises an IllegalModelStateException if any exist. """ def check_attr(name, obj=self): # don't allow None or empty string, but allow 0 if getattr(obj, name) in [None, ""]: raise IllegalModelStateException("%s is required" % name) if self.start_condition_type == CASE_CRITERIA: check_attr("case_type") check_attr("start_property") check_attr("start_match_type") if self.start_match_type != MATCH_ANY_VALUE: check_attr("start_value") if self.start_condition_type == ON_DATETIME: check_attr("start_datetime") if self.method == METHOD_SMS: check_attr("default_lang") check_attr("schedule_length") check_attr("max_iteration_count") check_attr("start_offset") if len(self.events) == 0: raise IllegalModelStateException("len(events) must be > 0") last_day = 0 for event in self.events: check_attr("day_num", obj=event) if event.day_num < 0: raise IllegalModelStateException("event.day_num must be " "non-negative") if event.fire_time_type in [FIRE_TIME_DEFAULT, FIRE_TIME_RANDOM]: check_attr("fire_time", obj=event) if event.fire_time_type == FIRE_TIME_RANDOM: check_attr("time_window_length", obj=event) if event.fire_time_type == FIRE_TIME_CASE_PROPERTY: check_attr("fire_time_aux", obj=event) if self.method == METHOD_SMS and not self.custom_content_handler: if not isinstance(event.message, dict): raise IllegalModelStateException("event.message expected " "to be a dictionary") if self.default_lang not in event.message: raise IllegalModelStateException("default_lang missing " "from event.message") if self.method in [METHOD_SMS_SURVEY, METHOD_IVR_SURVEY]: check_attr("form_unique_id", obj=event) if not isinstance(event.callback_timeout_intervals, list): raise IllegalModelStateException("event." "callback_timeout_intervals expected to be a list") last_day = event.day_num if self.event_interpretation == EVENT_AS_SCHEDULE: if self.schedule_length <= last_day: raise IllegalModelStateException("schedule_length must be " "greater than last event's day_num") else: if self.schedule_length < 0: raise IllegalModelStateException("schedule_length must be" "non-negative") if self.recipient == RECIPIENT_SUBCASE: check_attr("recipient_case_match_property") check_attr("recipient_case_match_type") if self.recipient_case_match_type != MATCH_ANY_VALUE: check_attr("recipient_case_match_value") if (self.custom_content_handler and self.custom_content_handler not in settings.ALLOWED_CUSTOM_CONTENT_HANDLERS): raise IllegalModelStateException("unknown custom_content_handler") self.check_min_tick() def check_min_tick(self, minutes=60): """ For offset-based schedules that are repeated multiple times intraday, makes sure that the events are separated by at least the given number of minutes. """ if (self.event_interpretation == EVENT_AS_OFFSET and self.max_iteration_count != 1 and self.schedule_length == 0): minimum_tick = None for e in self.events: this_tick = timedelta(days=e.day_num, hours=e.fire_time.hour, minutes=e.fire_time.minute) if minimum_tick is None: minimum_tick = this_tick elif this_tick < minimum_tick: minimum_tick = this_tick if minimum_tick < timedelta(minutes=minutes): raise IllegalModelStateException("Minimum tick for a schedule " "repeated multiple times intraday is %s minutes." % minutes) def save(self, **params): from corehq.apps.reminders.tasks import process_reminder_rule self.check_state() schedule_changed = params.pop("schedule_changed", False) prev_definition = params.pop("prev_definition", None) send_immediately = params.pop("send_immediately", False) unlock = params.pop("unlock", False) self.last_modified = datetime.utcnow() if unlock: self.locked = False else: self.locked = True super(CaseReminderHandler, self).save(**params) delay = self.start_condition_type == CASE_CRITERIA if not unlock: if delay: process_reminder_rule.delay(self, schedule_changed, prev_definition, send_immediately) else: process_reminder_rule(self, schedule_changed, prev_definition, send_immediately) def process_rule(self, schedule_changed, prev_definition, send_immediately): if not self.deleted(): if self.start_condition_type == CASE_CRITERIA: case_ids = get_case_ids(self.domain) try: client = get_redis_client() client.set("reminder-rule-processing-current-%s" % self._id, 0) client.set("reminder-rule-processing-total-%s" % self._id, len(case_ids)) except: pass process_fast(case_ids, run_rule, item_goal=100, max_threads=5, args=(self, schedule_changed, prev_definition), use_critical_section=False, print_stack_interval=60) elif self.start_condition_type == ON_DATETIME: self.datetime_definition_changed(send_immediately=send_immediately) else: reminder_ids = self.get_reminders(ids_only=True) process_fast(reminder_ids, retire_reminder, item_goal=100, max_threads=5, use_critical_section=False, print_stack_interval=60) @classmethod def get_handlers(cls, domain, reminder_type_filter=None): ids = cls.get_handler_ids(domain, reminder_type_filter=reminder_type_filter) return cls.get_handlers_from_ids(ids) @classmethod def get_handlers_from_ids(cls, ids): return [ CaseReminderHandler.wrap(doc) for doc in iter_docs(cls.get_db(), ids) ] @classmethod def get_handler_ids(cls, domain, reminder_type_filter=None): result = cls.view('reminders/handlers_by_reminder_type', startkey=[domain], endkey=[domain, {}], include_docs=False, reduce=False, ) def filter_fcn(reminder_type): if reminder_type_filter is None: return True else: return ((reminder_type or REMINDER_TYPE_DEFAULT) == reminder_type_filter) return [ row['id'] for row in result if filter_fcn(row['key'][1]) ] @classmethod def get_referenced_forms(cls, domain): handlers = cls.get_handlers(domain) referenced_forms = [e.form_unique_id for events in [h.events for h in handlers] for e in events] return filter(None, referenced_forms) @classmethod def get_all_reminders(cls, domain=None, due_before=None, ids_only=False): if due_before: now_json = json_format_datetime(due_before) else: now_json = {} # domain=None will actually get them all, so this works smoothly result = CaseReminder.view('reminders/by_next_fire', startkey=[domain], endkey=[domain, now_json], include_docs=(not ids_only), ).all() if ids_only: return [entry["id"] for entry in result] else: return result @classmethod def fire_reminders(cls, now=None): now = now or cls.get_now() for reminder in cls.get_all_reminders(due_before=now): if reminder.acquire_lock(now) and now >= reminder.next_fire: handler = reminder.handler if handler.fire(reminder): handler.set_next_fire(reminder, now) try: reminder.save() except ResourceConflict: # Submitting a form updates the case, which can update the reminder. # Grab the latest version of the reminder and set the next fire if it's still in use. reminder = CaseReminder.get(reminder._id) if not reminder.retired: handler.set_next_fire(reminder, now) reminder.save() try: reminder.release_lock() except ResourceConflict: # This should go away once we move the locking to Redis reminder = CaseReminder.get(reminder._id) reminder.release_lock() def retire(self): self.doc_type += "-Deleted" self.save() def deleted(self): return self.doc_type != 'CaseReminderHandler' class CaseReminder(SafeSaveDocument, LockableMixIn): """ Where the CaseReminderHandler is the rule and schedule for sending out reminders, a CaseReminder is an instance of that rule as it is being applied to a specific CommCareCase. A CaseReminder only applies to a single CommCareCase/CaseReminderHandler interaction and is just a representation of the state of the rule in the lifecycle of the CaseReminderHandler. """ domain = StringProperty() # Domain last_modified = DateTimeProperty() case_id = StringProperty() # Reference to the CommCareCase handler_id = StringProperty() # Reference to the CaseReminderHandler user_id = StringProperty() # Reference to the CouchUser who will receive the SMS messages method = StringProperty(choices=METHOD_CHOICES) # See CaseReminderHandler.method next_fire = DateTimeProperty() # The date and time that the next message should go out last_fired = DateTimeProperty() # The date and time that the last message went out active = BooleanProperty(default=False) # True if active, False if deactivated start_date = DateProperty() # For CaseReminderHandlers with event_interpretation=SCHEDULE, this is the date (in the recipient's time zone) from which all event times are calculated schedule_iteration_num = IntegerProperty() # The current iteration through the cycle of self.handler.events current_event_sequence_num = IntegerProperty() # The current event number (index to self.handler.events) callback_try_count = IntegerProperty() # Keeps track of the number of times a callback has timed out skip_remaining_timeouts = BooleanProperty() # An event handling method can set this to True to skip the remaining timeout intervals for the current event start_condition_datetime = DateTimeProperty() # The date and time matching the case property specified by the CaseReminderHandler.start_condition sample_id = StringProperty() xforms_session_ids = ListProperty(StringProperty) error_retry_count = IntegerProperty(default=0) last_scheduled_fire_time = DateTimeProperty() event_initiation_timestamp = DateTimeProperty() # The date and time that the event was started (which is the same throughout all timeouts) error = BooleanProperty(default=False) error_msg = StringProperty() @property def handler(self): return CaseReminderHandler.get(self.handler_id) @property def current_event(self): return self.handler.events[self.current_event_sequence_num] @property def case(self): if self.case_id is not None: return CommCareCase.get(self.case_id) else: return None @property def user(self): if self.handler.recipient == RECIPIENT_USER: return CouchUser.get_by_user_id(self.user_id) else: return None @property def recipient(self): try: return self._recipient_lookup except ResourceNotFound: return None @property def _recipient_lookup(self): handler = self.handler if handler.recipient == RECIPIENT_USER: return self.user elif handler.recipient == RECIPIENT_CASE: return CommConnectCase.get(self.case_id) elif handler.recipient == RECIPIENT_SURVEY_SAMPLE: return CommCareCaseGroup.get(self.sample_id) elif handler.recipient == RECIPIENT_OWNER: return get_wrapped_owner(get_owner_id(self.case)) elif handler.recipient == RECIPIENT_PARENT_CASE: parent_case = None case = self.case if case is not None: parent_case = case.parent if parent_case is not None: parent_case = CommConnectCase.wrap_as_commconnect_case(parent_case) return parent_case elif handler.recipient == RECIPIENT_SUBCASE: indices = self.case.reverse_indices recipients = [] for index in indices: if index.identifier == "parent": subcase = CommConnectCase.get(index.referenced_id) if case_matches_criteria(subcase, handler.recipient_case_match_type, handler.recipient_case_match_property, handler.recipient_case_match_value): recipients.append(subcase) return recipients elif handler.recipient == RECIPIENT_USER_GROUP: return Group.get(handler.user_group_id) else: return None @property def retired(self): return self.doc_type.endswith("-Deleted") def save(self, *args, **kwargs): self.last_modified = datetime.utcnow() super(CaseReminder, self).save(*args, **kwargs) def retire(self): self.doc_type += "-Deleted" self.save() class SurveyKeywordAction(DocumentSchema): recipient = StringProperty(choices=KEYWORD_RECIPIENT_CHOICES) recipient_id = StringProperty() action = StringProperty(choices=KEYWORD_ACTION_CHOICES) # Only used for action == METHOD_SMS message_content = StringProperty() # Only used for action in [METHOD_SMS_SURVEY, METHOD_STRUCTURED_SMS] form_unique_id = StringProperty() # Only used for action == METHOD_STRUCTURED_SMS use_named_args = BooleanProperty() named_args = DictProperty() # Dictionary of {argument name in the sms (caps) : form question xpath} named_args_separator = StringProperty() # Can be None in which case there is no separator (i.e., a100 b200) class SurveyKeyword(Document): domain = StringProperty() keyword = StringProperty() description = StringProperty() actions = SchemaListProperty(SurveyKeywordAction) delimiter = StringProperty() # Only matters if this is a structured SMS: default is None, in which case the delimiter is any consecutive white space override_open_sessions = BooleanProperty() initiator_doc_type_filter = ListProperty(StringProperty) # List of doc types representing the only types of contacts who should be able to invoke this keyword. Empty list means anyone can invoke. # Properties needed for migration and then can be removed form_type = StringProperty(choices=FORM_TYPE_CHOICES, default=FORM_TYPE_ONE_BY_ONE) form_unique_id = StringProperty() use_named_args = BooleanProperty() named_args = DictProperty() named_args_separator = StringProperty() oct13_migration_timestamp = DateTimeProperty() def retire(self): self.doc_type += "-Deleted" self.save() @property def get_id(self): return self._id @classmethod def get_all(cls, domain): return cls.view("reminders/survey_keywords", startkey=[domain], endkey=[domain, {}], include_docs=True, reduce=False, ).all() @classmethod def get_keyword(cls, domain, keyword): return cls.view("reminders/survey_keywords", key = [domain, keyword.upper()], include_docs=True, reduce=False, ).one() @classmethod def get_by_domain(cls, domain, limit=None, skip=None, include_docs=True): extra_kwargs = {} if limit is not None: extra_kwargs['limit'] = limit if skip is not None: extra_kwargs['skip'] = skip return cls.view( 'reminders/survey_keywords', startkey=[domain], endkey=[domain, {}], include_docs=include_docs, reduce=False, **extra_kwargs ).all() class SurveySample(Document): domain = StringProperty() name = StringProperty() contacts = ListProperty(StringProperty) time_zone = StringProperty() def get_time_zone(self): return self.time_zone @classmethod def get_all(cls, domain): return cls.view('reminders/sample_by_domain', startkey=[domain], endkey=[domain, {}], include_docs=True ).all() class SurveyWave(DocumentSchema): date = DateProperty() time = TimeProperty() end_date = DateProperty() form_id = StringProperty() reminder_definitions = DictProperty() # Dictionary of CommCareCaseGroup._id : CaseReminderHandler._id delegation_tasks = DictProperty() # Dictionary of {sample id : {contact id : delegation task id, ...}, ...} def has_started(self, parent_survey_ref): samples = [CommCareCaseGroup.get(sample["sample_id"]) for sample in parent_survey_ref.samples] for sample in samples: if CaseReminderHandler.timestamp_to_utc(sample, datetime.combine(self.date, self.time)) <= datetime.utcnow(): return True return False class Survey(Document): domain = StringProperty() name = StringProperty() waves = SchemaListProperty(SurveyWave) followups = ListProperty(DictProperty) samples = ListProperty(DictProperty) send_automatically = BooleanProperty() send_followup = BooleanProperty() @classmethod def get_all(cls, domain): return get_surveys_in_domain(domain) def has_started(self): for wave in self.waves: if wave.has_started(self): return True return False def update_delegation_tasks(self, submitting_user_id): utcnow = datetime.utcnow() # Get info about each CATI sample and the instance of that sample used for this survey cati_sample_data = {} for sample_json in self.samples: if sample_json["method"] == "CATI": sample_id = sample_json["sample_id"] cati_sample_data[sample_id] = { "sample_object": CommCareCaseGroup.get(sample_id), "incentive" : sample_json["incentive"], "cati_operator" : sample_json["cati_operator"], } for wave in self.waves: if wave.has_started(self): continue # Close any tasks for samples that are no longer used, and for contacts that are no longer in the samples for sample_id, tasks in wave.delegation_tasks.items(): if sample_id not in cati_sample_data: for case_id, delegation_case_id in tasks.items(): close_task(self.domain, delegation_case_id, submitting_user_id) del wave.delegation_tasks[sample_id] else: for case_id in list(set(tasks.keys()).difference( cati_sample_data[sample_id]["sample_object"].cases)): close_task(self.domain, tasks[case_id], submitting_user_id) del wave.delegation_tasks[sample_id][case_id] # Update / Create tasks for existing / new contacts for sample_id, sample_data in cati_sample_data.items(): task_activation_datetime = CaseReminderHandler.timestamp_to_utc(sample_data["sample_object"], datetime.combine(wave.date, wave.time)) task_deactivation_datetime = CaseReminderHandler.timestamp_to_utc(sample_data["sample_object"], datetime.combine(wave.end_date, wave.time)) if sample_id not in wave.delegation_tasks: wave.delegation_tasks[sample_id] = {} for case_id in sample_data["sample_object"].cases: wave.delegation_tasks[sample_id][case_id] = create_task( CommCareCase.get(case_id), submitting_user_id, sample_data["cati_operator"], wave.form_id, task_activation_datetime, task_deactivation_datetime, sample_data["incentive"] ) else: for case_id in sample_data["sample_object"].cases: delegation_case_id = wave.delegation_tasks[sample_id].get(case_id, None) if delegation_case_id is None: wave.delegation_tasks[sample_id][case_id] = create_task( CommCareCase.get(case_id), submitting_user_id, sample_data["cati_operator"], wave.form_id, task_activation_datetime, task_deactivation_datetime, sample_data["incentive"] ) else: delegation_case = CommCareCase.get(delegation_case_id) if (delegation_case.owner_id != sample_data["cati_operator"] or delegation_case.get_case_property("start_date") != task_activation_datetime or delegation_case.get_case_property("end_date") != task_deactivation_datetime or delegation_case.get_case_property("form_id") != wave.form_id): update_task( self.domain, delegation_case_id, submitting_user_id, sample_data["cati_operator"], wave.form_id, task_activation_datetime, task_deactivation_datetime, sample_data["incentive"] ) from .signals import *
bsd-3-clause
-1,628,130,193,549,512,200
42.947729
204
0.614621
false
amenonsen/ansible
lib/ansible/modules/network/fortios/fortios_system_replacemsg_ec.py
1
9923
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program 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. # # This program 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 this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_system_replacemsg_ec short_description: Replacement messages in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS device by allowing the user to set and modify system_replacemsg feature and ec category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.9" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true state: description: - Indicates whether to create or remove the object. type: str choices: - present - absent system_replacemsg_ec: description: - Replacement messages. default: null type: dict suboptions: buffer: description: - Message string. type: str format: description: - Format flag. type: str choices: - none - text - html - wml header: description: - Header flag. type: str choices: - none - http - 8bit msg_type: description: - Message type. type: str ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Replacement messages. fortios_system_replacemsg_ec: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" state: "present" system_replacemsg_ec: buffer: "<your_own_value>" format: "none" header: "none" msg_type: "<your_own_value>" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_system_replacemsg_ec_data(json): option_list = ['buffer', 'format', 'header', 'msg_type'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def system_replacemsg_ec(data, fos): vdom = data['vdom'] state = data['state'] system_replacemsg_ec_data = data['system_replacemsg_ec'] filtered_data = underscore_to_hyphen(filter_system_replacemsg_ec_data(system_replacemsg_ec_data)) if state == "present": return fos.set('system.replacemsg', 'ec', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('system.replacemsg', 'ec', mkey=filtered_data['msg-type'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_system_replacemsg(data, fos): if data['system_replacemsg_ec']: resp = system_replacemsg_ec(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "system_replacemsg_ec": { "required": False, "type": "dict", "default": None, "options": { "buffer": {"required": False, "type": "str"}, "format": {"required": False, "type": "str", "choices": ["none", "text", "html", "wml"]}, "header": {"required": False, "type": "str", "choices": ["none", "http", "8bit"]}, "msg_type": {"required": False, "type": "str"} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_system_replacemsg(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_system_replacemsg(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
gpl-3.0
-4,127,854,104,198,008,000
28.445104
101
0.582082
false
biosustain/marsi
marsi/nearest_neighbors/model.py
1
19310
# Copyright 2016 Chr. Hansen A/S and The Novo Nordisk Foundation Center for Biosustainability, DTU. # 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 from sklearn import neighbors from cameo.parallel import SequentialView from sqlalchemy.orm import load_only from marsi.io.db import Metabolite try: # pragma: no cover import pyopencl as cl MF = cl.mem_flags cl_available = True except ImportError: class ClFail: def __getattr__(self, item): raise RuntimeError("OpenCL is not available. try 'pip install pyopencl'") cl = ClFail() MF = None cl_available = False import numpy as np from pandas import DataFrame from marsi.utils import timing from marsi.nearest_neighbors import model_ext logger = logging.getLogger(__name__) # Tanimoto coefficient calculation is implemented based on to OpenBabel's implementation # https://github.com/openbabel/openbabel/blob/master/include/openbabel/fingerprint.h#L86 nn_source = """ __kernel void nn(__global float *distances, __global int *fingerprint, __constant int *fpLength, __global int *database, __global int *positions, __constant int *lengths) { int gid = (int)get_global_id(0); float tanimotoCoefficient = -1; int dbEntryLength = lengths[gid]; int fpLen = fpLength[0]; if (fpLen == dbEntryLength) { int andBits = 0; int orBits = 0; int fpPos = positions[gid]; int i; for (i=0; i < fpLen; ++i) { int fpAnd = database[fpPos+i] & fingerprint[i]; int fpOr = database[fpPos+i] | fingerprint[i]; andBits += popcount(fpAnd); orBits += popcount(fpOr); } tanimotoCoefficient = (float)andBits/(float)orBits; } distances[gid] = 1 - tanimotoCoefficient; } """ class KNN(object): """ K-Nearest Neighbors runner object. It is assigned to a model and runs the `knn` function. Attributes ---------- fp : numpy.array A numpy.array with the fingerprint values. k : int The maximum number of neighbors to retrieve. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. """ def __init__(self, fingerprint, k, mode): self.fp = np.array(list(fingerprint), dtype=np.int32) self.k = k self.mode = mode def __call__(self, nn): return nn.knn(self.fp, k=self.k) def __getstate__(self): return dict(fp=self.fp.tolist(), k=self.k, mode=self.mode) def __setstate__(self, d): d['fp'] = np.array(d['fp'], dtype=np.int32) self.__dict__.update(d) class RNN(object): """ R-Nearest Neighbors runner object. It is assigned to a model and runs the `rnn` function. Attributes ---------- fp : numpy.array A numpy.array with the fingerprint values. radius : float A distance radius ]0, 1]. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. """ def __init__(self, fingerprint, radius, mode): self.fp = np.array(list(fingerprint), dtype=np.int32) assert 0 < radius <= 1 self.radius = radius self.mode = mode def __call__(self, nn): return nn.rnn(self.fp, radius=self.radius, mode=self.mode) def __getstate__(self): return dict(fp=self.fp.tolist(), radius=self.radius, mode=self.mode) def __setstate__(self, d): d['fp'] = np.array(d['fp'], dtype=np.int32) self.__dict__.update(d) class Distance(object): """ Distance runner object. It is assigned to a model and runs the `distance` function. Attributes ---------- fp : numpy.array A numpy.array with the fingerprint values. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. """ def __init__(self, fingerprint, mode): self.fp = np.array(list(fingerprint), dtype=np.int32) self.mode = mode def __call__(self, nn): return nn.distances(self.fp, mode=self.mode) def __getstate__(self): return dict(fp=self.fp, mode=self.mode) def __setstate__(self, d): d['fp'] = np.array(d['fp'], dtype=np.int32) self.__dict__.update(d) class DistributedNearestNeighbors(object): """ Nearest Neighbors distributed implementation. Attributes ---------- index : numpy.array The index of all entries across multiple models. """ def __init__(self, nns): self._nns = nns def k_nearest_neighbors(self, fingerprint, k=5, mode="native", view=SequentialView()): """ Retrieves the K nearest neighbors to a fingerprint. Parameters ---------- fingerprint : list, np.array, tuple A fingerprint to use as query. k : int The number of neighbors to retrieve. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. view : cameo.parallel.ParallelView, cameo.parallel.SequentialView A parallel mode runner. Returns ------- dict A dictionary with the InChI Key as key and the distance as value. """ func = KNN(fingerprint, k, mode) results = view.map(func, self._nns) neighbors = {} [neighbors.update(res) for res in results] return dict(sorted(neighbors.items(), key=lambda x: x[1])[:k]) def radius_nearest_neighbors(self, fingerprint, radius=0.25, mode="native", view=SequentialView()): """ Retrieves the nearest neighbors to a fingerprint within a distance radius. Parameters ---------- fingerprint : list, np.array, tuple A fingerprint to use as query. radius : float A distance radius ]0, 1]. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. view : cameo.parallel.ParallelView, cameo.parallel.SequentialView A parallel mode runner. Returns ------- dict A dictionary with the InChI Key as key and the distance as value. """ func = RNN(fingerprint, radius, mode) results = view.map(func, self._nns) neighbors = {} [neighbors.update(res) for res in results] return neighbors def distances(self, fingerprint, mode="native", view=SequentialView()): """ Retrieves the distance a fingerprint and all elements in the model. Parameters ---------- fingerprint : list, np.array, tuple A fingerprint to use as query. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. view : cameo.parallel.ParallelView, cameo.parallel.SequentialView A parallel mode runner. Returns ------- dict A dictionary with the InChI Key as key and the distance as value. """ func = Distance(fingerprint, mode) results = view.map(func, self._nns) distances = {} [distances.update(res) for res in results] return distances def __repr__(self): return " | ".join(repr(nn) for nn in self._nns) def __getitem__(self, index): return self._nns[index] @property def index(self): return np.concatenate([nn.index for nn in self._nns]) def distance_matrix(self, mode="native"): """ Generates a distance matrix between all elements in the models. Parameters ---------- mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. Returns ------- numpy.array The distance matrix. """ index = self.index size = len(index) matrix = np.zeros((size, size), dtype=np.float) for i in range(size): matrix[i] = self.distances(self.feature(i), mode=mode) return matrix def feature(self, index): """ Retrieves the fingerprint at a given index. The index is global for the ensemble of models. Returns ------- numpy.array The fingerprint. Raises ------ IndexError """ total = len(self) if index >= total: raise IndexError(index) group = 0 off = 0 for nn in self._nns: if index + 1 > len(nn): group += 1 off += len(nn) return self._nns[group][index - off] def __len__(self): return sum(len(nn) for nn in self._nns) class NearestNeighbors(model_ext.CNearestNeighbors): def __init__(self, index, features, features_lengths, use_cl=False, opencl_context=None): features = np.concatenate(features).astype(np.int32) features_lengths = np.array(features_lengths, dtype=np.int32) super(NearestNeighbors, self).__init__(features, features_lengths) self._index = index self._use_cl = use_cl if cl_available and self._use_cl: if opencl_context is None: self._ctx = cl.create_some_context() else: self._ctx = opencl_context self._program = cl.Program(self._ctx, nn_source).build() @property def cl_context(self): if not self._use_cl: raise RuntimeError("Configuration is set to don't run CL") return self._ctx @cl_context.setter def cl_context(self, ctx): if not self._use_cl: raise RuntimeError("Configuration is set to don't run CL") self._ctx = ctx self._program = cl.Program(self._ctx, nn_source).build() def queue(self): return cl.CommandQueue(self.cl_context) @property def program(self): if not self._use_cl: raise RuntimeError("Configuration is set to don't run CL") return self._program def __getstate__(self): state = super(NearestNeighbors, self).__getstate__() state.update({"_index": self._index, "_use_cl": self._use_cl}) return state def __getitem__(self, index): start = self.start_positions[index] length = self.start_positions[index] end = start + length return self._features[start:end] def __setstate__(self, state): super(NearestNeighbors, self).__setstate__(state) self._index = state['_index'] self._use_cl = state['_use_cl'] if cl_available and self._use_cl: self.cl_context = cl.create_some_context() def knn(self, fingerprint, k, mode="native"): """ K-Nearest Neighbors Parameters ---------- fingerprint : ndarray The fingerprint to search for. k : int The number of neighbors to return. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. Returns ------- dict (Index --> Distance) """ distances = self.distances(fingerprint, mode) indices = np.argsort(distances) return {i.decode('utf-8'): d for i, d in zip(self._index[indices, 0][:k], distances[indices][:k])} def rnn(self, fingerprint, radius, mode="native"): """ Radius-Nearest Neighbors Parameters ---------- fingerprint : ndarray The fingerprint to search for. radius : float The maximum distance of neighbors to return. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. Returns ------- dict (Index --> Distance) """ distances = self.distances(fingerprint, mode) indices = np.argsort(distances) indices = indices[distances[indices] <= radius] return {i.decode('utf-8'): d for i, d in zip(self._index[indices, 0], distances[indices])} def distances(self, fingerprint, mode="native"): if mode == "native": return self.distances_py(fingerprint) elif mode == "cl": return self.distances_cl(fingerprint) else: raise ValueError("'mode' can only be 'native' or 'cl'") def max_memory_allocation_size(self): return min([d.max_mem_alloc_size for d in self.cl_context.devices]) @timing(debug=True) def distances_cl(self, fingerprint): database_buffer = self.input_buffer(self.features) start_positions_buffer = self.input_buffer(self.start_positions) features_lengths_buffers = self.input_buffer(self.features_lengths) fingerprint_buffer = self.input_buffer(fingerprint) fingerprint_length = np.array([len(fingerprint)]) fingerprint_length_buffer = self.input_buffer(fingerprint_length) distances = np.zeros(len(self._index), dtype=np.float32) distances_buf = self.output_buffer(distances) # Run the kernel queue = self.queue() exec_evt = self.run_kernel(queue, distances.shape, distances_buf, fingerprint_buffer, fingerprint_length_buffer, database_buffer, start_positions_buffer, features_lengths_buffers) # Read the result cl.enqueue_copy(queue, distances, distances_buf, is_blocking=True, wait_for=[exec_evt]).wait() queue.finish() return distances @timing(debug=True) def input_buffer(self, array): return cl.Buffer(self._ctx, MF.READ_ONLY | MF.COPY_HOST_PTR, hostbuf=array) @timing(debug=True) def output_buffer(self, array): return cl.Buffer(self._ctx, MF.WRITE_ONLY, size=array.nbytes) @timing(debug=True) def run_kernel(self, queue, shape, *args): exec_evt = self.program.nn(queue, shape, None, *args) return exec_evt @property def index(self): return self._index @property def data_frame(self): """ Create a DataFrame with this model. Returns ------- pandas.DataFrame A data frame. """ df = DataFrame([self[i] for i in range(len(self))], index=["fingerprint"], columns=self._index) return df.T def __repr__(self): return "NearestNeighbors %i rows" % (len(self)) def __len__(self): return len(self._index) class DBNearestNeighbors(object): def __init__(self, index, session, fingerprint_format, metric='jaccard'): self._index = index self._session = session self.fingerprint_format = fingerprint_format self._neighbors = None self._metric = metric @property def neighbors(self): if self._neighbors is None: logger.info("db-nn: building NearestNeighbors") self._neighbors = neighbors.NearestNeighbors(algorithm='brute', metric=self._metric) self._neighbors.fit(self.features) return self._neighbors def __getitem__(self, index): key = self._index[index] metabolite = self._session.query(Metabolite).filter(Metabolite.inchi_key == key).one() return metabolite.fingerprings[self.fingerprint_format] def knn(self, fingerprint, k, mode="native"): """ K-Nearest Neighbors Parameters ---------- fingerprint : ndarray The fingerprint to search for. k : int The number of neighbors to return. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. Returns ------- dict (Index --> Distance) """ logger.info("db-nn: searching for k-nearest-neighbors (%i)" % k) fingerprint = fingerprint.reshape(1, -1) logger.debug("Reshaped fingerprint %s" % fingerprint) distances, indices = self.neighbors.kneighbors(fingerprint, k, True) distances, indices = distances[0], indices[0] return {self.index[i]: d for i, d in zip(indices, distances)} def rnn(self, fingerprint, radius, mode="native"): """ Radius-Nearest Neighbors Parameters ---------- fingerprint : ndarray The fingerprint to search for. radius : float The maximum distance of neighbors to return. mode : str 'native' to run python implementation or 'cl' to run OpenCL implementation if available. Returns ------- dict (Index --> Distance) """ logger.info("db-nn: searching for radius-nearest-neighbors (%.4f)" % radius) fingerprint = fingerprint.reshape(1, -1) logger.debug("Reshaped fingerprint %s" % fingerprint) distances, indices = self.neighbors.radius_neighbors(fingerprint, radius, True) distances, indices = distances[0], indices[0] return {self.index[i]: d for i, d in zip(indices, distances)} def distances(self, fingerprint, mode="native"): logger.info("db-nn: calculating all distances") fingerprint = fingerprint.reshape(1, -1) distances, indices = self.neighbors.radius_neighbors(fingerprint, 0, True) distances, indices = distances[0], indices[0] return {self.index[i]: d for i, d in zip(indices, distances)} @property def index(self): return [b.decode() for b in self._index[:, 0]] @property def features(self): features = [None for _ in self.index] query = self._session.query(Metabolite).filter( Metabolite.inchi_key.in_(self.index) ).options(load_only('id', 'inchi_key')) indices = {inchi_key: i for i, inchi_key in enumerate(self.index)} for metabolite in query.yield_per(1000): fp = metabolite.fingerprints[self.fingerprint_format] i = indices[metabolite.inchi_key] features[i] = fp assert all(f is not None for f in features) return features @property def data_frame(self): """ Create a DataFrame with this model. Returns ------- pandas.DataFrame A data frame. """ df = DataFrame([self[i] for i in range(len(self))], index=["fingerprint"], columns=self._index) return df.T def __repr__(self): return "DBNearestNeighbors %i rows" % (len(self)) def __len__(self): return len(self._index)
apache-2.0
1,223,818,149,547,254,800
30.655738
120
0.594303
false
zhaque/django-error-capture-middleware
src/django_error_capture_middleware/admin.py
1
1964
# Copyright (c) 2009-2010, Steve 'Ashcrow' Milner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials # provided with the distribution. # * Neither the name of the project nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. """ Bindings for models. """ __docformat__ = 'restructuredtext' from django.contrib import admin from django_error_capture_middleware.models import Error class ErrorAdmin(admin.ModelAdmin): """ Admin binding for Error to include Notes. """ list_display = ('id', 'traceback', 'resolved', 'timestamp') # Register admin admin.site.register(Error, ErrorAdmin)
bsd-3-clause
-7,327,751,584,935,976,000
38.28
69
0.753055
false
nagaozen/my-os-customizations
home/nagaozen/.gnome2/gedit/plugins/align-columns/window_helper.py
1
3590
# Align columns - Gedit plugin # # Copyright (c) 2011 Hugo Henriques Maia Vieira # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. import gtk import os from localization import Localization from text_block import TextBlock, DifferentNumberOfColumnsError, WhiteSpacesError class WindowHelper: """Align text blocks into columns separated by pipe ( , )""" _UI_FILE = os.path.join(os.path.dirname(__file__), 'align_columns_menu.ui.xml') def __init__(self, window): """Constructor.""" self._window = window self._action_group = None Localization.setup() self._insert_menu() def deactivate(self): """Deactivates the plugin for a window.""" self._remove_menu() self._window = None self._action_group = None def update_ui(self): """Reacts on user interface updates for a window.""" self._action_group.set_sensitive(self._has_active_view()) def _insert_menu(self): """Adds the menu entries.""" manager = self._window.get_ui_manager() self._action_group = gtk.ActionGroup("AlignColumnsActions") action_align_columns = gtk.Action("AlignColumns", _("Align columns"), _("Align columns"), None) action_align_columns.connect('activate', self.on_align_columns_activate) self._action_group.add_action_with_accel(action_align_columns, '<Shift><Alt>a') manager.insert_action_group(self._action_group) # Merge the UI self._ui_id = manager.add_ui_from_file(self.__class__._UI_FILE) def _remove_menu(self): """Removes the additional menu entries.""" manager = self._window.get_ui_manager() manager.remove_ui(self._ui_id) manager.remove_action_group(self._action_group) manager.ensure_update() def on_align_columns_activate(self, action): """Callback to align columns on menu click or accelerator.""" doc = self._window.get_active_document() bounds = doc.get_selection_bounds() if not doc or not bounds: return text = doc.get_text(*bounds) try: text_block = TextBlock(text) aligned_columns = text_block.align() doc.delete_interactive(*bounds, default_editable=True) doc.insert(bounds[0], aligned_columns) except WhiteSpacesError: return except DifferentNumberOfColumnsError: message = gtk.MessageDialog(None, 0, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, 'The selection has lines with different numbers of columns.') message.run() message.destroy() def _has_active_view(self): """Returns 'true' if there is an active view.""" return (self._window.get_active_view() != None)
gpl-3.0
3,712,914,509,710,296,000
35.262626
101
0.613928
false
carquois/blobon
blobon/blogs/migrations/0124_auto__add_field_model_hidden__add_field_modelfielddata_foreign.py
1
32164
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Model.hidden' db.add_column('blogs_model', 'hidden', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) # Adding field 'ModelFieldData.foreign' db.add_column('blogs_modelfielddata', 'foreign', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['blogs.ModelFieldData'], null=True), keep_default=False) def backwards(self, orm): # Deleting field 'Model.hidden' db.delete_column('blogs_model', 'hidden') # Deleting field 'ModelFieldData.foreign' db.delete_column('blogs_modelfielddata', 'foreign_id') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'blogs.blog': { 'Meta': {'object_name': 'Blog'}, 'analytics_account': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}), 'contributors': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'blogcontributor'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['auth.User']"}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'custom_domain': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}), 'draft_notice': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'exclusion_end': ('django.db.models.fields.CharField', [], {'max_length': '5', 'blank': 'True'}), 'exclusion_start': ('django.db.models.fields.CharField', [], {'max_length': '5', 'blank': 'True'}), 'facebook_link': ('django.db.models.fields.URLField', [], {'max_length': '100', 'blank': 'True'}), 'fb_page_access_token': ('django.db.models.fields.CharField', [], {'max_length': '260', 'blank': 'True'}), 'frequency': ('django.db.models.fields.CharField', [], {'max_length': '5', 'blank': 'True'}), 'has_artists': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'has_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'header_image': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_bootblog': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_online': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_open': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '7', 'blank': 'True'}), 'main_color': ('django.db.models.fields.CharField', [], {'default': "'#C4BDB2'", 'max_length': '10', 'blank': 'True'}), 'moderator_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'pinterest_link': ('django.db.models.fields.URLField', [], {'max_length': '100', 'blank': 'True'}), 'short_description': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '30'}), 'template': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Template']", 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '240'}), 'translation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Blog']", 'null': 'True', 'blank': 'True'}), 'twitter_link': ('django.db.models.fields.URLField', [], {'max_length': '100', 'blank': 'True'}), 'twitter_oauth_token': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'twitter_oauth_token_secret': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}) }, 'blogs.category': { 'Meta': {'object_name': 'Category'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Blog_category'", 'null': 'True', 'to': "orm['blogs.Blog']"}), 'cat_image': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'cat_image_caret': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'cat_image_close': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'cat_image_email': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'cat_image_fb': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'cat_image_left': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'cat_image_pint': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'cat_image_right': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'cat_image_tw': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'color': ('django.db.models.fields.CharField', [], {'default': "'#000000'", 'max_length': '10'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '140', 'null': 'True', 'blank': 'True'}), 'parent_category': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'child_category'", 'null': 'True', 'to': "orm['blogs.Category']"}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '140', 'blank': 'True'}) }, 'blogs.comment': { 'Meta': {'object_name': 'Comment'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'Comment_author'", 'null': 'True', 'to': "orm['auth.User']"}), 'blog': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Blog']", 'null': 'True'}), 'comment': ('django.db.models.fields.TextField', [], {'max_length': '10000'}), 'comment_status': ('django.db.models.fields.CharField', [], {'default': "'pe'", 'max_length': '2'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '140'}), 'notify_me': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'occupation': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'post': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Post']", 'null': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '300', 'blank': 'True'}) }, 'blogs.info_email': { 'Meta': {'object_name': 'Info_email'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'blog': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Blog']", 'null': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'frequency': ('django.db.models.fields.CharField', [], {'default': "'We'", 'max_length': '2', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'message': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'subject': ('django.db.models.fields.TextField', [], {'max_length': '100', 'blank': 'True'}), 'subscribers': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '2', 'null': 'True'}) }, 'blogs.language': { 'Meta': {'object_name': 'Language'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language_code': ('django.db.models.fields.CharField', [], {'max_length': '5'}), 'language_name': ('django.db.models.fields.CharField', [], {'max_length': '40'}) }, 'blogs.menu': { 'Meta': {'object_name': 'Menu'}, 'blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Blog_menu'", 'null': 'True', 'to': "orm['blogs.Blog']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_main': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}) }, 'blogs.menuitem': { 'Meta': {'object_name': 'MenuItem'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Category']", 'null': 'True', 'blank': 'True'}), 'external_link': ('django.db.models.fields.URLField', [], {'max_length': '140', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'menu': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Menu']", 'null': 'True'}), 'page': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Page']", 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}) }, 'blogs.model': { 'Meta': {'object_name': 'Model'}, 'blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Custom_post'", 'null': 'True', 'to': "orm['blogs.Blog']"}), 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '60'}) }, 'blogs.modeldata': { 'Meta': {'object_name': 'ModelData'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Model']", 'null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "'Unknown'", 'max_length': '140'}) }, 'blogs.modelfield': { 'Meta': {'object_name': 'ModelField'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Model']", 'null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '140', 'null': 'True', 'blank': 'True'}), 'post_type': ('django.db.models.fields.CharField', [], {'default': "'Text'", 'max_length': '40'}), 'rank': ('django.db.models.fields.CharField', [], {'default': "'1'", 'max_length': '2'}) }, 'blogs.modelfielddata': { 'Meta': {'object_name': 'ModelFieldData'}, 'date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '100', 'blank': 'True'}), 'foreign': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.ModelFieldData']", 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'longtext': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'model': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Model']", 'null': 'True'}), 'model_data': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.ModelData']", 'null': 'True'}), 'model_field': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.ModelField']", 'null': 'True'}), 'nullboolean': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'onetofive': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'positiveinteger': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'price': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '6', 'decimal_places': '2', 'blank': 'True'}), 'relation': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'relation'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['blogs.ModelData']"}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '140', 'blank': 'True'}) }, 'blogs.page': { 'Meta': {'object_name': 'Page'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Blog_page'", 'null': 'True', 'to': "orm['blogs.Blog']"}), 'content': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}), 'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '140', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}) }, 'blogs.post': { 'Meta': {'object_name': 'Post'}, 'artist': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}), 'base62id': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'blog': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Blog']", 'null': 'True'}), 'category': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['blogs.Category']", 'null': 'True', 'blank': 'True'}), 'content': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_0': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_01': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_1': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_2': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_3': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_4': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_5': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_6': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'content_video': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'custom_post': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Model']", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_discarded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_ready': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_sticky': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_top': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'karma': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'}), 'layout_type': ('django.db.models.fields.CharField', [], {'default': "'s'", 'max_length': '1'}), 'message': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'pic': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_0': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_04': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_1': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_10': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_11': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_12': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_13': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_14': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_15': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_16': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_17': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_18': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_19': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_2': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_20': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_21': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_22': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_23': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_24': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_25': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_26': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_27': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_28': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_29': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_3': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_30': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_31': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_32': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_33': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_4': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_5': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_6': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_7': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_8': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pic_9': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'pub_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'publish_on_facebook': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '140', 'blank': 'True'}), 'soundcloud_id': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}), 'soundcloud_url': ('django.db.models.fields.URLField', [], {'max_length': '300', 'blank': 'True'}), 'source': ('django.db.models.fields.URLField', [], {'max_length': '300', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'P'", 'max_length': '2', 'null': 'True'}), 'tag': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['blogs.Tag']", 'null': 'True', 'blank': 'True'}), 'temp_tag_field': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'blank': 'True'}), 'text': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'translated_content': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'translated_title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}), 'video': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'video_ogg': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'video_url': ('django.db.models.fields.URLField', [], {'max_length': '300', 'blank': 'True'}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'vimeo_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'vimeo_thumb_url': ('django.db.models.fields.URLField', [], {'max_length': '300', 'blank': 'True'}), 'youtube_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}) }, 'blogs.rss': { 'Meta': {'object_name': 'Rss'}, 'blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Blog_rss'", 'null': 'True', 'to': "orm['blogs.Blog']"}), 'feed_url': ('django.db.models.fields.URLField', [], {'max_length': '300', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'blogs.subscription': { 'Meta': {'object_name': 'Subscription'}, 'blog': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['blogs.Blog']", 'null': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_new': ('django.db.models.fields.BooleanField', [], {'default': 'True'}) }, 'blogs.subuser': { 'Meta': {'object_name': 'Subuser'}, 'blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Blog_user'", 'null': 'True', 'to': "orm['blogs.Blog']"}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}) }, 'blogs.tag': { 'Meta': {'object_name': 'Tag'}, 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Blog_tag'", 'null': 'True', 'to': "orm['blogs.Blog']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '140', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '140', 'blank': 'True'}) }, 'blogs.template': { 'Meta': {'object_name': 'Template'}, 'archives': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'base': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'category': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '60'}), 'single': ('django.db.models.fields.TextField', [], {'max_length': '10000', 'blank': 'True'}) }, 'blogs.translation': { 'Meta': {'object_name': 'Translation'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}), 'origin_blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Translation_origin_blog'", 'null': 'True', 'to': "orm['blogs.Blog']"}), 'translated_blog': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'Translation_translated_blog'", 'null': 'True', 'to': "orm['blogs.Blog']"}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['blogs']
mit
1,610,596,835,419,017,700
88.846369
206
0.53762
false
winxos/python
udpdebug.py
1
1786
# -*- coding: utf-8 -*- ''' p2p server. winxos 2015-12-04 ''' import socket import threading import os import time port = 9010 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # DGRAM -> UDP is_exit = False class getcmd(threading.Thread): global s, clients def __init__(self): threading.Thread.__init__(self) def run(self): while not is_exit: try: cmd = raw_input() cmds = cmd.split() op = cmds[0] if op == "to": if cmds[3].isdigit():#port range for i in range(int(cmds[2]),int(cmds[3])): s.sendto(" ".join(cmds[4:]), (cmds[1],i)) if i%1000==0: time.sleep(1); else: s.sendto(" ".join(cmds[3:]), (cmds[1],int(cmds[2]))) except Exception, e: print("[shell err] %s" % e) class listener(threading.Thread): global s, clients def __init__(self): threading.Thread.__init__(self) def run(self): while not is_exit: try: data, addr = s.recvfrom(1024) print("%s:%s" % (addr, data)) except Exception, e: print("[listen err] %s" % e) if __name__ == '__main__': port = raw_input("input port:") s.bind(('0.0.0.0', int(port))) t = getcmd() t.setDaemon(True) # important t.start() l = listener() l.setDaemon(True) l.start() print("listening...") try: while t.isAlive() and l.isAlive(): pass except KeyboardInterrupt: print("[sys err] user stop.") is_exit = True print("server exit.") os._exit(0)
mit
4,525,472,451,138,704,400
24.514286
76
0.469205
false