content stringlengths 5 1.05M |
|---|
"""
This Python file contains the template for the QuickPACS-style workflow
builder functions and function runners.
The runners are designed to make it easy to run each modular workflow function
without having it connected to a larger workflow - this allows the user to
generate only one needed output if necessary, or allows the developer to
easily run/test the workflow function and build unit tests for it.
Each workflow function has one associated runner function.
"""
def template_workflow(workflow, resource_pool, config, name="_"):
"""Build a Nipype workflow to...
- If any resources/outputs required by this workflow are not in the
resource pool, this workflow will call pre-requisite workflow builder
functions to further populate the pipeline with workflows which will
calculate/generate these necessary pre-requisites.
Expected Resources in Resource Pool
- {resource name}: {resource description}
- {resource name}: {resource description}
- ..
New Resources Added to Resource Pool
- {resource name}: {resource description}
- {resource name}: {resource description}
- ..
Workflow Steps
1. {node 1..}
2. {node 2..}
3. ..
:type workflow: Nipype workflow object
:param workflow: A Nipype workflow object which can already contain other
connected nodes; this function will insert the following
workflow into this one provided.
:type resource_pool: dict
:param resource_pool: A dictionary defining input files and pointers to
Nipype node outputs / workflow connections; the keys
are the resource names.
:type config: dict
:param config: A dictionary defining the configuration settings for the
workflow, such as directory paths or toggled options.
:type name: str
:param name: (default: "_") A string to append to the end of each node
name.
:rtype: Nipype workflow object
:return: The Nipype workflow originally provided, but with this function's
sub-workflow connected into it.
:rtype: dict
:return: The resource pool originally provided, but updated (if
applicable) with the newest outputs and connections.\
"""
import copy
import nipype.interfaces.io as nio
import nipype.pipeline.engine as pe
import nipype.interfaces.utility as util
### Check resource pool for expected resources and call pre-requisite
### workflows if necessary
if "{resource name}" not in resource_pool.keys():
from module import workflow_function
old_rp = copy.copy(resource_pool)
workflow, new_resource_pool = \
workflow_function(workflow, resource_pool, config, name)
if resource_pool == old_rp:
return workflow, resource_pool
### Node declarations and configuration, node connections
node_one = pe.Node(interface=nipype_module.Interface(),
name='node_one%s' % name)
node_two = pe.Node(interface=nipype_module.Interface(),
name='node_two%s' % name)
### Check if the resource is a tuple or a string
### - if it's a tuple: it's a Nipype workflow connection pointer
### - if it's a string: it's a filepath to the resource file on disk
if len(resource_pool["{resource name}"]) == 2:
node, out_file = resource_pool["{resource name}"]
workflow.connect(node, out_file, node_one, 'input_file')
else:
node_one.inputs.in_file = resource_pool["{resource name}"]
workflow.connect(node_one, 'output_file', node_two, 'input_file')
### "Send" final output to resource pool in the form of a Nipype workflow
### connection pointer (the tuple)
resource_pool["{resource name}"] = (node_two, 'output_file')
return workflow, resource_pool
def run_template_workflow(input_resource, out_dir=None, run=True):
"""Run the 'template_workflow' function to execute the modular workflow
with the provided inputs.
:type input_resource: str
:param input_resource: The filepath of the { input resource }. Can have
multiple.
:type out_dir: str
:param out_dir: (default: None) The output directory to write the results
to; if left as None, will write to the current directory.
:type run: bool
:param run: (default: True) Will run the workflow; if set to False, will
connect the Nipype workflow and return the workflow object
instead.
:rtype: str
:return: (if run=True) The filepath of the generated anatomical_reorient
file.
:rtype: Nipype workflow object
:return: (if run=False) The connected Nipype workflow object.
:rtype: str
:return: (if run=False) The base directory of the workflow if it were to
be run.
"""
import os
import glob
import nipype.interfaces.io as nio
import nipype.pipeline.engine as pe
output = "{ output resource name }"
workflow = pe.Workflow(name='workflow_name')
if not out_dir:
out_dir = os.getcwd()
workflow_dir = os.path.join(out_dir, "workflow_output", output)
workflow.base_dir = workflow_dir
resource_pool = {}
config = {}
num_cores_per_subject = 1
resource_pool["input_resource"] = input_resource
workflow, resource_pool = \
template_workflow(workflow, resource_pool, config)
ds = pe.Node(nio.DataSink(), name='datasink_workflow_name')
ds.inputs.base_directory = workflow_dir
node, out_file = resource_pool[output]
workflow.connect(node, out_file, ds, output)
if run == True:
workflow.run(plugin='MultiProc', plugin_args= \
{'n_procs': num_cores_per_subject})
outpath = glob.glob(os.path.join(workflow_dir, output, "*"))[0]
return outpath
else:
return workflow, workflow.base_dir |
from unittest import mock
import urllib
import tornado.web
from monstro import forms, db
from monstro.views import (
View, ListView, TemplateView, DetailView, FormView,
CreateView, UpdateView, RedirectView, DeleteView
)
from monstro.views.authenticators import CookieAuthenticator
import monstro.testing
class User(db.Model):
value = db.String()
class Meta:
collection = 'users'
class UserForm(forms.ModelForm):
value = forms.String()
class Meta:
model = User
class RedirectViewTest(monstro.testing.AsyncHTTPTestCase):
def get_app(self):
class TestView(RedirectView):
redirect_url = '/r'
return tornado.web.Application([tornado.web.url(r'/', TestView)])
def test_get(self):
response = self.fetch('/', follow_redirects=False)
self.assertEqual(301, response.code)
class ViewTest(monstro.testing.AsyncHTTPTestCase):
class TestView(View):
authenticators = (CookieAuthenticator(User, 'value'),)
async def get(self):
self.write(self.request.method)
@View.authenticated('/')
async def options(self):
self.write(self.request.method)
@View.authenticated('http://github.com')
async def head(self):
self.write(self.request.method)
def get_app(self):
return tornado.web.Application(
[tornado.web.url(r'/', self.TestView)],
cookie_secret='test'
)
def test_get(self):
response = self.fetch('/')
self.assertEqual(200, response.code)
self.assertEqual('GET', response.body.decode('utf-8'))
def test_get_auth(self):
user = self.run_sync(User.objects.create, value='test')
with mock.patch.object(self.TestView, 'get_secure_cookie') as m:
m.return_value = user.value.encode()
response = self.fetch('/', method='OPTIONS')
self.assertEqual(200, response.code)
self.assertEqual('OPTIONS', response.body.decode('utf-8'))
def test_get_auth__error(self):
response = self.fetch('/', method='OPTIONS', follow_redirects=False)
self.assertEqual(302, response.code)
def test_get_auth__error__absolute_url(self):
response = self.fetch('/', method='HEAD', follow_redirects=False)
self.assertEqual(302, response.code)
class TemplateViewTest(monstro.testing.AsyncHTTPTestCase):
class TestView(TemplateView):
template_name = 'index.html'
def get_app(self):
return tornado.web.Application([tornado.web.url(r'/', self.TestView)])
def test_get(self):
with mock.patch.object(self.TestView, 'render_string') as m:
m.return_value = 'test'
response = self.fetch('/')
self.assertEqual(200, response.code)
self.assertEqual('test', response.body.decode('utf-8'))
class ListViewTest(monstro.testing.AsyncHTTPTestCase):
class TestView(ListView):
model = User
template_name = 'index.html'
class TestSearchView(ListView):
model = User
template_name = 'index.html'
search_fields = ('value',)
def get_app(self):
return tornado.web.Application([
tornado.web.url(r'/', self.TestView),
tornado.web.url(r'/search', self.TestSearchView),
])
def test_get(self):
with mock.patch.object(self.TestView, 'render_string') as m:
m.return_value = 'test'
response = self.fetch('/')
self.assertEqual(200, response.code)
self.assertEqual('test', response.body.decode('utf-8'))
def test_get__search(self):
with mock.patch.object(self.TestSearchView, 'render_string') as m:
m.return_value = 'test'
response = self.fetch('/search?q=1')
self.assertEqual(200, response.code)
self.assertEqual('test', response.body.decode('utf-8'))
class DetailViewTest(monstro.testing.AsyncHTTPTestCase):
class TestView(DetailView):
model = User
template_name = 'index.html'
lookup_field = 'value'
def get_app(self):
return tornado.web.Application(
[tornado.web.url(r'/(?P<value>\w+)', self.TestView)]
)
def test_get(self):
user = self.run_sync(User.objects.create, value='test')
with mock.patch.object(self.TestView, 'render_string') as m:
m.return_value = 'test'
response = self.fetch('/{}'.format(user.value))
self.assertEqual(200, response.code)
self.assertEqual('test', response.body.decode('utf-8'))
def test_get_404(self):
with mock.patch.object(self.TestView, 'render_string') as m:
m.return_value = 'test'
response = self.fetch('/wrong')
self.assertEqual(404, response.code)
class FormViewTest(monstro.testing.AsyncHTTPTestCase):
class TestView(FormView):
form_class = UserForm
template_name = 'index.html'
redirect_url = '/'
async def form_valid(self, form):
await form.save()
return await super().form_valid(form)
def get_app(self):
return tornado.web.Application(
[tornado.web.url(r'/', self.TestView)]
)
def test_get(self):
with mock.patch.object(self.TestView, 'render_string') as m:
m.return_value = 'test'
response = self.fetch('/')
self.assertEqual(200, response.code)
self.assertEqual('test', response.body.decode('utf-8'))
def test_post(self):
data = {'value': 'test'}
response = self.fetch(
'/', method='POST', body=urllib.parse.urlencode(data),
follow_redirects=False
)
self.assertEqual(302, response.code)
self.run_sync(User.objects.get, **data)
def test_post__invalid(self):
with mock.patch.object(self.TestView, 'render_string') as m:
m.return_value = 'test'
response = self.fetch('/', method='POST', body='')
self.assertEqual(200, response.code)
class CreateViewTest(monstro.testing.AsyncHTTPTestCase):
class TestView(CreateView):
model = User
template_name = 'index.html'
redirect_url = '/'
def get_app(self):
return tornado.web.Application(
[tornado.web.url(r'/', self.TestView)]
)
def test_get(self):
with mock.patch.object(self.TestView, 'render_string') as m:
m.return_value = 'test'
response = self.fetch('/')
self.assertEqual(200, response.code)
self.assertEqual('test', response.body.decode('utf-8'))
def test_post(self):
data = {'value': 'test'}
response = self.fetch(
'/', method='POST', body=urllib.parse.urlencode(data),
follow_redirects=False
)
self.assertEqual(302, response.code)
self.run_sync(User.objects.get, **data)
class UpdateViewTest(monstro.testing.AsyncHTTPTestCase):
class TestView(UpdateView): # pylint:disable=R0901
model = User
template_name = 'index.html'
redirect_url = '/'
lookup_field = 'value'
def get_app(self):
return tornado.web.Application(
[tornado.web.url(r'/(?P<value>\w+)', self.TestView)]
)
def test_post(self):
user = self.run_sync(User.objects.create, value='test')
data = {'value': user.value[::-1]}
response = self.fetch(
'/{}'.format(user.value), method='POST',
body=urllib.parse.urlencode(data), follow_redirects=False
)
self.assertEqual(302, response.code)
self.assertEqual(user._id, self.run_sync(User.objects.get, **data)._id)
class DeleteViewTest(monstro.testing.AsyncHTTPTestCase):
class TestView(DeleteView):
model = User
redirect_url = '/'
lookup_field = 'value'
def get_app(self):
return tornado.web.Application(
[tornado.web.url(r'/(?P<value>\w+)', self.TestView)]
)
def test_delete(self):
user = self.run_sync(User.objects.create, value='test')
response = self.fetch(
'/{}'.format(user.value),
method='DELETE',
follow_redirects=False
)
self.assertEqual(301, response.code)
with self.assertRaises(User.DoesNotExist):
self.run_sync(User.objects.get, value=user.value)
|
import matplotlib.pyplot as plt
import pandas as pd
# 数据文件high-speed rail.csv存放着世界各国高速铁路的情况
# 1)各国运营里程对比柱状图, 标注China为“Longest”
data = pd.read_csv('High-speed+rail.csv', index_col='Country')
print(data)
print(data['Operation'])
operation = data['Operation']
operation.plot(title='Operation Mileage', kind='bar', use_index=True, fontsize='small')
plt.xlabel('Country')
plt.ylabel('Mileage(km)')
plt.annotate('Longest', xy=(0, operation['China']), xytext=(2, operation['China']), arrowprops=dict(arrowstyle='->'))
plt.show()
# 2)各国运营里程现状和发展堆叠柱状图
data.plot(title='Global trends of high-speed rail', kind='barh', stacked=True, use_index=True, fontsize='small')
plt.ylabel('Country')
plt.xlabel('Mileage(km)')
plt.show()
# 3)各国运营里程占比饼图,China扇形离开中心点
operation.plot(title='Operation Mileage', kind='pie', use_index=True, fontsize='small', explode=[0.2, 0, 0, 0, 0, 0], autopct='%0.0f%%', startangle=60)
plt.show()
# 【提示】:
# 从文件中读取数据时,使用第一列数据作为index
# data = pd.read_csv(‘High-speed rail.csv’, index_col =‘Country’) ,获取中国对应的数据行,使用data ['China’] |
mail_box = input('Enter a file name: ')
file = open(mail_box, 'r')
count = 0
for line in file:
if line.startswith('From '):
words = line.split()
print(words[1])
count += 1
print('There are', count, 'lines in the file with From as the first word')
|
import time
from playwright.sync_api import sync_playwright, Route
from playwright.sync_api import Request
from pages.login_page.login_page import LoginPage
from pages.main_page.main_page import MainPage
from models.user import User, fake_user
from test.test_base import *
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
login_page = LoginPage(base_url, page)
login_page.open()
def log_and_continue_request(route, request: Request):
print(request.url)
print(request.post_data)
route.continue_()
page.route('**', lambda route, request: log_and_continue_request(route, request))
# login_page.login("%s@gmail.com" % username, password)
#
# print("======||======= Auth Response:")
# auth_resp: Response = page.waitForResponse("**/api/users/login")
# print(auth_resp.url)
# print(auth_resp.body())
with page.expect_response("**/api/users/login") as resp:
login_page.login("%s@gmail.com" % username, password)
auth_resp = resp.value
import json
user: User = json.loads(auth_resp.body())
print(str(user))
print(str(user["user"]['username']))
print(str(user["user"]['token']))
assert MainPage(base_url, page).account_button(username).innerText() == username
page.goto("%s/#/" % base_url)
print(page.context.cookies())
browser.close()
# with sync_playwright() as p:
# browser = p.chromium.launch(headless=False)
# page = browser.new_page()
#
# def print_requests(request: Request):
# print(request.url)
#
# page.on("request", lambda request: print_requests(request))
#
# def filter_requests(route: Route, request: Request):
# # 1. Replace all images on parrot image
# if route.request.resource_type != 'image':
# return route.continue_()
# else:
# lorem_flickr = "https://loremflickr.com"
# route.fulfill(status=301, headers={'location': f"{lorem_flickr}/320/240/parrot"})
# # 2. Filter advertisement
# # if request.frame.parentFrame:
# # route.abort()
# # else:
# # route.continue_()
#
# page.route('**/*', lambda route, request: filter_requests(route, request))
#
# page.goto("https://www.theverge.com")
# time.sleep(4)
# browser.close()
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# @author:Spring
# 斯坦福大学官网有完整的课程计划和视频.
# 其中自然语言处理推荐CS224,
# 如果是图像处理好象是CS231.
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.estimators.estimator import SKCompat
from tensorflow.python.ops import array_ops as array_ops_
import matplotlib.pyplot as plt
learn = tf.contrib.learn
HIDDEN_SIZE = 30
NUM_LAYERS = 2
TIMESTEPS = 10
TRAINING_STEPS = 3000
BATCH_SIZE = 32
TRAINING_EXAMPLES = 10000
TESTING_EXAMPLES = 1000
SAMPLE_GAP = 0.01
def generate_data(seq):
X = []
y = []
for i in range(len(seq) - TIMESTEPS - 1):
X.append([seq[i: i + TIMESTEPS]])
y.append([seq[i + TIMESTEPS]])
return np.array(X, dtype=np.float32), np.array(y, dtype=np.float32)
def lstm_model(X, y):
lstm_cell = tf.contrib.rnn.BasicLSTMCell(HIDDEN_SIZE, state_is_tuple=True)
cell = tf.contrib.rnn.MultiRNNCell([lstm_cell] * NUM_LAYERS)
output, _ = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
output = tf.reshape(output, [-1, HIDDEN_SIZE])
# 通过无激活函数的全联接层计算线性回归,并将数据压缩成一维数组的结构。
predictions = tf.contrib.layers.fully_connected(output, 1, None)
# 将predictions和labels调整统一的shape
labels = tf.reshape(y, [-1])
predictions = tf.reshape(predictions, [-1])
loss = tf.losses.mean_squared_error(predictions, labels)
train_op = tf.contrib.layers.optimize_loss(
loss, tf.contrib.framework.get_global_step(),
optimizer="Adagrad", learning_rate=0.1)
return predictions, loss, train_op
# 封装之前定义的lstm。
regressor = SKCompat(learn.Estimator(model_fn=lstm_model,model_dir="Models/model_2"))
# 生成数据。
test_start = TRAINING_EXAMPLES * SAMPLE_GAP
test_end = (TRAINING_EXAMPLES + TESTING_EXAMPLES) * SAMPLE_GAP
train_X, train_y = generate_data(np.sin(np.linspace(
0, test_start, TRAINING_EXAMPLES, dtype=np.float32)))
test_X, test_y = generate_data(np.sin(np.linspace(
test_start, test_end, TESTING_EXAMPLES, dtype=np.float32)))
# 拟合数据。
regressor.fit(train_X, train_y, batch_size=BATCH_SIZE, steps=TRAINING_STEPS)
# 计算预测值。
predicted = [[pred] for pred in regressor.predict(test_X)]
# 计算MSE。
rmse = np.sqrt(((predicted - test_y) ** 2).mean(axis=0))
print ("Mean Square Error is: %f" % rmse[0])
plot_predicted, = plt.plot(predicted, label='predicted')
plot_test, = plt.plot(test_y, label='real_sin')
plt.legend([plot_predicted, plot_test],['predicted', 'real_sin'])
plt.show()
|
from __future__ import unicode_literals
from django.contrib import admin
from django_business_rules.models import BusinessRuleModel
@admin.register(BusinessRuleModel)
class BusinessRuleAdmin(admin.ModelAdmin):
pass
|
# coding=utf-8
import tensorflow as tf
import logging
import os
from algorithm import config
from base.env.stock_market import Market
from base.nn.tf.model import BaseSLTFModel
from checkpoints import CHECKPOINTS_DIR
from helper.args_parser import model_launcher_parser
class Algorithm(BaseSLTFModel):
def __init__(self, session, env, seq_length, x_space, y_space, **options):
super(Algorithm, self).__init__(session, env, **options)
self.seq_length, self.x_space, self.y_space = seq_length, x_space, y_space
try:
self.hidden_size = options['hidden_size']
except KeyError:
self.hidden_size = 1
self._init_input()
self._init_nn()
self._init_op()
self._init_saver()
def _init_input(self):
self.x = tf.placeholder(tf.float32, [None, self.seq_length, self.x_space])
self.label = tf.placeholder(tf.float32, [None, self.y_space])
def _init_nn(self):
self.rnn = self.add_rnn(1, self.hidden_size)
self.rnn_output, _ = tf.nn.dynamic_rnn(self.rnn, self.x, dtype=tf.float32)
self.rnn_output = self.rnn_output[:, -1]
self.rnn_output_dense = self.add_fc(self.rnn_output, 16)
self.y = self.add_fc(self.rnn_output_dense, self.y_space)
def _init_op(self):
self.loss = tf.losses.mean_squared_error(self.y, self.label)
self.global_step = tf.Variable(0, trainable=False)
self.optimizer = tf.train.RMSPropOptimizer(self.learning_rate)
self.train_op = self.optimizer.minimize(self.loss)
self.session.run(tf.global_variables_initializer())
def train(self):
for step in range(self.train_steps):
batch_x, batch_y = self.env.get_stock_batch_data(self.batch_size)
_, loss = self.session.run([self.train_op, self.loss], feed_dict={self.x: batch_x, self.label: batch_y})
if (step + 1) % 1000 == 0:
logging.warning("Step: {0} | Loss: {1:.7f}".format(step + 1, loss))
if step > 0 and (step + 1) % self.save_step == 0:
if self.enable_saver:
self.save(step)
def predict(self, x):
return self.session.run(self.y, feed_dict={self.x: x})
def main(args):
env = Market(args.codes, **{"use_sequence": True})
algorithm = Algorithm(tf.Session(config=config), env, env.seq_length, env.data_dim, env.code_count, **{
"mode": args.mode,
# "mode": "test",
"save_path": os.path.join(CHECKPOINTS_DIR, "SL", "NaiveLSTM", "model"),
"enable_saver": True,
})
algorithm.run()
algorithm.eval_and_plot()
if __name__ == '__main__':
main(model_launcher_parser.parse_args())
|
# -*- coding: utf-8 -*-
# Copyright (c) 2020, ifitwala and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import getdate, add_years, date_diff, nowdate
from frappe.model.document import Document
class StudentApplicant(Document):
def validate(self):
self.validate_dates()
def on_update_after_submit(self):
student = frappe.get_doc("Student", filters = {"student_applicant", self.name})
if student:
frappe.throw(_("You cannot change fields as student {0} is linked with application {1}").format(get_link_to_form("Student", student[0].name), self.name))
def validate_dates(self):
if self.date_of_birth and getdate(self.date_of_birth) >= getdate():
frappe.throw(_("The date of birth {0} cannot be after today. Please adjust the dates.").format(self.date_of_birth))
self.title = " ".join(filter(None, [self.first_name, self.middle_name, self.last_name]))
if self.student_admission and self.program and self.date_of_birth:
self.validate_admission_age()
def validate_admission_age(self):
student_admission = get_student_admission_data(self.student_admission, self.program)
if student_admission and student_admission.cutoff_birthdate and getdate(self.date_of_birth) > getdate(student_admission.cutoff_birthdate):
frappe.throw(_("{0} is not eligible for admission to this program as per date of birth.").format(self.title))
if student_admission and student_admission.maximum_age and date_diff(nowdate(), add_years(get_date(self.date_of_birth), student_admission.maximum_age)) > 0:
frappe.throw(_("{0} is not eligible for admission to this program as per date of birth.").format(self.title))
def get_student_admission_data(student_admission, program):
student_admission = frappe.db.sql("""select sa.admission_start_date, sa.admission_end_date,
sap.program, sap.cutoff_birthdate, sap.maximum_age
from `tabStudent Admission` sa, `tabStudent Admission Program`sap
where sa.name = sap.parent and sa.name = %s and sap.program = %s """, (student_admission, program), as_dict=1)
if student_admission:
return student_admission[0]
else:
return None
|
import os
import secrets
def create_env_file():
prompt = "> "
print("APP_SETTINGS= ? ex. production, development, testing, staging")
APP_SETTINGS = input(prompt)
print("FLASK_APP= ? ex. run.py")
FLASK_APP = input(prompt)
print("FLASK_ENV= ? ex. development, production")
FLASK_ENV = input(prompt)
print("POSTGRES_USER= ?")
POSTGRES_USER = input(prompt)
print("POSTGRES_PW= ?")
POSTGRES_PW = input(prompt)
print("DATABASE= ?")
DATABASE = input(prompt)
print("REDIS_PW= ?")
REDIS_PW = input(prompt)
print("BROKER_USER= ?")
BROKER_USER = input(prompt)
print("BROKER_PW= ?")
BROKER_PW = input(prompt)
SECRET_KEY = secrets.token_hex(32)
JWT_SECRET = secrets.token_hex(32)
env_list = [
"APP_SETTINGS={}".format(APP_SETTINGS),
"FLASK_ENV={}".format(FLASK_ENV),
"FLASK_APP={}".format(FLASK_APP),
"POSTGRES_USER={}".format(POSTGRES_USER),
"POSTGRES_PW={}".format(POSTGRES_PW),
"DATABASE={}".format(DATABASE),
"REDIS_PW={}".format(REDIS_PW),
"BROKER_USER={}".format(BROKER_USER),
"BROKER_PW={}".format(BROKER_PW),
"SECRET_KEY={}".format(SECRET_KEY),
"JWT_SECRET={}".format(JWT_SECRET)
]
with open(os.path.join('../../..', '.env'), 'a') as f:
[ f.write(env_var) for env_var in env_list ]
f.close()
def main():
create_env_file()
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
#
import numpy
import pytest
import colorio
numpy.random.seed(0)
@pytest.mark.parametrize('xyz', [
numpy.random.rand(3),
numpy.random.rand(3, 7),
numpy.random.rand(3, 4, 5),
])
def test_conversion(xyz):
# test with srgb conditions
L_A = 64 / numpy.pi / 5
ciecam02 = colorio.CIECAM02(0.69, 20, L_A)
J, C, H, h, M, s, Q = ciecam02.from_xyz100(xyz)
out = ciecam02.to_xyz100(numpy.array([J, C, H]), 'JCH')
assert numpy.all(abs(xyz - out) < 1.0e-13 * abs(xyz))
out = ciecam02.to_xyz100(numpy.array([Q, M, h]), 'QMh')
assert numpy.all(abs(xyz - out) < 1.0e-13 * abs(xyz))
out = ciecam02.to_xyz100(numpy.array([J, s, h]), 'Jsh')
assert numpy.all(abs(xyz - out) < 1.0e-13 * abs(xyz))
return
def test_breakdown():
bad_xyz = [8.71292997, 2.02183974, 83.26198455]
L_A = 64 / numpy.pi / 5
ciecam02 = colorio.CIECAM02(0.69, 20, L_A)
with pytest.raises(colorio.ciecam02.NegativeAError):
ciecam02.from_xyz100(bad_xyz)
return
@pytest.mark.parametrize('variant', [
'LCD', 'SCD', 'UCS',
])
@pytest.mark.parametrize('xyz', [
numpy.random.rand(3),
numpy.random.rand(3, 7),
numpy.random.rand(3, 4, 5),
])
def test_conversion_variants(variant, xyz):
# test with srgb conditions
L_A = 64 / numpy.pi / 5
cam02 = colorio.CAM02(variant, 0.69, 20, L_A)
out = cam02.to_xyz100(cam02.from_xyz100(xyz))
assert numpy.all(abs(xyz - out) < 1.0e-14)
return
@pytest.mark.parametrize('xyz', [
numpy.zeros(3),
numpy.zeros((3, 4, 5)),
])
def test_zero(xyz):
L_A = 64 / numpy.pi / 5
cs = colorio.CIECAM02(0.69, 20, L_A)
J, C, H, h, M, s, Q = cs.from_xyz100(xyz)
assert numpy.all(J == 0.0)
assert numpy.all(C == 0.0)
assert numpy.all(h == 0.0)
assert numpy.all(M == 0.0)
assert numpy.all(s == 0.0)
assert numpy.all(Q == 0.0)
out = cs.to_xyz100(numpy.array([J, C, H]), 'JCH')
assert numpy.all(abs(out) < 1.0e-13)
out = cs.to_xyz100(numpy.array([Q, M, h]), 'QMh')
assert numpy.all(abs(out) < 1.0e-13)
out = cs.to_xyz100(numpy.array([J, s, h]), 'Jsh')
assert numpy.all(abs(out) < 1.0e-13)
return
def test_gold():
# See
# https://github.com/njsmith/colorspacious/blob/master/colorspacious/gold_values.py
xyz = [19.31, 23.93, 10.14]
ciecam02 = colorio.CIECAM02(0.69, 18, 200, whitepoint=[98.88, 90, 32.03])
values = ciecam02.from_xyz100(xyz)
reference_values = numpy.array([
# J, C, H, h, M, s, Q
48.0314, 38.7789, 240.8885, 191.0452, 38.7789, 46.0177, 183.1240
])
assert numpy.all(
abs(values - reference_values) < 1.0e-6 * reference_values
)
# different L_A
xyz = [19.31, 23.93, 10.14]
ciecam02 = colorio.CIECAM02(0.69, 18, 20, whitepoint=[98.88, 90, 32.03])
values = ciecam02.from_xyz100(xyz)
reference_values = numpy.array([
# J, C, H, h, M, s, Q
47.6856, 36.0527, 232.6630, 185.3445, 29.7580, 51.1275, 113.8401
])
assert numpy.all(
abs(values - reference_values) < 1.0e-5 * reference_values
)
# gold values from Mark Fairchild's spreadsheet at
# http://rit-mcsl.org/fairchild//files/AppModEx.xls
xyz = [19.01, 20.00, 21.78]
ciecam02 = colorio.CIECAM02(
0.69, 20, 318.30988618379, whitepoint=[95.05, 100.0, 108.88]
)
values = ciecam02.from_xyz100(xyz)
reference_values = numpy.array([
# J, C, H, h, M, s, Q
4.17310911e+01, 1.04707861e-01, 2.78060724e+02, 2.19048423e+02,
1.08842280e-01, 2.36030659e+00, 1.95371311e+02
])
assert numpy.all(
abs(values - reference_values) < 1.0e-8 * reference_values
)
xyz = [57.06, 43.06, 31.96]
ciecam02 = colorio.CIECAM02(
0.69, 20, 31.830988618379, whitepoint=[95.05, 100.0, 108.88],
)
values = ciecam02.from_xyz100(xyz)
reference_values = numpy.array([
# J, C, H, h, M, s, Q
65.95523, 48.57050, 399.38837, 19.55739, 41.67327, 52.24549, 152.67220
])
assert numpy.all(
abs(values - reference_values) < 1.0e-6 * reference_values
)
return
# @pytest.mark.parametrize('variant, xyz100, ref', [
# # From
# <https://github.com/njsmith/colorspacious/blob/master/colorspacious/gold_values.py>.
# ('UCS', [50, 20, 10], [62.96296296, 16.22742674, 2.86133316]),
# ('UCS', [10, 60, 100], [15.88785047, -6.56546789, 37.23461867]),
# ('LCD', [50, 20, 10], [81.77008177, 18.72061994, 3.30095039]),
# ('LCD', [10, 60, 100], [20.63357204, -9.04659289, 51.30577777]),
# ('SCD', [50, 20, 10], [50.77658303, 14.80756375, 2.61097301]),
# ('SCD', [10, 60, 100], [12.81278263, -5.5311588, 31.36876036]),
# ])
# def test_reference(variant, xyz100, ref):
# cs = colorio.CAM02(
# variant, whitepoint=numpy.array([96.422, 100, 82.521])/100
# )
# xyz = numpy.array(xyz100) / 100
# assert numpy.all(
# abs(cs.from_xyz100(xyz) - ref) < 1.0e-6 * abs(numpy.array(ref))
# )
# return
if __name__ == '__main__':
test_gold()
|
from pandas import Series
s = Series([100, 200, 300, 400])
print(s /10)
|
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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.
#
# ##### END GPL LICENSE BLOCK #####
# Copyright 2011, Ryan Inch
import bpy
from .internals import (
layer_collections,
qcd_slots,
expanded,
expand_history,
rto_history,
copy_buffer,
swap_buffer,
update_property_group,
get_move_selection,
)
mode_converter = {
'EDIT_MESH': 'EDIT',
'EDIT_CURVE': 'EDIT',
'EDIT_SURFACE': 'EDIT',
'EDIT_TEXT': 'EDIT',
'EDIT_ARMATURE': 'EDIT',
'EDIT_METABALL': 'EDIT',
'EDIT_LATTICE': 'EDIT',
'POSE': 'POSE',
'SCULPT': 'SCULPT',
'PAINT_WEIGHT': 'WEIGHT_PAINT',
'PAINT_VERTEX': 'VERTEX_PAINT',
'PAINT_TEXTURE': 'TEXTURE_PAINT',
'PARTICLE': 'PARTICLE_EDIT',
'OBJECT': 'OBJECT',
'PAINT_GPENCIL': 'PAINT_GPENCIL',
'EDIT_GPENCIL': 'EDIT_GPENCIL',
'SCULPT_GPENCIL': 'SCULPT_GPENCIL',
'WEIGHT_GPENCIL': 'WEIGHT_GPENCIL',
'VERTEX_GPENCIL': 'VERTEX_GPENCIL',
}
rto_path = {
"exclude": "exclude",
"select": "collection.hide_select",
"hide": "hide_viewport",
"disable": "collection.hide_viewport",
"render": "collection.hide_render",
"holdout": "holdout",
"indirect": "indirect_only",
}
set_off_on = {
"exclude": {
"off": True,
"on": False
},
"select": {
"off": True,
"on": False
},
"hide": {
"off": True,
"on": False
},
"disable": {
"off": True,
"on": False
},
"render": {
"off": True,
"on": False
},
"holdout": {
"off": False,
"on": True
},
"indirect": {
"off": False,
"on": True
}
}
get_off_on = {
False: {
"exclude": "on",
"select": "on",
"hide": "on",
"disable": "on",
"render": "on",
"holdout": "off",
"indirect": "off",
},
True: {
"exclude": "off",
"select": "off",
"hide": "off",
"disable": "off",
"render": "off",
"holdout": "on",
"indirect": "on",
}
}
def get_rto(layer_collection, rto):
if rto in ["exclude", "hide", "holdout", "indirect"]:
return getattr(layer_collection, rto_path[rto])
else:
collection = getattr(layer_collection, "collection")
return getattr(collection, rto_path[rto].split(".")[1])
def set_rto(layer_collection, rto, value):
if rto in ["exclude", "hide", "holdout", "indirect"]:
setattr(layer_collection, rto_path[rto], value)
else:
collection = getattr(layer_collection, "collection")
setattr(collection, rto_path[rto].split(".")[1], value)
def apply_to_children(parent, apply_function):
# works for both Collections & LayerCollections
child_lists = [parent.children]
while child_lists:
new_child_lists = []
for child_list in child_lists:
for child in child_list:
apply_function(child)
if child.children:
new_child_lists.append(child.children)
child_lists = new_child_lists
def isolate_rto(cls, self, view_layer, rto, *, children=False):
off = set_off_on[rto]["off"]
on = set_off_on[rto]["on"]
laycol_ptr = layer_collections[self.name]["ptr"]
target = rto_history[rto][view_layer]["target"]
history = rto_history[rto][view_layer]["history"]
# get active collections
active_layer_collections = [x["ptr"] for x in layer_collections.values()
if get_rto(x["ptr"], rto) == on]
# check if previous state should be restored
if cls.isolated and self.name == target:
# restore previous state
for x, item in enumerate(layer_collections.values()):
set_rto(item["ptr"], rto, history[x])
# reset target and history
del rto_history[rto][view_layer]
cls.isolated = False
# check if all RTOs should be activated
elif (len(active_layer_collections) == 1 and
active_layer_collections[0].name == self.name):
# activate all collections
for item in layer_collections.values():
set_rto(item["ptr"], rto, on)
# reset target and history
del rto_history[rto][view_layer]
cls.isolated = False
else:
# isolate collection
rto_history[rto][view_layer]["target"] = self.name
# reset history
history.clear()
# save state
for item in layer_collections.values():
history.append(get_rto(item["ptr"], rto))
child_states = {}
if children:
# get child states
def get_child_states(layer_collection):
child_states[layer_collection.name] = get_rto(layer_collection, rto)
apply_to_children(laycol_ptr, get_child_states)
# isolate collection
for item in layer_collections.values():
if item["name"] != laycol_ptr.name:
set_rto(item["ptr"], rto, off)
set_rto(laycol_ptr, rto, on)
if rto not in ["exclude", "holdout", "indirect"]:
# activate all parents
laycol = layer_collections[self.name]
while laycol["id"] != 0:
set_rto(laycol["ptr"], rto, on)
laycol = laycol["parent"]
if children:
# restore child states
def restore_child_states(layer_collection):
set_rto(layer_collection, rto, child_states[layer_collection.name])
apply_to_children(laycol_ptr, restore_child_states)
else:
if children:
# restore child states
def restore_child_states(layer_collection):
set_rto(layer_collection, rto, child_states[layer_collection.name])
apply_to_children(laycol_ptr, restore_child_states)
elif rto == "exclude":
# deactivate all children
def deactivate_all_children(layer_collection):
set_rto(layer_collection, rto, True)
apply_to_children(laycol_ptr, deactivate_all_children)
cls.isolated = True
def toggle_children(self, view_layer, rto):
laycol_ptr = layer_collections[self.name]["ptr"]
# clear rto history
del rto_history[rto][view_layer]
rto_history[rto+"_all"].pop(view_layer, None)
# toggle rto state
state = not get_rto(laycol_ptr, rto)
set_rto(laycol_ptr, rto, state)
def set_state(layer_collection):
set_rto(layer_collection, rto, state)
apply_to_children(laycol_ptr, set_state)
def activate_all_rtos(view_layer, rto):
off = set_off_on[rto]["off"]
on = set_off_on[rto]["on"]
history = rto_history[rto+"_all"][view_layer]
# if not activated, activate all
if len(history) == 0:
keep_history = False
for item in reversed(list(layer_collections.values())):
if get_rto(item["ptr"], rto) == off:
keep_history = True
history.append(get_rto(item["ptr"], rto))
set_rto(item["ptr"], rto, on)
if not keep_history:
history.clear()
history.reverse()
else:
for x, item in enumerate(layer_collections.values()):
set_rto(item["ptr"], rto, history[x])
# clear rto history
del rto_history[rto+"_all"][view_layer]
def invert_rtos(view_layer, rto):
if rto == "exclude":
orig_values = []
for item in layer_collections.values():
orig_values.append(get_rto(item["ptr"], rto))
for x, item in enumerate(layer_collections.values()):
set_rto(item["ptr"], rto, not orig_values[x])
else:
for item in layer_collections.values():
set_rto(item["ptr"], rto, not get_rto(item["ptr"], rto))
# clear rto history
rto_history[rto].pop(view_layer, None)
def copy_rtos(view_layer, rto):
if not copy_buffer["RTO"]:
# copy
copy_buffer["RTO"] = rto
for laycol in layer_collections.values():
copy_buffer["values"].append(get_off_on[
get_rto(laycol["ptr"], rto)
][
rto
]
)
else:
# paste
for x, laycol in enumerate(layer_collections.values()):
set_rto(laycol["ptr"],
rto,
set_off_on[rto][
copy_buffer["values"][x]
]
)
# clear rto history
rto_history[rto].pop(view_layer, None)
del rto_history[rto+"_all"][view_layer]
# clear copy buffer
copy_buffer["RTO"] = ""
copy_buffer["values"].clear()
def swap_rtos(view_layer, rto):
if not swap_buffer["A"]["values"]:
# get A
swap_buffer["A"]["RTO"] = rto
for laycol in layer_collections.values():
swap_buffer["A"]["values"].append(get_off_on[
get_rto(laycol["ptr"], rto)
][
rto
]
)
else:
# get B
swap_buffer["B"]["RTO"] = rto
for laycol in layer_collections.values():
swap_buffer["B"]["values"].append(get_off_on[
get_rto(laycol["ptr"], rto)
][
rto
]
)
# swap A with B
for x, laycol in enumerate(layer_collections.values()):
set_rto(laycol["ptr"], swap_buffer["A"]["RTO"],
set_off_on[
swap_buffer["A"]["RTO"]
][
swap_buffer["B"]["values"][x]
]
)
set_rto(laycol["ptr"], swap_buffer["B"]["RTO"],
set_off_on[
swap_buffer["B"]["RTO"]
][
swap_buffer["A"]["values"][x]
]
)
# clear rto history
swap_a = swap_buffer["A"]["RTO"]
swap_b = swap_buffer["B"]["RTO"]
rto_history[swap_a].pop(view_layer, None)
rto_history[swap_a+"_all"].pop(view_layer, None)
rto_history[swap_b].pop(view_layer, None)
rto_history[swap_b+"_all"].pop(view_layer, None)
# clear swap buffer
swap_buffer["A"]["RTO"] = ""
swap_buffer["A"]["values"].clear()
swap_buffer["B"]["RTO"] = ""
swap_buffer["B"]["values"].clear()
def clear_copy(rto):
if copy_buffer["RTO"] == rto:
copy_buffer["RTO"] = ""
copy_buffer["values"].clear()
def clear_swap(rto):
if swap_buffer["A"]["RTO"] == rto:
swap_buffer["A"]["RTO"] = ""
swap_buffer["A"]["values"].clear()
swap_buffer["B"]["RTO"] = ""
swap_buffer["B"]["values"].clear()
def link_child_collections_to_parent(laycol, collection, parent_collection):
# store view layer RTOs for all children of the to be deleted collection
child_states = {}
def get_child_states(layer_collection):
child_states[layer_collection.name] = (layer_collection.exclude,
layer_collection.hide_viewport,
layer_collection.holdout,
layer_collection.indirect_only)
apply_to_children(laycol["ptr"], get_child_states)
# link any subcollections of the to be deleted collection to it's parent
for subcollection in collection.children:
if not subcollection.name in parent_collection.children:
parent_collection.children.link(subcollection)
# apply the stored view layer RTOs to the newly linked collections and their
# children
def restore_child_states(layer_collection):
state = child_states.get(layer_collection.name)
if state:
layer_collection.exclude = state[0]
layer_collection.hide_viewport = state[1]
layer_collection.holdout = state[2]
layer_collection.indirect_only = state[3]
apply_to_children(laycol["parent"]["ptr"], restore_child_states)
def remove_collection(laycol, collection, context):
# get selected row
cm = context.scene.collection_manager
selected_row_name = cm.cm_list_collection[cm.cm_list_index].name
# delete collection
bpy.data.collections.remove(collection)
# update references
expanded.discard(laycol["name"])
if expand_history["target"] == laycol["name"]:
expand_history["target"] = ""
if laycol["name"] in expand_history["history"]:
expand_history["history"].remove(laycol["name"])
if qcd_slots.contains(name=laycol["name"]):
qcd_slots.del_slot(name=laycol["name"])
if laycol["name"] in qcd_slots.overrides:
qcd_slots.overrides.remove(laycol["name"])
# reset history
for rto in rto_history.values():
rto.clear()
# update tree view
update_property_group(context)
# update selected row
laycol = layer_collections.get(selected_row_name, None)
if laycol:
cm.cm_list_index = laycol["row_index"]
elif len(cm.cm_list_collection) <= cm.cm_list_index:
cm.cm_list_index = len(cm.cm_list_collection) - 1
if cm.cm_list_index > -1:
name = cm.cm_list_collection[cm.cm_list_index].name
laycol = layer_collections[name]
while not laycol["visible"]:
laycol = laycol["parent"]
cm.cm_list_index = laycol["row_index"]
def select_collection_objects(is_master_collection, collection_name, replace, nested, selection_state=None):
if bpy.context.mode != 'OBJECT':
return
if is_master_collection:
target_collection = bpy.context.view_layer.layer_collection.collection
else:
laycol = layer_collections[collection_name]
target_collection = laycol["ptr"].collection
if replace:
bpy.ops.object.select_all(action='DESELECT')
if selection_state == None:
selection_state = get_move_selection().isdisjoint(target_collection.objects)
def select_objects(collection):
for obj in collection.objects:
try:
obj.select_set(selection_state)
except RuntimeError:
pass
select_objects(target_collection)
if nested:
apply_to_children(target_collection, select_objects)
def set_exclude_state(target_layer_collection, state):
# get current child exclusion state
child_exclusion = []
def get_child_exclusion(layer_collection):
child_exclusion.append([layer_collection, layer_collection.exclude])
apply_to_children(target_layer_collection, get_child_exclusion)
# set exclusion
target_layer_collection.exclude = state
# set correct state for all children
for laycol in child_exclusion:
laycol[0].exclude = laycol[1]
|
#!/usr/bin/env python
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
# Reval = re-eval. Re-evaluate saved detections.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
from model.test import apply_nms
from model.config import cfg
from datasets.factory import get_imdb
import pickle
import os, sys, argparse
import numpy as np
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Re-evaluate results')
parser.add_argument('output_dir', nargs=1, help='results directory',
type=str)
parser.add_argument('--imdb', dest='imdb_name',
help='dataset to re-evaluate',
default='stanford_test', type=str)
parser.add_argument('--matlab', dest='matlab_eval',
help='use matlab for evaluation',
action='store_true')
parser.add_argument('--comp', dest='comp_mode', help='competition mode',
action='store_true')
parser.add_argument('--nms', dest='apply_nms', help='apply nms',
action='store_true')
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
return args
def from_dets(imdb_name, output_dir, args):
imdb = get_imdb(imdb_name)
imdb.competition_mode(args.comp_mode)
imdb.config['matlab_eval'] = args.matlab_eval
with open(os.path.join(output_dir, 'detections.pkl'), 'rb') as f:
dets = pickle.load(f)
if args.apply_nms:
print('Applying NMS to all detections')
nms_dets = apply_nms(dets, cfg.TEST.NMS)
else:
nms_dets = dets
print('Evaluating detections')
imdb.evaluate_detections(nms_dets, output_dir)
if __name__ == '__main__':
args = parse_args()
output_dir = os.path.abspath(args.output_dir[0])
imdb_name = args.imdb_name
from_dets(imdb_name, output_dir, args)
|
from backend.target_validators.abinitio_gmx_validator import AbinitioGMXValidator
from backend.target_validators.abinitio_smirnoff_validator import AbinitioSMIRNOFFValidator
def new_validator(target_type, target_name=None):
target_validator_dict = {
'ABINITIO_GMX': AbinitioGMXValidator,
'ABINITIO_SMIRNOFF': AbinitioSMIRNOFFValidator,
}
return target_validator_dict[target_type](target_name) |
# Copyright 2019 Inspur 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.
# ==============================================================================
import torch
import torch.nn as nn
import time
from utility import *
def train_val(train_loader, val_loader,model,criterion, optimizer,args):
best_acc1 = validate(val_loader, model, criterion, args)
#best_acc1 = 70.258
for epoch in range(args.start_epoch, args.epochs):
if args.distributed:
train_sampler.set_epoch(epoch)
adjust_learning_rate(optimizer, epoch, args)
# train for one epoch
train(train_loader, model, criterion, optimizer, epoch,args)
# evaluate on validation set
acc1 = validate(val_loader, model, criterion, args)
# remember best acc@1 and save checkpoint
is_best = acc1 > best_acc1
best_acc1 = max(acc1, best_acc1)
if not args.multiprocessing_distributed or (args.multiprocessing_distributed
and args.rank % ngpus_per_node == 0):
save_finetune_checkpoint({
'epoch': epoch + 1,
'arch': args.arch,
'pruned_model': model,
'acc1': acc1,
'optimizer' : optimizer.state_dict(),
}, is_best,args.snapshotmodelname)
def train(train_loader, model, criterion, optimizer, epoch,args):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(
len(train_loader),
[batch_time, data_time, losses, top1, top5],
prefix="Epoch: [{}]".format(epoch))
# switch to train mode
model.train()
end = time.time()
for i, (images, target) in enumerate(train_loader):
# measure data loading time
data_time.update(time.time() - end)
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# compute gradient and do SGD step
optimizer.zero_grad()
loss.backward()
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
#break
def validate(val_loader, model, criterion,args):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(
len(val_loader),
[batch_time, losses, top1, top5],
prefix='Test: ')
# switch to evaluate mode
model.eval()
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if i % args.print_freq == 0:
progress.display(i)
# TODO: this should also be done with the ProgressMeter
print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'
.format(top1=top1, top5=top5))
return top1.avg |
from net.swordie.ms.constants import BossConstants
# Amon - (Easy/Chaos) Zakum's Altar
mapText = {
BossConstants.ZAKUM_JQ_MAP_2 : "I am impressed. Now, for the final stage.\r\nProceed, if you dare..",
BossConstants.ZAKUM_JQ_MAP_1 : "Intimidated? It's not too late to turn around."
}
optionOne = "#L0#Take me back to El Nath!!#l"
optionTwo = "#L1#I will continue.#l"
if sm.getFieldID() in mapText:
reply = sm.sendNext(mapText[sm.getFieldID()] + "\r\n" + optionOne + "\r\n" + optionTwo)
if reply == 0:
if sm.sendAskYesNo("Are you sure you want to leave?\r\nYou will lose any progress you have made."):
sm.warpNoReturn(211000000, 11) # El Nath Town
else:
sm.sendSayOkay("Brave choice, I commend you.")
elif reply == 1:
sm.sendSayOkay("I'll be here when you return.")
else:
if sm.sendAskYesNo("Are you ready to leave? Your whole party will be warped out and will not be allowed back in."):
sm.stopEvents()
sm.warpNoReturn(211042300, 1) |
import os
import pickle
import shutil
import subprocess
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
import h5py
from QDTK.Operator import trafo_to_momentum_rep
from mlxtk import dvr
from mlxtk.cwd import WorkingDir
from mlxtk.doit_analyses import output
from mlxtk.doit_compat import DoitAction
from mlxtk.hashing import inaccurate_hash
from mlxtk.inout.momentum_distribution import (
add_momentum_distribution_to_hdf5,
read_momentum_distribution_ascii,
)
from mlxtk.tasks.task import Task
class MCTDHBMomentumDistribution(Task):
def __init__(
self,
psi: str,
operator: str,
wfn: str,
grid: dvr.DVRSpecification,
output_file: Optional[str] = None,
):
self.psi = psi
self.name = psi.replace("/", "_")
self.operator = operator
if grid.is_fft():
self.momentum_operator = -1j * grid.get_expdvr().get_d1()
else:
self.momentum_operator = -1j * grid.get_d1()
self.wfn = wfn
if output_file is None:
self.output_file = str(Path(psi).parent / "momentum_distribution.h5")
else:
self.output_file = output_file
self.pickle_file = str(Path(self.output_file).with_suffix("")) + ".pickle"
def task_write_parameters(self) -> Dict[str, Any]:
@DoitAction
def action_write_parameters(targets: List[str]):
obj = [
self.psi,
self.operator,
inaccurate_hash(self.momentum_operator.real),
inaccurate_hash(self.momentum_operator.imag),
self.wfn,
self.output_file,
]
with open(targets[0], "wb") as fptr:
pickle.dump(obj, fptr, protocol=3)
return {
"name": f"momentum_distribution:{self.name}:write_parameters",
"actions": [action_write_parameters],
"targets": [self.pickle_file],
}
def task_compute(self) -> Dict[str, Any]:
@DoitAction
def action_compute(targets: List[str]):
path_psi = Path(self.psi).resolve()
path_operator = Path(self.operator).resolve()
path_wfn = Path(self.wfn).resolve()
path_output = Path(self.output_file).resolve()
path_temp = path_psi.parent / ("." + self.name)
if path_temp.exists():
shutil.rmtree(path_temp)
path_temp.mkdir(parents=True)
with WorkingDir(path_temp):
shutil.copy(path_psi, "psi")
shutil.copy(path_operator, "oper")
shutil.copy(path_wfn, "restart")
trafo_to_momentum_rep(
[
self.momentum_operator,
],
[
1,
],
)
cmd = [
"qdtk_analysis.x",
"-mtrafo",
"trafo_mom_rep",
"-opr",
"oper",
"-psi",
"psi",
"-rst",
"restart",
]
env = os.environ.copy()
env["OMP_NUM_THREADS"] = env.get("OMP_NUM_THREADS", "1")
result = subprocess.run(cmd, env=env)
if result.returncode != 0:
raise RuntimeError("Failed to run qdtk_analysis.x")
with h5py.File(path_output, "w") as fptr:
add_momentum_distribution_to_hdf5(
fptr, *read_momentum_distribution_ascii("mom_distr_1")
)
shutil.rmtree(path_temp)
return {
"name": f"momentum_distribution:{self.name}:compute",
"actions": [action_compute],
"targets": [self.output_file],
"file_dep": [self.pickle_file, self.psi, self.wfn, self.operator],
}
def get_tasks_run(self) -> List[Callable[[], Dict[str, Any]]]:
return [self.task_write_parameters, self.task_compute]
|
import json
from typing import Union
import numpy as np
# Modified from
# https://gist.github.com/jannismain/e96666ca4f059c3e5bc28abb711b5c92#file-compactjsonencoder-py
# to handle more classes
class CompactJSONEncoder(json.JSONEncoder):
"""A JSON Encoder that puts small containers on single lines."""
CONTAINER_TYPES = (list, tuple, dict)
"""Container datatypes include primitives or other containers."""
MAX_ITEMS = 6
"""Maximum number of items in container that might be put on single line."""
INDENTATION_CHAR = " "
def __init__(self, max_width = 80, precise = False, *args, **kwargs):
self.max_width = max_width
self.precise = precise
super().__init__(*args, **kwargs)
self.indentation_level = 0
def encode(self, o):
"""Encode JSON object *o* with respect to single line lists."""
if isinstance(o, (list, tuple)):
if self._put_on_single_line(o):
return "[" + ", ".join(self.encode(el) for el in o) + "]"
else:
self.indentation_level += 1
output = [self.indent_str + self.encode(el) for el in o]
self.indentation_level -= 1
return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
elif isinstance(o, dict):
if o:
if self._put_on_single_line(o):
return "{ " + ", ".join(f"{self.encode(k)}: {self.encode(el)}" for k, el in o.items()) + " }"
else:
self.indentation_level += 1
output = [self.indent_str + f"{json.dumps(k)}: {self.encode(v)}" for k, v in o.items()]
self.indentation_level -= 1
return "{\n" + ",\n".join(output) + "\n" + self.indent_str + "}"
else:
return "{}"
elif isinstance(o, float): # Use scientific notation for floats, where appropiate
if self.precise:
return format(o, ".12g")
else:
return format(o, "g")
elif isinstance(o, str): # escape newlines
o = o.replace("\n", "\\n")
return f'"{o}"'
elif isinstance(o, np.int32):
return json.dumps(int(o))
elif isinstance(o, np.bool_):
return json.dumps(bool(o))
elif isinstance(o, np.ndarray):
return self.encode(list(o))
else:
return json.dumps(o)
def _put_on_single_line(self, o):
return self._primitives_only(o) and len(o) <= self.MAX_ITEMS and len(str(o)) - 2 <= self.max_width
def _primitives_only(self, o: Union[list, tuple, dict]):
if isinstance(o, (list, tuple)):
return not any(isinstance(el, self.CONTAINER_TYPES) for el in o)
elif isinstance(o, dict):
return not any(isinstance(el, self.CONTAINER_TYPES) for el in o.values())
@property
def indent_str(self) -> str:
return self.INDENTATION_CHAR*(self.indentation_level*self.indent)
|
# This file is part of Moksha.
# Copyright (C) 2008-2010 Red Hat, 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.
"""
:mod:`moksha.api.widgets.amqp` - An AMQP driven live Moksha socket
==================================================================
.. moduleauthor:: Luke Macken <lmacken@redhat.com>
"""
import moksha
from tg import config
from tw.api import Widget, JSLink, js_callback, js_function
from paste.deploy.converters import asbool
from moksha.api.widgets.orbited import orbited_host, orbited_port, orbited_url
from moksha.api.widgets.orbited import orbited_js
from moksha.lib.helpers import defaultdict, listify
from moksha.widgets.moksha_js import moksha_js
from moksha.widgets.notify import moksha_notify
from moksha.widgets.json import jquery_json_js
from widgets import kamaloka_qpid_js
def amqp_subscribe(topic):
""" Return a javascript callback that subscribes to a given topic,
or a list of topics.
"""
sub = """
moksha.debug("Subscribing to the '%(topic)s' topic");
moksha_amqp_queue.subscribe({
exchange: 'amq.topic',
remote_queue: moksha_amqp_remote_queue,
binding_key: '%(topic)s',
callback: moksha_amqp_on_message,
});
"""
return ''.join([sub % {'topic': t} for t in listify(topic)])
def amqp_unsubscribe(topic):
""" Return a javascript callback that unsubscribes to a given topic,
or a list of topics.
"""
return ""
# TODO:
#sub = "stomp.unsubscribe('%s');"
#if isinstance(topic, list):
# sub = ''.join([sub % t for t in topic])
#else:
# sub = sub % topic
#return sub
class AMQPSocket(Widget):
callbacks = ['onconnectedframe', 'onmessageframe']
javascript = [jquery_json_js, moksha_js, kamaloka_qpid_js]
params = callbacks[:] + ['topics', 'notify', 'orbited_host',
'orbited_port', 'orbited_url', 'orbited_js', 'amqp_broker_host',
'amqp_broker_port', 'amqp_broker_user', 'amqp_broker_pass',
'send_hook', 'recieve_hook']
onconnectedframe = ''
onmessageframe = ''
send_hook = ''
recieve_hook = ''
engine_name = 'mako'
template = u"""
<script type="text/javascript">
if (typeof moksha_amqp_conn == 'undefined') {
moksha_callbacks = new Object();
moksha_amqp_remote_queue = null;
moksha_amqp_queue = null;
moksha_amqp_on_message = function(msg) {
var dest = msg.header.delivery_properties.routing_key;
var json = null;
try {
var json = $.parseJSON(msg.body);
} catch(err) {
moksha.error("Unable to decode JSON message body");
moksha.error(msg);
}
if (moksha_callbacks[dest]) {
for (var i=0; i < moksha_callbacks[dest].length; i++) {
moksha_callbacks[dest][i](json, msg);
}
}
}
}
## Register our topic callbacks
% for topic in topics:
var topic = "${topic}";
if (!moksha_callbacks[topic]) {
moksha_callbacks[topic] = [];
}
moksha_callbacks[topic].push(function(json, frame) {
${onmessageframe[topic]}
});
% endfor
## Create a new AMQP client
if (typeof moksha_amqp_conn == 'undefined') {
document.domain = document.domain;
$.getScript("${orbited_url}/static/Orbited.js", function() {
Orbited.settings.port = ${orbited_port};
Orbited.settings.hostname = '${orbited_host}';
Orbited.settings.streaming = true;
moksha_amqp_conn = new amqp.Connection({
% if send_hook:
send_hook: function(data, frame) { ${send_hook} },
% endif
% if recieve_hook:
recive_hook: function(data, frame) { ${recieve_hook} },
% endif
host: '${amqp_broker_host}',
port: ${amqp_broker_port},
username: '${amqp_broker_user}',
password: '${amqp_broker_pass}',
});
moksha_amqp_conn.start();
moksha_amqp_session = moksha_amqp_conn.create_session(
'moksha_socket_' + (new Date().getTime() + Math.random()));
moksha_amqp_remote_queue = 'moksha_socket_queue_' +
moksha_amqp_session.name;
moksha_amqp_session.Queue('declare', {
queue: moksha_amqp_remote_queue
});
moksha_amqp_queue = moksha_amqp_session.create_local_queue({
name: 'local_queue'
});
% if onconnectedframe:
${onconnectedframe}
moksha_amqp_queue.start();
% endif
});
} else {
## Utilize the existing Moksha AMQP socket connection
${onconnectedframe}
moksha_amqp_queue.start();
}
if (typeof moksha == 'undefined') {
moksha = {
/* Send an AMQP message to a given topic */
send_message: function(topic, body) {
moksha_amqp_session.Message('transfer', {
accept_mode: 1,
acquire_mode: 1,
destination: 'amq.topic',
_body: $.toJSON(body),
_header: {
delivery_properties: {
routing_key: topic
}
}
});
},
}
}
</script>
"""
hidden = True
def __init__(self, *args, **kw):
self.notify = asbool(config.get('moksha.socket.notify', False))
self.orbited_host = config.get('orbited_host', 'localhost')
self.orbited_port = config.get('orbited_port', 9000)
self.orbited_scheme = config.get('orbited_scheme', 'http')
self.orbited_url = '%s://%s:%s' % (self.orbited_scheme,
self.orbited_host, self.orbited_port)
self.orbited_js = JSLink(link=self.orbited_url + '/static/Orbited.js')
self.amqp_broker_host = config.get('amqp_broker_host', 'localhost')
self.amqp_broker_port = config.get('amqp_broker_port', 5672)
self.amqp_broker_user = config.get('amqp_broker_user', 'guest')
self.amqp_broker_pass = config.get('amqp_broker_pass', 'guest')
super(AMQPSocket, self).__init__(*args, **kw)
def update_params(self, d):
super(AMQPSocket, self).update_params(d)
d.topics = []
d.onmessageframe = defaultdict(str) # {topic: 'js callbacks'}
for callback in self.callbacks:
if len(moksha.livewidgets[callback]):
cbs = ''
if callback == 'onmessageframe':
for topic in moksha.livewidgets[callback]:
d.topics.append(topic)
for cb in moksha.livewidgets[callback][topic]:
d.onmessageframe[topic] += '%s;' % str(cb)
else:
for cb in moksha.livewidgets[callback]:
if isinstance(cb, (js_callback, js_function)):
cbs += '$(%s);' % str(cb)
else:
cbs += str(cb)
if cbs:
d[callback] = cbs
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'CachingType',
'DeallocationOption',
'JobPriority',
'StorageAccountType',
'VmPriority',
]
class CachingType(str, Enum):
"""
Caching type for the disks. Available values are none (default), readonly, readwrite. Caching type can be set only for VM sizes supporting premium storage.
"""
NONE = "none"
READONLY = "readonly"
READWRITE = "readwrite"
class DeallocationOption(str, Enum):
"""
An action to be performed when the cluster size is decreasing. The default value is requeue.
"""
REQUEUE = "requeue"
TERMINATE = "terminate"
WAITFORJOBCOMPLETION = "waitforjobcompletion"
class JobPriority(str, Enum):
"""
Scheduling priority associated with the job. Possible values: low, normal, high.
"""
LOW = "low"
NORMAL = "normal"
HIGH = "high"
class StorageAccountType(str, Enum):
"""
Type of storage account to be used on the disk. Possible values are: Standard_LRS or Premium_LRS. Premium storage account type can only be used with VM sizes supporting premium storage.
"""
STANDARD_LRS = "Standard_LRS"
PREMIUM_LRS = "Premium_LRS"
class VmPriority(str, Enum):
"""
VM priority. Allowed values are: dedicated (default) and lowpriority.
"""
DEDICATED = "dedicated"
LOWPRIORITY = "lowpriority"
|
# Copyright (c) 2021 Jonas Thorsell
import sys
import numpy as np
numbers = [int(x) for x in sys.stdin.readline().split(',')]
print(numbers)
board = []
for l in sys.stdin:
if len(l.strip()) != 0:
board.append([int(x) for x in l.split()])
board = np.array(board).reshape((-1,5,5))
mark = np.zeros(board.shape, dtype=np.uint)
w = None
for n in numbers:
mark[board == n] = 1
if np.any(mark.sum(axis=2) == 5):
w = (mark.sum(axis=2) == 5).nonzero()[0][0]
break
if np.any(mark.sum(axis=1) == 5):
w = (mark.sum(axis=1) == 5).nonzero()[0][0]
break
print(w)
print(board[w])
print(mark[w])
s = board[w][mark[w] == 0].sum()
print(f'{s} * {n} = {s*n}')
|
import json
from werkzeug.exceptions import InternalServerError
from werkzeug.wrappers import Response
class HttpResponse(Response):
def __init__(self, content=None, content_type='text/html;charset=utf8', status=200, headers=None, **kwargs):
super().__init__(content, content_type=content_type, status=status, headers=headers, **kwargs)
class JsonResponse(HttpResponse):
def __init__(self, obj, encoder=None):
content = json.dumps(obj, ensure_ascii=True, cls=encoder)
super().__init__(content, content_type='application/json;charset=utf8')
class HttpBadRequest(HttpResponse):
def __init__(self, content=None):
super().__init__(content, status=400)
class HttpUnauthorized(HttpResponse):
def __init__(self, content=None):
super().__init__(content, status=401)
class HttpNotFound(HttpResponse):
def __init__(self, content=None):
super().__init__(content, status=404)
class HttpServerError(InternalServerError, HttpResponse):
def __init__(self, content=None):
e = None
if isinstance(content, Exception):
e = content
content = None
super().__init__(content, None, e)
|
# GMIT IF Statements
x = int(input("Please enter an interger: "))
if x < 0:
x = 0
print('negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print ('Single')
else:
print ('More')
print("The final value of x is:", x)
|
#!/usr/bin/python
import pysam
import csv
import Bio.Seq
import regex
import sys, getopt
# http://www.tutorialspoint.com/python/python_command_line_arguments.htm
# Returns "Start" if You need to look for the primer at the "start" of the read, returns "End" if you need to look for the primer at the end of the read
# parameters are passed by reference by default
#FOR REFERENCE NOT USING ANYMORE
def where_to_look_for_primer(selectedread):
if selectedread.is_reverse:
if selectedread.is_read1:
currentPrimerList = end_pos
else:
currentPrimerList = end_neg
else:
if selectedread.is_read1:
currentPrimerList = start_neg
else:
currentPrimerList = start_pos
return currentPrimerList
#FOR REFERENCE NOT USING ANYMORE
def getmatch(selectedread, primerList, target_portion_read):
count_end = len(primerList)-1
count = 0
endreadmatchlength = None
returnlist = None
foundPrimerLength = None
while (count <= count_end):
# CHECKING IF THE READ IS REVERSED, IF IT IS REVERSED THEN ENDING SEQUENCE CONTAINS THE PRIMER
# IF THE READ IS NOT REVERSED THEN THE BEGINNED SEQUENCE CONTAINS THE PRIMER
currentPrimer = primerList[count]
if selectedread.is_reverse:
endPrimer = currentPrimer[::-1]
endtestprimer = "(" + endPrimer + ")" + "{e<=2}"
end_reverse_read = target_portion_read[::-1]
match = regex.match(endtestprimer, end_reverse_read)
else:
# searching the beginning, with allowable error of 2 or less
testprimer = "(" + currentPrimer + ")" + "{e<=2}"
match = regex.match(testprimer, target_portion_read)
# index_of_primer_start = read.query_sequence.find(currentPrimer,0,40)
# if index_of_primer != -1:
if match != None:
count = count_end + 1
endreadmatchlength = match.span()[1]
foundPrimerLength = len(currentPrimer)
returnlist = [endreadmatchlength, foundPrimerLength]
else:
if count != count_end:
count = count + 1
else:
# THIS MEANS THERE IS NO MATCHES AND THEREFORE UNSURE WHAT PRIMER USED AND SO CUTTING OFF THE LENGTH OF THE LARGEST PRIMER WHICH IS THIRTY
count = count + 1
return returnlist
def getmatchall(readforward, readreverse, PrimerDictList, usePosStrand, target_portion_read_forward, target_portion_read_reverse):
# forward and reverse fasta files should be the same length
currentChr=readforward.tid
currentPos=readforward.pos
count_end = len(PrimerDictList)-1
count = 0
endreadmatchlengthforward = None
endreadmatchlengthreverse = None
returnlist = None
foundPrimerLengthforward = None
foundPrimerLengthreverse = None
while (count <= count_end):
if PrimerDictList[count]["strand"] == '-' and usePosStrand:
count= count +1
continue
elif int(PrimerDictList[count]["chr"]) != currentChr:
count= count +1
continue
elif abs(int(PrimerDictList[count]["startPos"])-currentPos) > 400:
count= count + 1
continue
# CHECKING IF THE READ IS REVERSED, IF IT IS REVERSED THEN ENDING SEQUENCE CONTAINS THE PRIMER
# IF THE READ IS NOT REVERSED THEN THE BEGINNED SEQUENCE CONTAINS THE PRIMER
currentPrimerforward = PrimerDictList[count]["currentStartPrimer"]
currentPrimerreverse = PrimerDictList[count]["currentEndPrimer"]
# if selectedread.is_reverse:
endPrimerreverse = currentPrimerreverse[::-1]
testprimerreverse = "(" + endPrimerreverse + ")" + "{e<=2}"
end_reverse_read = target_portion_read_reverse[::-1]
matchreverse = regex.match(testprimerreverse, end_reverse_read)
# else:
# searching the beginning, with allowable error of 2 or less
testprimerforward = "(" + currentPrimerforward + ")" + "{e<=2}"
matchforward = regex.match(testprimerforward, target_portion_read_forward)
# index_of_primer_start = read.query_sequence.find(currentPrimer,0,40)
# if index_of_primer != -1:
if matchreverse != None and matchforward != None:
targetLength= PrimerDictList[count]["targetLength"]
startPos = PrimerDictList[count]["startPos"]
endPos = PrimerDictList[count]["endPos"]
count = count_end + 1
endreadmatchlengthforward = matchforward.span()[1]
endreadmatchlengthreverse = matchreverse.span()[1]
foundPrimerLengthforward = len(currentPrimerforward)
foundPrimerLengthreverse = len(currentPrimerreverse)
returnlist = [endreadmatchlengthforward, foundPrimerLengthforward, endreadmatchlengthreverse, foundPrimerLengthreverse,targetLength,startPos,endPos]
elif matchreverse != None:
#print "Reverse matched but forward did not"
#print "The read forward is below"
#print readforward
#print target_portion_read_forward
#print "The read reverse is below"
#print readreverse
#print target_portion_read_reverse
#print "The fasta file forward is below"
#print primerListforward.filename
#print "The fasta file reverse is below"
#print primerListreverse.filename
count = count + 1
elif matchforward != None:
#print "Forward matched but reverse did not"
#print "The read forward is below"
#print readforward
#print target_portion_read_forward
#print "The read reverse is below"
#print readreverse
#print target_portion_read_reverse
#print "The fasta file forward is below"
#print primerListforward.filename
#print "The fasta file reverse is below"
#print primerListreverse.filename
count = count + 1
else:
count = count + 1
return returnlist
def change_cigar_either(booleanIsReverse,originalcigar, endreadmatchlength, numberlist, numberlistint, letterlist, expectedEndReadMatchLength, readLength, read,targetLength,startManifestPos,endManifestPos):
#returns list of two indexes one says if there was an error making the cigar and other says if there is overlapping of reads
overlappingReads=False
# because changing read.position
global forwardread
global reverseread
oldAlignmentStart = 0
# print sum(numberlistint)
###DEBUGGING
#if forwardread.qname != "NS500796:7:H77VTAFXX:1:11101:7184:4318":
#return True
# print 'Found M01382:52:000000000-AAECF:1:2102:21256:8889'
# print 'The endreadmatchlength is ' + str(endreadmatchlength)
# IF IT IS NOT LESS THEN OR EQUAL TO endreadmatchlength
indexchanging = 0
deletionPresent = False
# numberToSubtract is dependent on whether or not there is a deletion present in the primer area, need to adjust position by the number of deletions present
# (shouldn't be more than 2 since only 2 deletions are allowed, if more then read should be thrown out)
# numberToSubtract and InsertionCount, only works if in the primer
DeletionCount = 0
DeletionCountExceptEnd=0
InsertionCount = 0
insertionAtEnd = 0
booleanDeletionAtEnd = False
booleanInsertionAtEnd = False
runningTotal = 0
DeletionPos = 0
if booleanIsReverse:
numberlist = numberlist[::-1]
numberlistint = numberlistint[::-1]
letterlist = letterlist[::-1]
oldAlignmentStartR = reverseread.qstart
oldPositionStart = reverseread.pos
#need to do this for reverse
#WILL DO POSITION CHECK LATER FOR REVERSE
#if endManifestPos-oldPositionStart-reverseread.qlen > 0:
# print read.qname
# print "The position is " + str(oldPositionStart)
# print "The q length is " + str(reverseread.qlen)
#when there is a deletion (ie there is less of the probe because the position start is different)
#the oldPositionStart is actually smaller and hence it will be > 0 since normal is zero
#print "The reverse read position is " + str(reverseread.pos)
#print "The reverse read position is " + str(reverseread.pos+reverseread.qlen)
#print "The reverse read qlen is " + str(reverseread.qlen)
#print "The reverse read qstart is " + str(reverseread.qstart)
#FOR REV
# DeletionCount= DeletionCount + abs(endManifestPos-oldPositionStart-reverseread.qlen)
# DeletionPos=DeletionCount
#elif endManifestPos-oldPositionStart-reverseread.qlen < 0:
# InsertionCount= InsertionCount + (endManifestPos-oldPositionStart-reverseread.qlen)
#else:
# return True
#print str(endManifestPos-forwardread.pos)
else:
oldAlignmentStart = forwardread.qstart
oldPositionStart = forwardread.pos
softclipbeginning = 0
if letterlist[0]=='S':
softclipbeginning = int(numberlist[0])
forwardreadOffset = startManifestPos - forwardread.pos + softclipbeginning
if forwardreadOffset != 1 and (forwardreadOffset > 4 and forwardreadOffset < -2):
#ie maps position "early" because skips first read on probe (like a deletion) or maps late because it added on a read
#if too match then too much error in the probe
return [True,overlappingReads]
if forwardreadOffset > 1:
#print "Hello insertion!!!!!!!!!!!!!!!!!!!"
#print str(startManifestPos - forwardread.pos)
InsertionCount= InsertionCount + (startManifestPos - forwardread.pos - 1)
#the expectedpostionforward - forwardread.pos should equal 1 expected, because forwardread.pos is base 0? if difference < 1 deletion, if > 1 insertion
if forwardreadOffset < 1:
#ie maps position "early" because skips first read on probe (like a deletion)
#print "Hello"
#print str(startManifestPos - forwardread.pos)
#need to add on DeletionPos makes it work (if not get cigar error where 25S125M when should be 25S126M)
#DeletionPos will not be used to modify the position
DeletionCount= DeletionCount + abs(startManifestPos - forwardread.pos - 1)
DeletionPos=DeletionCount
#runningTotal=runningTotal+DeletionCount
# #THERE MAY BE A SITUATION IF THERE IS TANDEM DUPLICATION shortly after a probe and the duplicated entry gets a match even though THOUGH THERE ARE TOO MANY DELETIONS, NEED TO GET RID OF THIS SCENARIO BECAUSE ONLY EXPECTING 2 deletions at most
if not sum(numberlistint) <= expectedEndReadMatchLength:
for index in range(len(numberlist)):
#
if expectedEndReadMatchLength <= numberlistint[index] + runningTotal:
indexchanging = index
runningTotal = runningTotal + numberlistint[index]
if letterlist[index] == 'D' or letterlist[index] == 'H' or letterlist[index] == 'N' or letterlist[index] == 'P':
deletionPresent = True
booleanDeletionAtEnd = True
DeletionCountExceptEnd = DeletionCount
DeletionCount = DeletionCount + (runningTotal - expectedEndReadMatchLength) + 1
runningtotalBeforeDeletion = runningTotal - numberlistint[index]
if letterlist[index] == 'I':
insertionAtEnd = expectedEndReadMatchLength - (runningTotal - numberlistint[index])
if DeletionCount + InsertionCount + insertionAtEnd >= 3:
return [True,overlappingReads]
break
else:
if letterlist[index] == 'D' or letterlist[index] == 'H' or letterlist[index] == 'N' or letterlist[index] == 'P':
deletionPresent = True
DeletionCount = DeletionCount + numberlistint[index]
elif letterlist[index] == 'I':
InsertionCount = InsertionCount + numberlistint[index]
runningTotal = runningTotal + numberlistint[index]
else:
return [True,overlappingReads]
#The position modification is not valid if there is a deletion in the primer when a reverse read, hence need to check if a deletion is present in the reverse
#read
if booleanIsReverse:
#get total Deletions and total insertions
totalDeletions=0
totalInsertions=0
totalSoftClip=0
for index in range(len(numberlist)):
if letterlist[index] == 'D':
totalDeletions = totalDeletions + numberlistint[index]
elif letterlist[index] == 'I':
totalInsertions = totalInsertions + numberlistint[index]
elif letterlist[index] == 'S':
totalSoftClip == totalSoftClip + numberlistint[index]
reversereadOffset= endManifestPos-oldPositionStart-reverseread.qlen - totalDeletions + totalInsertions - totalSoftClip
if abs(reversereadOffset) > 2:
#if too match then too much error in the probe
return [True,overlappingReads]
if reversereadOffset > 0:
DeletionCount= DeletionCount + abs(reversereadOffset)
DeletionPos=abs(reversereadOffset)
#if reversereadOffset > 2:
# print "Oh no!"
# print read.qname
# print read.cigarstring
# print "below is the results"
# print str(reversereadOffset)
# print "totalSoftClip is " + str(totalSoftClip)
# print "the chr location is " + str(read.tid)
# print "the location is " + str(endManifestPos)
elif reversereadOffset < 0:
#print "We are in endManifestPos-oldPositionStart-reverseread.qlen - totalDeletions + totalInsertions"
#print read.qname
InsertionCount= InsertionCount + abs(endManifestPos-oldPositionStart-reverseread.qlen - totalDeletions + totalInsertions -totalSoftClip)
# check if deletion is present in the primer (if so need to adjust cigar so the cigar length is what is expected, need to substract from not the primer)
# ie if 100M1D21M, need it to be 94M27S not 95M27S
# if expected endreadmatchlength do not match that means there was either a 1 or 2 bp deletion or 1 or 2 bp insertion
# need to subtract or add on to the last
# IF INSERTION NEED TO MOVE POSITION BACK INSTEAD OF FORWARD
#TO MAKE THINGS EASIER
#numberToSubtractTotal = DeletionCount + InsertionCount + insertionAtEnd
TotalInsertionsPresent = InsertionCount + insertionAtEnd
# #PLEASENOTE: INSERTIONATEND DOES NOT CHANGE POSITION
newcigar = ""
newcigarnumberlist = []
newcigarletterlist = []
needtomodifynumber = False
numberToSubtractTotal = 0
for index in range(len(numberlist)):
if index == 0:
# newcigar=newcigar+str(expectedEndReadMatchLength)+'S'
# newcigarnumberlist.append(str(expectedEndReadMatchLength-numberToSubtract))
if booleanDeletionAtEnd == True:
newcigarnumberlist.append(str(runningtotalBeforeDeletion + InsertionCount -DeletionCountExceptEnd))
else:
#newcigarnumberlist.append(str(expectedEndReadMatchLength + InsertionCount -DeletionCount))
newcigarnumberlist.append(str(expectedEndReadMatchLength + InsertionCount -DeletionCount))
newcigarletterlist.append('S')
if indexchanging == 0 and not (letterlist[indexchanging] == 'S' or letterlist[indexchanging] == 'H'):
# newcigar=newcigar+str(runningTotal-expectedEndReadMatchLength)+letterlist[indexchanging]
##TODO MAKE SUBFUNCTION AS CALLED TWICE
newnumber= runningTotal - (expectedEndReadMatchLength + InsertionCount) + DeletionPos
if newnumber > 0:
newcigarnumberlist.append(str(newnumber))
newcigarletterlist.append(letterlist[indexchanging])
elif newnumber == 0:
continue
else:
numberToSubtractTotal = abs(newnumber)
needtomodifynumber= True
###END TODO
# else just keep the position the same
else:
if indexchanging == 0:
# IF THE CURRENT S or H is larger then the primer then get rid of the primer length added to the newcigarnumberlist
del newcigarnumberlist[len(newcigarnumberlist) - 1]
newcigarnumberlist.append(str(numberlistint[0]))
elif index < indexchanging:
continue
elif index == indexchanging:
if letterlist[indexchanging] == 'D' or letterlist[indexchanging] == 'H':
#print 'I am trying to modify a read with a deletion at the end of the primer'
#print 'The read is ' + str(read.qname)
needtomodifynumber = True
booleanDeletionAtEnd = True
newnumber= runningTotal - (expectedEndReadMatchLength + InsertionCount) + DeletionPos
#print 'The newnumber is ' + str(newnumber)
if newnumber > 0:
newcigarnumberlist.append(str(newnumber))
newcigarletterlist.append(letterlist[indexchanging])
else:
numberToSubtractTotal = abs(newnumber)
# DO NOTHING, THE DELETION LETTER WILL BE REMOVES (ONLY TWO SCENARIOS REMEMBER CAN'T HAVE MORE THAN 2 INS OR DEL
elif letterlist[indexchanging] == 'I':
#NOTE: WE ARE NOT MODIFYING IF THERE IS AN INSERTION AT THE END
needtomodifynumber = True
booleanInsertionAtEnd = True
numberToSubtractTotal = TotalInsertionsPresent
newcigarnumberlist.append(numberlist[indexchanging])
newcigarletterlist.append(letterlist[indexchanging])
else:
##TODO MAKE SUBFUNCTION AS CALLED TWICE
newnumber= runningTotal - (expectedEndReadMatchLength + InsertionCount) + DeletionPos
if newnumber > 0:
newcigarnumberlist.append(str(newnumber))
newcigarletterlist.append(letterlist[indexchanging])
#numberToSubtractTotal = abs(DeletionCount)
#needtomodifynumber= True
elif newnumber == 0:
continue
else:
numberToSubtractTotal = abs(newnumber)
needtomodifynumber= True
##END TODO
else:
if needtomodifynumber and letterlist[index] != 'D' and letterlist[index] !='I':
newnumber = numberlistint[index] - numberToSubtractTotal
if newnumber > 0:
newcigarnumberlist.append(str(newnumber))
newcigarletterlist.append(letterlist[index])
needtomodifynumber = False
else:
numberToSubtractTotal = numberToSubtractTotal - numberlistint[index] + 1
newcigarnumberlist.append(str(1))
newcigarletterlist.append(letterlist[index])
elif needtomodifynumber and letterlist[index] == 'D' and InsertionCount >0:
#THIS IS A SPECIFIC SITUATION AND NEED TO ADD TO DELETIONCOUNT IN ORDER TO PROPERLY POSITION THE READ IF IT IS FORWARD
DeletionCount = DeletionCount + 1
newnumber = numberlistint[index] - numberToSubtractTotal
if newnumber > 0:
newcigarnumberlist.append(str(newnumber))
newcigarletterlist.append(letterlist[index])
needtomodifynumber = False
elif newnumber == 0:
#KNOW THAT THIS IS A CERTAIN SITUATION IN WHICH WILL WANT TO REDUCE SIZE OF CLIP
newcigarnumberlist[len(newcigarletterlist)-1]=str(int(newcigarnumberlist[len(newcigarletterlist)-1])-1)
needtomodifynumber = False
else:
numberToSubtractTotal = numberToSubtractTotal - numberlistint[index] + 1
newcigarnumberlist.append(str(1))
newcigarletterlist.append(letterlist[index])
else:
newcigarnumberlist.append(numberlist[index])
newcigarletterlist.append(letterlist[index])
if newcigarletterlist[0] != 'S':
print "there was an error and a cigar was not clipped"
return [True,overlappingReads]
dontClipEnd=False
numbertoClip=0
indexchangingAll=len(newcigarnumberlist)-1
deletionEnd=0
insertionEnd=0
softEnd=0
matchEnd=0
foundIndexChanged=False
#print "Started new end read clip"
if sum(numberlistint) > expectedEndReadMatchLength + targetLength:
numbertoClip = 0-targetLength
#starting at one because not wanting to count the probe that was soft clipped
for index in range(1,len(newcigarnumberlist)):
if numbertoClip < 0:
if (newcigarletterlist[index] != 'D') and (newcigarletterlist[index] != 'I') and (newcigarletterlist[index] != 'S') and (newcigarletterlist[index] != 'H') and (newcigarletterlist[index] != 'N') and (newcigarletterlist[index] != 'P'):
numbertoClip=numbertoClip+int(newcigarnumberlist[index])
#because less of target will be covered if there is an insertion, DO NOT DO ANYTHING IF INSERTION (THE NUMBER OF MATCHES IN CIGAR ALREADY LESS)
#elif newcigarletterlist[index] == 'I':
#numbertoClip=numbertoClip
elif newcigarletterlist[index] == 'D':
#because more of target will be covered if there is an deletion
#DONT NEED TO MULTIPLY BY TWO BECAUSE THE NUMBER COVERED WILL BE LESS
#numbertoClip=numbertoClip+(int(2*newcigarnumberlist[index]))
numbertoClip=numbertoClip+(int(newcigarnumberlist[index]))
elif newcigarletterlist[index] == 'S':
#soft clips are only at the end and since for loop started at 1 this means at the end, if it hasn't
#made the target yet will set numbertoClip at zero so in the next if statement it will be set as softEnd
numbertoClip=0
#has to be equal too since 0 represents it exactly reached the target point, using matchEnd, softEnd and insertionEnd after that
if numbertoClip >= 0:
if foundIndexChanged==False:
foundIndexChanged=True
indexchangingAll=index
if newcigarletterlist[index] == 'I':
#numbertoClip=numbertoClip+int(newcigarnumberlist[index])
insertionEnd=insertionEnd+int(newcigarnumberlist[index])
elif newcigarletterlist[index] == 'M' and index > indexchangingAll:
matchEnd= matchEnd + int(newcigarnumberlist[index])
elif newcigarletterlist[index] == 'S':
softEnd= matchEnd + int(newcigarnumberlist[index])
elif newcigarletterlist[index] == 'D':
if index==indexchangingAll:
#can't have indexchanging on a deletion, reseting
#indexchangingAll=len(newcigarnumberlist)-1
numbertoClip=0
deletionEnd = deletionEnd + int(newcigarnumberlist[index])
#numbertoClip=runningTotal-targetLength
if numbertoClip > 0 and dontClipEnd==False:
newcigar2 = ""
newcigarnumberlist2 = []
newcigarletterlist2 = []
for index in range(len(newcigarnumberlist)):
if index ==indexchangingAll:
currentNumber=int(newcigarnumberlist[index])
currentLetter=newcigarletterlist[index]
if currentLetter =='M':
if currentNumber-numbertoClip > 0:
newcigarletterlist2.append('M')
newcigarnumberlist2.append(str(currentNumber-numbertoClip))
newcigarletterlist2.append('S')
newcigarnumberlist2.append(str(numbertoClip+insertionEnd+matchEnd+softEnd))
else:
newcigarletterlist2.append('S')
newcigarnumberlist2.append(str(numbertoClip+insertionEnd+matchEnd+softEnd))
else:
newcigarletterlist2.append('S')
newcigarnumberlist2.append(str(numbertoClip+insertionEnd+matchEnd+softEnd))
elif index < indexchangingAll:
newcigarletterlist2.append(newcigarletterlist[index])
newcigarnumberlist2.append(str(newcigarnumberlist[index]))
else:
dontClipEnd=True
else:
dontClipEnd=True
if dontClipEnd != True:
overlappingReads=True
newcigarletterlist=newcigarletterlist2
newcigarnumberlist=newcigarnumberlist2
if booleanIsReverse:
newcigarnumberlist = newcigarnumberlist[::-1]
newcigarletterlist = newcigarletterlist[::-1]
for index in range(len(newcigarletterlist)):
###TODO GET RID OF IF FOUND NOT TO HAVE ERRORS
##if int(newcigarnumberlist[index]) <= 0:
### continue
newcigar = newcigar + newcigarnumberlist[index] + newcigarletterlist[index]
# Sum of lengths of the M/I/S/=/X operations shall equal the length of SEQ
if booleanIsReverse:
reverseread.cigarstring = newcigar
if dontClipEnd != True:
#####reverseread.pos = reverseread.pos + reverseread.qstart - oldAlignmentStart + DeletionCount - InsertionCount - insertionEnd + deletionEnd
reverseread.pos = reverseread.pos + reverseread.qstart - oldAlignmentStartR - insertionEnd + deletionEnd
###
#if abs(startManifestPos-oldAlignmentStartR) < abs(endManifestPos-oldAlignmentStartR):
# reverseread.pos = startManifestPos + expectedEndReadMatchLength
#else:
# reverseread.qstart = EndManifestPos + expectedEndReadMatchLength
if not booleanIsReverse:
forwardread.cigarstring = newcigar
# need to adjust position if a deletion was present in the primer area so adding + numbertosubtract
if startManifestPos - oldPositionStart != 1:
forwardread.pos = forwardread.pos + forwardread.qstart - oldAlignmentStart + DeletionCount - InsertionCount + (startManifestPos - oldPositionStart - 1)
else:
forwardread.pos = forwardread.pos + forwardread.qstart - oldAlignmentStart + DeletionCount - InsertionCount
###forwardread.pos = readExpectedPostion + DeletionCount - InsertionCount
#if abs(startManifestPos-oldAlignmentStart) < abs(endManifestPos-oldAlignmentStart):
# forwardread.qstart = startManifestPos + expectedEndReadMatchLength
#else:
# forwardread.qstart = EndManifestPos + expectedEndReadMatchLength
RealOnly = regex.compile(ur'[MIDN]')
RealLetterlist = regex.findall(RealOnly, newcigar)
# http://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int
numberlistint = map(int, newcigarnumberlist)
calCigarLength = 0
zeroLengthElement=False
for eachindex in range(0, len(newcigarletterlist)):
if (newcigarletterlist[eachindex] != 'D') and (newcigarletterlist[eachindex] != 'H') and (newcigarletterlist[eachindex] != 'N') and (newcigarletterlist[eachindex] != 'P'):
calCigarLength = abs(numberlistint[eachindex]) + calCigarLength
for eachindex in range(0, len(numberlistint)):
if numberlistint[eachindex]== 0:
zeroLengthElement=True
# if letterlist has D,H,N,P; then don't write it down
if (calCigarLength != readLength) or zeroLengthElement:
print "Cigar length did not match or Zero Length Element"
print read.qname
print read.query_length
if booleanIsReverse:
print "the deletion count is " + str(DeletionCount)
print "the insertion count is " + str(InsertionCount)
print "the endManifestPos is " + str(endManifestPos)
print "the oldPositionStart is " + str(oldPositionStart)
print "the totalDeletions is " + str(totalDeletions)
print "the totalInsertions is " + str(totalInsertions)
print "the reverseread.qlen is " + str(readLength)
print "the endManifestPos-oldPositionStart-reverseread.qlen - totalDeletions + totalInsertions is " + str(endManifestPos-oldPositionStart-readLength - totalDeletions + totalInsertions)
print "is read revserse " + str(booleanIsReverse)
print "the length of letterlistR is: " + str(len(letterlist))
print "the length of the matched endreadmatchlength is:" + str(endreadmatchlength)
print "the length of the expected matched primer is:" + str(expectedEndReadMatchLength)
print "the new calculated Cigar Length is: " + str(calCigarLength)
print "the cigar length should be " + str(read.query_length)
print "the original cigar is: " + str(originalcigar)
print "the new cigarstring is: " + str(newcigar)
print "the target length is: " + str(targetLength)
print "return True at if (calCigarLength != read.query_length)"
return [True,overlappingReads]
if (not RealLetterlist):
print "continue at if (not RealLetterlistF) or (not RealLetterlistR)"
return [True,overlappingReads]
return [False,overlappingReads]
def main(argv):
global inputfile
global outputfile
global start_pos
global end_pos
global end_neg
global start_neg
global library_type
global reverseread
global forwardread
global current
inputfile = ''
outputfile = ''
library_type = ''
try:
opts, args = getopt.getopt(argv, "hi:o:t:m:", ["ifile=", "ofile=", "librarytype=", "manifest="])
except getopt.GetoptError:
print 'clipPrimers.py -i <inputfile> -o <outputfile> -t <library_type> -m <Illumina manifest file>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'clipPrimers.py -i <inputfile> -o <outputfile> -t <library_type> -m <Illumina manifest file>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
elif opt in ("-t", "--librarytype"):
library_type = arg
elif opt in ("-m", "--manifest"):
manifest = arg
print 'The manifest file is "', manifest
print 'Input file is "', inputfile
print 'Output file "', outputfile
#start pos is postive strand ULSO sequences
start_pos=[]
#start neg is negative strand DLSO sequences, note these are reverse complement of sequences in manifest
start_neg=[]
#end pos is positive strand DLSO sequences
end_pos=[]
#end neg is negative strand ULSO sequences, note these are reverse complement of sequences in manifest
end_neg=[]
header=[]
#list where [strand,chr,startPosition,endPosition,currentStartPrimer,currentEndPrimer]
#customPrimerList=[]
rowcount=0
file_read = csv.reader(open(manifest, 'r'), delimiter='\t');
# for row in file_read:
# if rowcount==1:
# #this is a header row
# header=row
# rowcount=rowcount+1
# continue
# elif row[0]=='[Targets]':
# break
# elif rowcount==0:
# rowcount=rowcount+1
# continue
# currentDLSO=row[header.index('DLSO Sequence')]
# currentULSO=row[header.index('ULSO Sequence')]
# startPosition=row[header.index('Start Position')]
# endPosition=row[header.index('End Position')]
# strand=row[header.index('Strand')]
# chr=row[header.index('Chromosome')][3:]
# currentStartPrimer=''
# currentEndPrimer=''
# if strand=='-':
# currentStartPrimer=Bio.Seq.reverse_complement(currentDLSO)
# currentEndPrimer=Bio.Seq.reverse_complement(currentULSO)
# start_neg.append(currentStartPrimer)
# end_neg.append(currentEndPrimer)
# else:
# currentStartPrimer=currentULSO
# currentEndPrimer=currentDLSO
# start_pos.append(currentStartPrimer)
# end_pos.append(currentEndPrimer)
# currentlist=[strand,chr,startPosition,endPosition,currentStartPrimer,currentEndPrimer]
# customPrimerList.append((currentlist[:]))
# rowcount=rowcount+1
header=[]
headernext=False
inTargetsPortion=False
inProbesPortion=False
PrimerDictList=[]
for row in file_read:
if row[0] == '[Probes]':
headernext = True
inProbesPortion = True
inTargetsPortion = False
continue
elif row[0] == '[Targets]':
headernext = True
inTargetsPortion = True
inProbesPortion = False
inTargetInteger = 0
continue
elif row[0] == '[Intervals]':
break
elif headernext == True:
header = row
headernext = False
continue
elif inProbesPortion == True:
currentULSO = str(row[header.index('ULSO Sequence')])
currentDLSO = str(row[header.index('DLSO Sequence')])
currentDict = {'ULSO Sequence':currentULSO, 'DLSO Sequence':currentDLSO}
currentDLSO = row[header.index('DLSO Sequence')]
currentULSO = row[header.index('ULSO Sequence')]
# startPosition=row[header.index('Start Position')]
# endPosition=row[header.index('End Position')]
strand = row[header.index('Strand')]
chr = row[header.index('Chromosome')][3:]
currentStartPrimer = ''
currentEndPrimer = ''
if strand == '-':
currentStartPrimer = Bio.Seq.reverse_complement(currentDLSO)
currentEndPrimer = Bio.Seq.reverse_complement(currentULSO)
else:
currentStartPrimer = currentULSO
currentEndPrimer = currentDLSO
currentDict = {"strand":strand, "chr":chr, "startPos":0, "endPos":0, "currentStartPrimer":currentStartPrimer, "currentEndPrimer":currentEndPrimer,
"startPrimerLength":0, "endPrimerLength":0, "targetLength":0}
PrimerDictList.append(currentDict)
continue
elif inTargetsPortion == True:
chr = str(row[header.index('Chromosome')])
startPos = int(str(row[header.index('Start Position')]))
endPos = int(str(row[header.index('End Position')]))
PrimerDictList[inTargetInteger]["startPos"] = startPos
PrimerDictList[inTargetInteger]["endPos"] = endPos
startPrimerLength = len(PrimerDictList[inTargetInteger]["currentStartPrimer"])
endPrimerLength = len(PrimerDictList[inTargetInteger]["currentEndPrimer"])
targetLength = endPos - startPos - len(PrimerDictList[inTargetInteger]["currentStartPrimer"]) - len(PrimerDictList[inTargetInteger]["currentEndPrimer"])
#adding plus 3 to match the clipping for the start probe (because actually clip before end of probe at the start, which is what illumina does)
PrimerDictList[inTargetInteger]["targetLength"] = targetLength+3
PrimerDictList[inTargetInteger]["startPrimerLength"] = startPrimerLength
PrimerDictList[inTargetInteger]["endPrimerLength"] = endPrimerLength
# print PrimerDictList[inTargetInteger]["targetLength"]
inTargetInteger = inTargetInteger + 1
else:
continue
samfile = pysam.AlignmentFile(inputfile)
# template copies the header from the other alignment file
newreads = pysam.AlignmentFile(outputfile, "wb", template=samfile)
readnum = 0
read1 = None
read2 = None
for read in samfile: # TMS KEY CHANGE (GET RID OF FETCH)
# have to process reads1 and reads2
# the read.rnext==read.rname is another double check they are on the same chromosome
#hence I am filtering out secondary alignments
if read.is_read1 and read.rnext == read.rname and not read.is_secondary: # Store read1 of the pair and iterate the for loop.
read1 = read
continue
elif read.is_read2 and read.rnext == read.rname and not read.is_secondary: # Store read2. Should now have read1 and read2 from a properly-paired read. Do a bit of QC-ing of the read-pair.
read2 = read
if read1 is None:
read1 = None
read1 = None
print "WARNING READ1 EMPTY WHILE READ2 WAS NOT, IF SEE ERROR MULTIPLE TIMES CHECK IF SORTED BY QUERYNAME"
#print "continue at elif read.is_read2 and read.rnext == read.rname:"
continue
elif read2.qname != read1.qname:
read1 = None
read1 = None
#print "continue at elif read2.qname != read1.qname"
continue
elif read1.is_reverse and read2.is_reverse:
#one of the reads has to be forward, filtering out
read1 = None
read2 = None
continue
elif not read1.is_reverse and not read2.is_reverse:
#one of the reads has to be reverse, filtering out
read1 = None
read2 = None
continue
if read1 is None or read2 is None:
#print "continue at if read1 is None or read2 is None"
continue
# if read1.tid != read2.tid then that means the mate is mapped to a different chromosome, so getting rid of
#print read1.cigarstring
if (read1.query_length <= 35) or (read2.query_length <= 35) or (not isinstance(read.cigarstring, str)) or (read1.tid != read2.tid):
# newreads.write(read)
#print "continue at if (read1.query_length <= 35) or (read2.query_length <= 35) or (not isinstance(read.cigarstring, str)) or (read1.tid != read2.tid):"
continue
# ASSUMING READ1 AND READ2 are opposite in read.is_reverse
p = regex.compile(ur'\d+')
p2 = regex.compile(ur'[MIDNSHP=X]')
# would rather know which read is reverse and which is forward, will find out later if one is read1 or read2
#if read1reverse
usePosStrand=True
if read1.is_reverse:
reverseread = read1
forwardread = read2
currentPrimerListF=start_pos
currentPrimerListR=end_pos
usePosStrand=True
else:
reverseread = read2
forwardread = read1
currentPrimerListF=start_neg
currentPrimerListR=end_neg
usePosStrand=False
#if forwardread.cigarstring == '121M' and reverseread.cigarstring == '121M':
# print "The read is 121M on both sides, this read should be written."
# print "The read name is : " + read1.qname
numberlistR=[]
letterlistR=[]
numberlistF=[]
letterlistF=[]
try:
numberlistR = regex.findall(p, reverseread.cigarstring)
letterlistR = regex.findall(p2, reverseread.cigarstring)
numberlistF = regex.findall(p, forwardread.cigarstring)
letterlistF = regex.findall(p2, forwardread.cigarstring)
except:
read1 = None
read2 = None
print "ERROR: in making numberlist and letterlist"
continue
# http://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int
numberlistintR = map(int, numberlistR)
numberlistintF = map(int, numberlistF)
if letterlistR[len(letterlistR) - 1] == 'H':
if numberlistintR[len(numberlistintR) - 1] > 2:
# then it clipped the end and hence it won't match a primer, filtering out
# newreads.write(read)
#print "continue at if numberlistintR[len(numberlistintR) - 1] > 2:"
#print "the reverseread is :" + str(reverseread.cigarstring)
continue
if letterlistF[0] == 'H':
if numberlistintF[0] > 2:
# then it clipped the start and hence it won't match a primer, filtering out
#print "continue at if numberlistintF[0] > 2:"
#print "the forwardread is :" + str(forwardread.cigarstring)
continue
# if the primer is already soft-clipped, likely probe mismatch, should get rid of, poor quality
if letterlistR[len(letterlistR) - 1] == 'S':
if numberlistintR[len(numberlistintR) - 1] > 10:
#print "continue at if numberlistintR[len(numberlistintR) - 1] > 10:"
#print "the reverseread is :" + str(reverseread.cigarstring)
continue
if letterlistF[0] == 'S':
if numberlistintF[0] > 10:
#print "continue at if numberlistintF[0] > 10:"
#print "the forwardread is :" + str(forwardread.cigarstring)
continue
#throw out if heavily soft clipped at end
if letterlistR[0] == 'S':
if numberlistintR[0] > 50:
#print "continue at if numberlistintR[0] > 50:"
#print "the reverseread is :" + str(reverseread.cigarstring)
continue
if letterlistF[len(numberlistintF) - 1] == 'S':
if numberlistintF[len(numberlistintF) - 1] > 50:
#print "continue at if numberlistintF[0] > 10:"
#print "the forwardread is :" + str(forwardread.cigarstring)
continue
# get read to check on
# get the last 35 reads
target_portion_read_R = reverseread.query_sequence[reverseread.query_length - 35:]
# need read start
target_portion_read_F = forwardread.query_sequence[0:35]
# currentSequence = read.query_sequence
# returns a match object
# print read.query_sequence
# print read.query_alignment_end
# print read.next_reference_start
# print read.is_reverse
#currentPrimerListR = ''
#currentPrimerListR = where_to_look_for_primer(reverseread)
#currentPrimerListF = ''
#currentPrimerListF = where_to_look_for_primer(forwardread)
#[currentPrimerListF,currentPrimerListR] = where_to_look_for_primer_both(forwardread)
# First only matched forward then reverse, to increase sensitivity the forward and reverse match have to have same index (ie can't match primer of PTEN forward and TP53 reverse)
matchAllList = getmatchall(forwardread, reverseread, PrimerDictList, usePosStrand, target_portion_read_F, target_portion_read_R)
# throwing out reads if the primer did not match, likely low quality reads
if matchAllList == None:
#print "continue at if matchAllList == None:"
#print "The target portion read forward is below"
#print target_portion_read_F
#print "The name is " + reverseread.qname
continue
else:
matchF = matchAllList[0]
matchFexpectedLength = matchAllList[1]
matchR = matchAllList[2]
matchRexpectedLength = matchAllList[3]
targetLength=matchAllList[4]
startPos=matchAllList[5]
endPos=matchAllList[6]
originalreversecigar = reverseread.cigarstring
originalforwardcigar = forwardread.cigarstring
# cigar_end_error=change_cigar_end(originalreversecigar,matchR-1,numberlistR,numberlistintR,letterlistR,matchRexpectedLength-1,reverseread.query_length)
#cigar_end_error = change_cigar_end(originalreversecigar, matchRexpectedLength - 1, numberlistR, numberlistintR, letterlistR, matchRexpectedLength - 1, reverseread.query_length, read)
[cigar_end_error,overlappingReadsReverse] = change_cigar_either(True,originalreversecigar, matchRexpectedLength - 1, numberlistR, numberlistintR, letterlistR, matchRexpectedLength - 1, reverseread.query_length, reverseread, targetLength,startPos,endPos)
# cigar_start_error=change_cigar_start(originalforwardcigar,matchF-1,numberlistF,numberlistintF,letterlistF,matchFexpectedLength-1,forwardread.query_length)
#cigar_start_error = change_cigar_start(originalforwardcigar, matchFexpectedLength - 1, numberlistF, numberlistintF, letterlistF, matchFexpectedLength - 1, forwardread.query_length, read)
[cigar_start_error,overlappingReadsForward] = change_cigar_either(False,originalforwardcigar, matchFexpectedLength - 1, numberlistF, numberlistintF, letterlistF, matchFexpectedLength - 1, forwardread.query_length, forwardread, targetLength,startPos,endPos)
#from samtools specifications
#Bit 0x4 (read is unmapped) is the only reliable place to tell whether the read is unmapped. If 0x4 is set, no assumptions
#can be made about RNAME, POS, CIGAR, MAPQ, and bits 0x2, 0x100, and 0x800
#note need to comment out what I am doing to rname because even though it is in the specifications, it is giving GATK issues on validation
if cigar_end_error == True and cigar_start_error == True:
#TEMP print "There was an error in making both cigars"
read1 = None
read2 = None
#print "in cigar_end_error == True and cigar_start_error == True:"
#print "the original start cigar is" + str(originalforwardcigar)
#print "the original end cigar is" + str(originalreversecigar)
continue
if cigar_start_error == True:
#read1 = None
#read2 = None
#continue
#will unmap forward read if only cigar error in one of the reads
#print "in cigar_start_error == True"
#print "the original start cigar is" + str(originalforwardcigar)
if not (forwardread.is_unmapped):
tosubtract=0
if forwardread.is_secondary:
tosubtract=tosubtract+256
if forwardread.is_proper_pair:
tosubtract=tosubtract+2
if forwardread.is_supplementary:
tosubtract=tosubtract+2048
forwardread.flag = forwardread.flag + 4 - tosubtract
forwardread.mapping_quality = 0
forwardread.cigarstring=''
forwardread.pos=0
#forwardread.rname=0
reverseread.flag = reverseread.flag + 8
if cigar_end_error == True:
#read1 = None
#read2 = None
#continue
#will unmap reverse read if only cigar error in one of the reads
#print "in cigar_end_error == True"
#print "the original end cigar is" + str(originalreversecigar)
if not (reverseread.is_unmapped):
tosubtract=0
if reverseread.is_secondary:
tosubtract=tosubtract+256
if reverseread.is_proper_pair:
tosubtract=tosubtract+2
if reverseread.is_supplementary:
tosubtract=tosubtract+2048
reverseread.flag = reverseread.flag + 4 - tosubtract
reverseread.mapping_quality = 0
reverseread.cigarstring=''
reverseread.pos=0
#reverseread.rname=0
forwardread.flag = forwardread.flag + 8
# final double checking of CIGAR invalids
#and requires that all of its parts in the expression evaluate to True for the whole expression to be True.
#or is much less picky, as soon as any part of the expression evaluates to True the whole expression is True.
# print "THE ENDING CIGAR STRING IS : " + read.cigarstring
reverseread.mpos = forwardread.pos
forwardread.mpos = reverseread.pos
#print "The read is " + str(reverseread.qname)
###################NOW ADDING A CHECK WHERE I AM UNMAPPING A READ if there are > 10 mismatches or if reads overlap, drop read with more mismatches
###from sam format specifications
#MD ZString for mismatching positions. Regex : [0-9]+(([A-Z]|\^[A-Z]+)[0-9]+)*10
#to only get mismatches regex should be [0-9]+([A-Z]+)
#since don't want it where 6^ATTTTTTA is used because that represents a deletion
if not (cigar_end_error or cigar_start_error):
try:
mismatchTagForword=forwardread.get_tag('MD');
mismatchTagReverse=reverseread.get_tag('MD');
p = regex.compile(ur'[0-9]+([A-Z]+)')
mismatchLetterListForward=regex.findall(p,mismatchTagForword)
mismatchLetterListReverse=regex.findall(p,mismatchTagReverse)
numberofMismatchesF=len(mismatchLetterListForward)
numberofMismatchesR=len(mismatchLetterListReverse)
if numberofMismatchesF > 10 and not (forwardread.is_unmapped):
tosubtract=0
if forwardread.is_secondary:
tosubtract=tosubtract+256
if forwardread.is_proper_pair:
tosubtract=tosubtract+2
if forwardread.is_supplementary:
tosubtract=tosubtract+2048
forwardread.flag = forwardread.flag + 4 - tosubtract
forwardread.mapping_quality = 0
forwardread.cigarstring=''
forwardread.pos=0
#telling it that the mate is unmapped
reverseread.flag = reverseread.flag + 8
elif overlappingReadsReverse and not overlappingReadsForward and (numberofMismatchesR < numberofMismatchesF):
tosubtract=0
if forwardread.is_secondary:
tosubtract=tosubtract+256
if forwardread.is_proper_pair:
tosubtract=tosubtract+2
if forwardread.is_supplementary:
tosubtract=tosubtract+2048
forwardread.flag = forwardread.flag + 4 - tosubtract
forwardread.mapping_quality = 0
forwardread.cigarstring=''
forwardread.pos=0
#telling it that the mate is unmapped
reverseread.flag = reverseread.flag + 8
if numberofMismatchesR > 10 and not (reverseread.is_unmapped):
tosubtract=0
if reverseread.is_secondary:
tosubtract=tosubtract+256
if reverseread.is_proper_pair:
tosubtract=tosubtract+2
if reverseread.is_supplementary:
tosubtract=tosubtract+2048
reverseread.flag = reverseread.flag + 4 - tosubtract
reverseread.mapping_quality = 0
reverseread.cigarstring=''
reverseread.pos=0
#telling it that the mate is unmapped
forwardread.flag = forwardread.flag + 8
elif overlappingReadsForward and not overlappingReadsReverse and (numberofMismatchesF < numberofMismatchesR):
#suggests low quality reverse if it was clipped and still had more mismatches
tosubtract=0
if reverseread.is_secondary:
tosubtract=tosubtract+256
if reverseread.is_proper_pair:
tosubtract=tosubtract+2
if reverseread.is_supplementary:
tosubtract=tosubtract+2048
reverseread.flag = reverseread.flag + 4 - tosubtract
reverseread.mapping_quality = 0
reverseread.cigarstring=''
reverseread.pos=0
#telling it that the mate is unmapped
forwardread.flag = forwardread.flag + 8
except:
pass
#Do nothing, ie there is no MD
###########################
if reverseread.mapping_quality == 0 and forwardread.mapping_quality == 0:
read1 = None
read2 = None
continue
#if read.qname == 'M01382:152:000000000-AM7DD:1:1110:14900:4306':
#print "line 1230"
#print "In read M01382:152:000000000-AM7DD:1:1110:14900:4306"
#print "cigar_end_error is " + str(cigar_end_error)
#print "cigar_start_error is " + str(cigar_end_error)
#print "forward read qname is " + str(forwardread.qname)
#print "reverse read qname is " + str(reverseread.qname)
#print str(reverseread.is_read1)
#print str(reverseread.flag)
#print str(forwardread.is_read1)
#print str(forwardread.flag)
if reverseread.is_read1:
newreads.write(reverseread)
newreads.write(forwardread)
else:
newreads.write(forwardread)
newreads.write(reverseread)
# END FOR READ IN SAMFILE
newreads.close()
samfile.close()
if __name__ == "__main__":
main(sys.argv[1:])
|
from cms.models.pages import (
BlogIndexPage, EventIndexPage, HomePage, IndexPage, NewsIndexPage,
PastEventIndexPage, RichTextPage, _paginate, ChapterIndexPage,
PersonIndexPage
)
from django.test import RequestFactory, TestCase
from wagtail.tests.utils import WagtailPageTests
class TestPages(TestCase):
def test__paginate(self):
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
factory = RequestFactory()
request = factory.get('/test?page=1')
self.assertEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
_paginate(request, items).object_list)
request = factory.get('/test?page=2')
self.assertEqual([10, 11, 12, 13, 14, 15, 16, 17],
_paginate(request, items).object_list)
request = factory.get('/test?page=10')
self.assertEqual([10, 11, 12, 13, 14, 15, 16, 17],
_paginate(request, items).object_list)
request = factory.get('/test?page=a')
self.assertEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
_paginate(request, items).object_list)
class TestHomePage(WagtailPageTests):
fixtures = ['tests.json']
def test_subpage_types(self):
self.assertAllowedSubpageTypes(
HomePage, {
BlogIndexPage,
ChapterIndexPage,
EventIndexPage,
IndexPage,
NewsIndexPage,
PastEventIndexPage,
RichTextPage,
PersonIndexPage
})
class TestIndexPage(WagtailPageTests):
fixtures = ['tests.json']
def test_subpage_types(self):
self.assertAllowedSubpageTypes(IndexPage, {IndexPage, RichTextPage})
class TestRichTextPage(WagtailPageTests):
fixtures = ['tests.json']
def test_subpage_types(self):
self.assertAllowedSubpageTypes(RichTextPage, {})
|
import os
import re
import sys
import time
import json
import signal
import urllib.request
from decimal import Decimal
from urllib.parse import quote
from datetime import datetime
from subprocess import TimeoutExpired, Popen, PIPE, DEVNULL, CompletedProcess, CalledProcessError
from multiprocessing import Process
from config import (
IS_TTY,
OUTPUT_PERMISSIONS,
REPO_DIR,
SOURCES_DIR,
OUTPUT_DIR,
ARCHIVE_DIR,
TIMEOUT,
TERM_WIDTH,
SHOW_PROGRESS,
ANSI,
CHROME_BINARY,
FETCH_WGET,
FETCH_PDF,
FETCH_SCREENSHOT,
FETCH_DOM,
FETCH_FAVICON,
FETCH_MEDIA,
SUBMIT_ARCHIVE_DOT_ORG,
)
# URL helpers
without_scheme = lambda url: url.replace('http://', '').replace('https://', '').replace('ftp://', '')
without_query = lambda url: url.split('?', 1)[0]
without_hash = lambda url: url.split('#', 1)[0]
without_path = lambda url: url.split('/', 1)[0]
domain = lambda url: without_hash(without_query(without_path(without_scheme(url))))
base_url = lambda url: without_scheme(url) # uniq base url used to dedupe links
short_ts = lambda ts: ts.split('.')[0]
URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))[^<\""]+'
def check_dependencies():
"""Check that all necessary dependencies are installed, and have valid versions"""
python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
if python_vers < 3.5:
print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
print(' See https://github.com/pirate/ArchiveBox#troubleshooting for help upgrading your Python installation.')
raise SystemExit(1)
if FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM:
if run(['which', CHROME_BINARY], stdout=DEVNULL).returncode:
print('{}[X] Missing dependency: {}{}'.format(ANSI['red'], CHROME_BINARY, ANSI['reset']))
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
print(' See https://github.com/pirate/ArchiveBox for help.')
raise SystemExit(1)
# parse chrome --version e.g. Google Chrome 61.0.3114.0 canary / Chromium 59.0.3029.110 built on Ubuntu, running on Ubuntu 16.04
try:
result = run([CHROME_BINARY, '--version'], stdout=PIPE)
version_str = result.stdout.decode('utf-8')
version_lines = re.sub("(Google Chrome|Chromium) (\\d+?)\\.(\\d+?)\\.(\\d+?).*?$", "\\2", version_str).split('\n')
version = [l for l in version_lines if l.isdigit()][-1]
if int(version) < 59:
print(version_lines)
print('{red}[X] Chrome version must be 59 or greater for headless PDF, screenshot, and DOM saving{reset}'.format(**ANSI))
print(' See https://github.com/pirate/ArchiveBox for help.')
raise SystemExit(1)
except (IndexError, TypeError, OSError):
print('{red}[X] Failed to parse Chrome version, is it installed properly?{reset}'.format(**ANSI))
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
print(' See https://github.com/pirate/ArchiveBox for help.')
raise SystemExit(1)
if FETCH_WGET:
if run(['which', 'wget'], stdout=DEVNULL).returncode or run(['wget', '--version'], stdout=DEVNULL).returncode:
print('{red}[X] Missing dependency: wget{reset}'.format(**ANSI))
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('wget'))
print(' See https://github.com/pirate/ArchiveBox for help.')
raise SystemExit(1)
if FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG:
if run(['which', 'curl'], stdout=DEVNULL).returncode or run(['curl', '--version'], stdout=DEVNULL).returncode:
print('{red}[X] Missing dependency: curl{reset}'.format(**ANSI))
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('curl'))
print(' See https://github.com/pirate/ArchiveBox for help.')
raise SystemExit(1)
if FETCH_MEDIA:
if run(['which', 'youtube-dl'], stdout=DEVNULL).returncode or run(['youtube-dl', '--version'], stdout=DEVNULL).returncode:
print('{red}[X] Missing dependency: youtube-dl{reset}'.format(**ANSI))
print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('youtube-dl'))
print(' See https://github.com/pirate/ArchiveBox for help.')
raise SystemExit(1)
def chmod_file(path, cwd='.', permissions=OUTPUT_PERMISSIONS, timeout=30):
"""chmod -R <permissions> <cwd>/<path>"""
if not os.path.exists(os.path.join(cwd, path)):
raise Exception('Failed to chmod: {} does not exist (did the previous step fail?)'.format(path))
chmod_result = run(['chmod', '-R', permissions, path], cwd=cwd, stdout=DEVNULL, stderr=PIPE, timeout=timeout)
if chmod_result.returncode == 1:
print(' ', chmod_result.stderr.decode())
raise Exception('Failed to chmod {}/{}'.format(cwd, path))
def progress(seconds=TIMEOUT, prefix=''):
"""Show a (subprocess-controlled) progress bar with a <seconds> timeout,
returns end() function to instantly finish the progress
"""
if not SHOW_PROGRESS:
return lambda: None
def progress_bar(seconds, prefix):
"""show timer in the form of progress bar, with percentage and seconds remaining"""
chunk = '█' if sys.stdout.encoding == 'UTF-8' else '#'
chunks = TERM_WIDTH - len(prefix) - 20 # number of progress chunks to show (aka max bar width)
try:
for s in range(seconds * chunks):
progress = s / chunks / seconds * 100
bar_width = round(progress/(100/chunks))
# ████████████████████ 0.9% (1/60sec)
sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
prefix,
ANSI['green'],
(chunk * bar_width).ljust(chunks),
ANSI['reset'],
round(progress, 1),
round(s/chunks),
seconds,
))
sys.stdout.flush()
time.sleep(1 / chunks)
# ██████████████████████████████████ 100.0% (60/60sec)
sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)\n'.format(
prefix,
ANSI['red'],
chunk * chunks,
ANSI['reset'],
100.0,
seconds,
seconds,
))
sys.stdout.flush()
except KeyboardInterrupt:
print()
pass
p = Process(target=progress_bar, args=(seconds, prefix))
p.start()
def end():
"""immediately finish progress and clear the progressbar line"""
# protect from double termination
#if p is None or not hasattr(p, 'kill'):
# return
nonlocal p
if p is not None:
p.terminate()
p = None
sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH), ANSI['reset'])) # clear whole terminal line
sys.stdout.flush()
return end
def pretty_path(path):
"""convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
return path.replace(REPO_DIR + '/', '')
def save_source(raw_text):
if not os.path.exists(SOURCES_DIR):
os.makedirs(SOURCES_DIR)
ts = str(datetime.now().timestamp()).split('.', 1)[0]
source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format('stdin', ts))
with open(source_path, 'w', encoding='utf-8') as f:
f.write(raw_text)
return source_path
def download_url(url):
"""download a given url's content into downloads/domain.txt"""
if not os.path.exists(SOURCES_DIR):
os.makedirs(SOURCES_DIR)
ts = str(datetime.now().timestamp()).split('.', 1)[0]
source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format(domain(url), ts))
print('[*] [{}] Downloading {} > {}'.format(
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
url,
pretty_path(source_path),
))
end = progress(TIMEOUT, prefix=' ')
try:
downloaded_xml = urllib.request.urlopen(url).read().decode('utf-8')
end()
except Exception as e:
end()
print('[!] Failed to download {}\n'.format(url))
print(' ', e)
raise SystemExit(1)
with open(source_path, 'w', encoding='utf-8') as f:
f.write(downloaded_xml)
return source_path
def fetch_page_title(url, default=True):
"""Attempt to guess a page's title by downloading the html"""
if default is True:
default = url
try:
if SHOW_PROGRESS:
sys.stdout.write('.')
sys.stdout.flush()
html_content = urllib.request.urlopen(url, timeout=10).read().decode('utf-8')
match = re.search('<title>(.*?)</title>', html_content)
return match.group(1) if match else default or None
except Exception:
if default is False:
raise
return default
def str_between(string, start, end=None):
"""(<abc>12345</def>, <abc>, </def>) -> 12345"""
content = string.split(start, 1)[-1]
if end is not None:
content = content.rsplit(end, 1)[0]
return content
def get_link_type(link):
"""Certain types of links need to be handled specially, this figures out when that's the case"""
if link['base_url'].endswith('.pdf'):
return 'PDF'
elif link['base_url'].rsplit('.', 1) in ('pdf', 'png', 'jpg', 'jpeg', 'svg', 'bmp', 'gif', 'tiff', 'webp'):
return 'image'
elif 'wikipedia.org' in link['domain']:
return 'wiki'
elif 'youtube.com' in link['domain']:
return 'youtube'
elif 'soundcloud.com' in link['domain']:
return 'soundcloud'
elif 'youku.com' in link['domain']:
return 'youku'
elif 'vimeo.com' in link['domain']:
return 'vimeo'
return None
def merge_links(a, b):
"""deterministially merge two links, favoring longer field values over shorter,
and "cleaner" values over worse ones.
"""
longer = lambda key: a[key] if len(a[key]) > len(b[key]) else b[key]
earlier = lambda key: a[key] if a[key] < b[key] else b[key]
url = longer('url')
longest_title = longer('title')
cleanest_title = a['title'] if '://' not in a['title'] else b['title']
link = {
'timestamp': earlier('timestamp'),
'url': url,
'domain': domain(url),
'base_url': base_url(url),
'tags': longer('tags'),
'title': longest_title if '://' not in longest_title else cleanest_title,
'sources': list(set(a.get('sources', []) + b.get('sources', []))),
}
link['type'] = get_link_type(link)
return link
def find_link(folder, links):
"""for a given archive folder, find the corresponding link object in links"""
url = parse_url(folder)
if url:
for link in links:
if (link['base_url'] in url) or (url in link['url']):
return link
timestamp = folder.split('.')[0]
for link in links:
if link['timestamp'].startswith(timestamp):
if link['domain'] in os.listdir(os.path.join(ARCHIVE_DIR, folder)):
return link # careful now, this isn't safe for most ppl
if link['domain'] in parse_url(folder):
return link
return None
def parse_url(folder):
"""for a given archive folder, figure out what url it's for"""
link_json = os.path.join(ARCHIVE_DIR, folder, 'index.json')
if os.path.exists(link_json):
with open(link_json, 'r') as f:
try:
link_json = f.read().strip()
if link_json:
link = json.loads(link_json)
return link['base_url']
except ValueError:
print('File contains invalid JSON: {}!'.format(link_json))
archive_org_txt = os.path.join(ARCHIVE_DIR, folder, 'archive.org.txt')
if os.path.exists(archive_org_txt):
with open(archive_org_txt, 'r') as f:
original_link = f.read().strip().split('/http', 1)[-1]
with_scheme = 'http{}'.format(original_link)
return with_scheme
return ''
def manually_merge_folders(source, target):
"""prompt for user input to resolve a conflict between two archive folders"""
if not IS_TTY:
return
fname = lambda path: path.split('/')[-1]
print(' {} and {} have conflicting files, which do you want to keep?'.format(fname(source), fname(target)))
print(' - [enter]: do nothing (keep both)')
print(' - a: prefer files from {}'.format(source))
print(' - b: prefer files from {}'.format(target))
print(' - q: quit and resolve the conflict manually')
try:
answer = input('> ').strip().lower()
except KeyboardInterrupt:
answer = 'q'
assert answer in ('', 'a', 'b', 'q'), 'Invalid choice.'
if answer == 'q':
print('\nJust run ArchiveBox again to pick up where you left off.')
raise SystemExit(0)
elif answer == '':
return
files_in_source = set(os.listdir(source))
files_in_target = set(os.listdir(target))
for file in files_in_source:
if file in files_in_target:
to_delete = target if answer == 'a' else source
run(['rm', '-Rf', os.path.join(to_delete, file)])
run(['mv', os.path.join(source, file), os.path.join(target, file)])
if not set(os.listdir(source)):
run(['rm', '-Rf', source])
def fix_folder_path(archive_path, link_folder, link):
"""given a folder, merge it to the canonical 'correct' path for the given link object"""
source = os.path.join(archive_path, link_folder)
target = os.path.join(archive_path, link['timestamp'])
url_in_folder = parse_url(source)
if not (url_in_folder in link['base_url']
or link['base_url'] in url_in_folder):
raise ValueError('The link does not match the url for this folder.')
if not os.path.exists(target):
# target doesn't exist so nothing needs merging, simply move A to B
run(['mv', source, target])
else:
# target folder exists, check for conflicting files and attempt manual merge
files_in_source = set(os.listdir(source))
files_in_target = set(os.listdir(target))
conflicting_files = files_in_source & files_in_target
if not conflicting_files:
for file in files_in_source:
run(['mv', os.path.join(source, file), os.path.join(target, file)])
if os.path.exists(source):
files_in_source = set(os.listdir(source))
if files_in_source:
manually_merge_folders(source, target)
else:
run(['rm', '-R', source])
def migrate_data():
# migrate old folder to new OUTPUT folder
old_dir = os.path.join(REPO_DIR, 'html')
if os.path.exists(old_dir):
print('[!] WARNING: Moved old output folder "html" to new location: {}'.format(OUTPUT_DIR))
run(['mv', old_dir, OUTPUT_DIR], timeout=10)
def cleanup_archive(archive_path, links):
"""move any incorrectly named folders to their canonical locations"""
# for each folder that exists, see if we can match it up with a known good link
# if we can, then merge the two folders (TODO: if not, move it to lost & found)
unmatched = []
bad_folders = []
if not os.path.exists(archive_path):
return
for folder in os.listdir(archive_path):
try:
files = os.listdir(os.path.join(archive_path, folder))
except NotADirectoryError:
continue
if files:
link = find_link(folder, links)
if link is None:
unmatched.append(folder)
continue
if folder != link['timestamp']:
bad_folders.append((folder, link))
else:
# delete empty folders
run(['rm', '-R', os.path.join(archive_path, folder)])
if bad_folders and IS_TTY and input('[!] Cleanup archive? y/[n]: ') == 'y':
print('[!] Fixing {} improperly named folders in archive...'.format(len(bad_folders)))
for folder, link in bad_folders:
fix_folder_path(archive_path, folder, link)
elif bad_folders:
print('[!] Warning! {} folders need to be merged, fix by running ArchiveBox.'.format(len(bad_folders)))
if unmatched:
print('[!] Warning! {} unrecognized folders in html/archive/'.format(len(unmatched)))
print(' '+ '\n '.join(unmatched))
def wget_output_path(link, look_in=None):
"""calculate the path to the wgetted .html file, since wget may
adjust some paths to be different than the base_url path.
See docs on wget --adjust-extension (-E)
"""
# if we have it stored, always prefer the actual output path to computed one
if link.get('latest', {}).get('wget'):
return link['latest']['wget']
urlencode = lambda s: quote(s, encoding='utf-8', errors='replace')
if link['type'] in ('PDF', 'image'):
return urlencode(link['base_url'])
# Since the wget algorithm to for -E (appending .html) is incredibly complex
# instead of trying to emulate it here, we just look in the output folder
# to see what html file wget actually created as the output
wget_folder = link['base_url'].rsplit('/', 1)[0].split('/')
look_in = os.path.join(ARCHIVE_DIR, link['timestamp'], *wget_folder)
if look_in and os.path.exists(look_in):
html_files = [
f for f in os.listdir(look_in)
if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", f, re.I | re.M)
]
if html_files:
return urlencode(os.path.join(*wget_folder, html_files[0]))
return None
# If finding the actual output file didn't work, fall back to the buggy
# implementation of the wget .html appending algorithm
# split_url = link['url'].split('#', 1)
# query = ('%3F' + link['url'].split('?', 1)[-1]) if '?' in link['url'] else ''
# if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", split_url[0], re.I | re.M):
# # already ends in .html
# return urlencode(link['base_url'])
# else:
# # .html needs to be appended
# without_scheme = split_url[0].split('://', 1)[-1].split('?', 1)[0]
# if without_scheme.endswith('/'):
# if query:
# return urlencode('#'.join([without_scheme + 'index.html' + query + '.html', *split_url[1:]]))
# return urlencode('#'.join([without_scheme + 'index.html', *split_url[1:]]))
# else:
# if query:
# return urlencode('#'.join([without_scheme + '/index.html' + query + '.html', *split_url[1:]]))
# elif '/' in without_scheme:
# return urlencode('#'.join([without_scheme + '.html', *split_url[1:]]))
# return urlencode(link['base_url'] + '/index.html')
def derived_link_info(link):
"""extend link info with the archive urls and other derived data"""
link_info = {
**link,
'date': datetime.fromtimestamp(Decimal(link['timestamp'])).strftime('%Y-%m-%d %H:%M'),
'google_favicon_url': 'https://www.google.com/s2/favicons?domain={domain}'.format(**link),
'favicon_url': 'archive/{timestamp}/favicon.ico'.format(**link),
'files_url': 'archive/{timestamp}/index.html'.format(**link),
'archive_url': 'archive/{}/{}'.format(link['timestamp'], wget_output_path(link) or 'index.html'),
'pdf_link': 'archive/{timestamp}/output.pdf'.format(**link),
'screenshot_link': 'archive/{timestamp}/screenshot.png'.format(**link),
'dom_link': 'archive/{timestamp}/output.html'.format(**link),
'archive_org_url': 'https://web.archive.org/web/{base_url}'.format(**link),
}
# PDF and images are handled slightly differently
# wget, screenshot, & pdf urls all point to the same file
if link['type'] in ('PDF', 'image'):
link_info.update({
'archive_url': 'archive/{timestamp}/{base_url}'.format(**link),
'pdf_link': 'archive/{timestamp}/{base_url}'.format(**link),
'screenshot_link': 'archive/{timestamp}/{base_url}'.format(**link),
'dom_link': 'archive/{timestamp}/{base_url}'.format(**link),
'title': '{title} ({type})'.format(**link),
})
return link_info
def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs):
"""Patched of subprocess.run to fix blocking io making timeout=innefective"""
if input is not None:
if 'stdin' in kwargs:
raise ValueError('stdin and input arguments may not both be used.')
kwargs['stdin'] = PIPE
if capture_output:
if ('stdout' in kwargs) or ('stderr' in kwargs):
raise ValueError('stdout and stderr arguments may not be used '
'with capture_output.')
kwargs['stdout'] = PIPE
kwargs['stderr'] = PIPE
with Popen(*popenargs, **kwargs) as process:
try:
stdout, stderr = process.communicate(input, timeout=timeout)
except TimeoutExpired:
process.kill()
try:
stdout, stderr = process.communicate(input, timeout=2)
except:
pass
raise TimeoutExpired(popenargs[0][0], timeout)
except BaseException as err:
process.kill()
# We don't call process.wait() as .__exit__ does that for us.
raise
retcode = process.poll()
if check and retcode:
raise CalledProcessError(retcode, process.args,
output=stdout, stderr=stderr)
return CompletedProcess(process.args, retcode, stdout, stderr)
|
# 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 .error_details import ErrorDetails
from .error_response import ErrorResponse, ErrorResponseException
from .operation_display import OperationDisplay
from .operation import Operation
from .management_group_info import ManagementGroupInfo
from .parent_group_info import ParentGroupInfo
from .management_group_details import ManagementGroupDetails
from .management_group_child_info import ManagementGroupChildInfo
from .management_group import ManagementGroup
from .create_management_group_request import CreateManagementGroupRequest
from .management_group_info_paged import ManagementGroupInfoPaged
from .operation_paged import OperationPaged
__all__ = [
'ErrorDetails',
'ErrorResponse', 'ErrorResponseException',
'OperationDisplay',
'Operation',
'ManagementGroupInfo',
'ParentGroupInfo',
'ManagementGroupDetails',
'ManagementGroupChildInfo',
'ManagementGroup',
'CreateManagementGroupRequest',
'ManagementGroupInfoPaged',
'OperationPaged',
]
|
# Copyright 2019 SAP SE
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import inspect
import sys
class FakeTbFrame(object):
def __init__(self, tb_frame, tb_lineno, tb_next):
self.tb_frame = tb_frame
self.tb_lineno = tb_lineno
self.tb_next = tb_next
def exc_info_full(exc_type=None, exc_descr=None, skip=1):
# save orig exception / tb info
orig_exc_type, orig_exc, tb = sys.exc_info()
exc_type = exc_type if exc_type is not None else orig_exc_type
exc_descr = exc_descr if exc_descr is not None else orig_exc
for stack_frame in inspect.stack()[skip:]:
tb_frame = stack_frame[0]
tb = FakeTbFrame(tb_frame, tb_frame.f_lineno, tb)
return exc_type, exc_descr, tb
|
"""
Author: Omkar Damle
March 2018
"""
from torch.utils.data import Dataset
import os
import numpy as np
import cv2
from scipy.misc import imresize
class DAVIS17OnlineDataset(Dataset):
def __init__(self, train=True,
inputRes=None,
db_root_dir='',
transform=None,
meanval=(104.00699, 116.66877, 122.67892),
seq_name=None, noIterations=1,
object_id = -1):
"""Loads deformations along with images and ground truth examples
db_root_dir: dataset directory with subfolders "JPEGImages" and "Annotations" and "Deformations"
"""
self.train = train
self.inputRes = inputRes
self.db_root_dir = db_root_dir
self.transform = transform
self.meanval = meanval
self.seq_name = seq_name
self.object_id = object_id
image_list_fname = 'train'
angle_list = [2*(angle+1) for angle in range(10)]
neg_angle_list = [-angle for angle in angle_list]
angle_list.extend(neg_angle_list)
angle_list.extend([None])
flip_list = [0,1]
if self.seq_name is None:
print('Please give sequence name')
return
else:
image_list = []
gt_list = []
deformations1_list = []
deformations2_list = []
base_path = "Deformations/480p/" + self.seq_name + "_online/00000"
for iterNo in range(noIterations):
for angle in angle_list:
for flip in flip_list:
angleString = ""
if angle is not None:
angleString = 'angle' + str(angle) + '_'
flipString = ""
if flip==1:
flipString = 'flipped_'
tempString = base_path + '_' + str(iterNo+1) + '_' + angleString + flipString
tempString1 = base_path + '_' + str(self.object_id) + '_' + str(iterNo+1) + '_' + angleString + flipString
image_list.append(tempString + 'i.png')
gt_list.append(tempString1 + 'gt.png')
deformations1_list.append(tempString1 + 'd1.png')
deformations2_list.append(tempString1 + 'd2.png')
self.img_list = image_list
self.labels = gt_list
self.deformations1 = deformations1_list
self.deformations2 = deformations2_list
assert (len(self.img_list) == len(self.labels))
assert(len(self.labels) == len(self.deformations1))
assert(len(self.labels) == len(self.deformations2))
def __len__(self):
return len(self.img_list)
def __getitem__(self, idx):
img, gt = self.make_img_gt_pair(idx)
df1, df2 = self.make_df1_df2(idx)
sample = {'image': img, 'gt': gt, 'df1': df1, 'df2':df2}
if self.seq_name is not None:
fname = os.path.join(self.seq_name, "%05d" % idx)
sample['fname'] = fname
if self.transform is not None:
sample = self.transform(sample)
return sample
def make_img_gt_pair(self, idx):
"""
Make the image-ground-truth pair
"""
img = cv2.imread(os.path.join(self.db_root_dir, self.img_list[idx]))
if self.labels[idx] is not None:
label = cv2.imread(os.path.join(self.db_root_dir, self.labels[idx]), 0)
else:
gt = np.zeros(img.shape[:-1], dtype=np.uint8)
if self.inputRes is not None:
img = imresize(img, self.inputRes)
if self.labels[idx] is not None:
label = imresize(label, self.inputRes, interp='nearest')
img = np.array(img, dtype=np.float32)
img = np.subtract(img, np.array(self.meanval, dtype=np.float32))
if self.labels[idx] is not None:
gt = np.array(label, dtype=np.float32)
gt = gt/np.max([gt.max(), 1e-8])
return img, gt
def make_df1_df2(self, idx):
"""
Make the deformations
"""
df1 = cv2.imread(os.path.join(self.db_root_dir, self.deformations1[idx]), cv2.IMREAD_GRAYSCALE)
df2 = cv2.imread(os.path.join(self.db_root_dir, self.deformations2[idx]), cv2.IMREAD_GRAYSCALE)
if self.inputRes is not None:
df1 = imresize(df1, self.inputRes, interp='nearest')
df2 = imresize(df2, self.inputRes, interp='nearest')
df1 = np.array(df1, dtype=np.float32)
df1 = df1/np.max([df1.max(), 1e-8])
df2 = np.array(df2, dtype=np.float32)
df2 = df2/np.max([df2.max(), 1e-8])
return df1, df2
|
# Copyright 2017 Google LLC
#
# 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 functools
import operator
import unittest
from google.cloud import error_reporting
from google.cloud.errorreporting_v1beta1.gapic import error_stats_service_client
from google.cloud.errorreporting_v1beta1.proto import error_stats_service_pb2
from google.protobuf.duration_pb2 import Duration
from test_utils.retry import RetryResult
from test_utils.system import unique_resource_id
ERROR_MSG = "Stackdriver Error Reporting System Test"
def setUpModule():
Config.CLIENT = error_reporting.Client()
class Config(object):
"""Run-time configuration to be modified at set-up.
This is a mutable stand-in to allow test set-up to modify
global state.
"""
CLIENT = None
def _list_groups(client):
"""List Error Groups from the last 60 seconds.
This class provides a wrapper around making calls to the GAX
API. It's used by the system tests to find the appropriate error group
to verify the error was successfully reported.
:type client: :class:`~google.cloud.error_reporting.client.Client`
:param client: The client containing a project and credentials.
:rtype: :class:`~google.gax.ResourceIterator`
:returns: Iterable of :class:`~.error_stats_service_pb2.ErrorGroupStats`.
"""
gax_api = error_stats_service_client.ErrorStatsServiceClient(
credentials=client._credentials
)
project_name = gax_api.project_path(client.project)
time_range = error_stats_service_pb2.QueryTimeRange()
time_range.period = error_stats_service_pb2.QueryTimeRange.PERIOD_1_HOUR
duration = Duration(seconds=60 * 60)
return gax_api.list_group_stats(
project_name, time_range, timed_count_duration=duration
)
def _simulate_exception(class_name, client):
"""Simulates an exception to verify it was reported.
:type class_name: str
:param class_name: The name of a custom error class to
create (and raise).
:type client: :class:`~google.cloud.error_reporting.client.Client`
:param client: The client that will report the exception.
"""
custom_exc = type(class_name, (RuntimeError,), {})
try:
raise custom_exc(ERROR_MSG)
except RuntimeError:
client.report_exception()
def _get_error_count(class_name, client):
"""Counts the number of errors in the group of the test exception.
:type class_name: str
:param class_name: The name of a custom error class used.
:type client: :class:`~google.cloud.error_reporting.client.Client`
:param client: The client containing a project and credentials.
:rtype: int
:returns: Group count for errors that match ``class_name``. If no
match is found, returns :data:`None`.
"""
groups = _list_groups(client)
for group in groups:
if class_name in group.representative.message:
return group.count
class TestErrorReporting(unittest.TestCase):
def test_report_exception(self):
# Get a class name unique to this test case.
class_name = "RuntimeError" + unique_resource_id("_")
# Simulate an error: group won't exist until we report
# first exception.
_simulate_exception(class_name, Config.CLIENT)
is_one = functools.partial(operator.eq, 1)
is_one.__name__ = "is_one" # partial() has no name.
retry = RetryResult(is_one, max_tries=6)
wrapped_get_count = retry(_get_error_count)
error_count = wrapped_get_count(class_name, Config.CLIENT)
self.assertEqual(error_count, 1)
|
from cyder.api.v1.endpoints.dns.mx import api
|
from __future__ import absolute_import, print_function
from datetime import datetime
import requests
from dateutil import parser
from . import endpoints
from .model.show import Show, Alias
from .model.episode import Episode
from .model.season import Season
from .model.person import Character, Person, Crew
from .model.embed import Embed
def _query_api(url, params=None):
res = requests.get(url, params)
print(res.url)
if res.status_code != requests.codes.OK:
print('Page request was unsuccessful: ' + res.status_code, res.reason)
return None
return res.json()
def search_show(show_name):
res = _query_api(endpoints.search_show_name, {'q': show_name})
return [Show(show) for show in res] if res is not None else []
def search_show_best_match(show_name, embed=None):
embed = Embed(embed)
res = _query_api(endpoints.search_show_best_match, {'q': show_name, embed.key: embed.value})
return Show(res) if res is not None else None
def get_show_external(imdb_id=None, tvdb_id=None, tvrage_id=None):
if len(list(filter(None, [imdb_id, tvdb_id, tvrage_id]))) == 0:
return None
if imdb_id is not None:
return _get_show_external_id('imdb', imdb_id)
if tvdb_id is not None:
return _get_show_external_id('thetvdb', tvdb_id)
if tvrage_id is not None:
return _get_show_external_id('tvrage', tvrage_id)
def _get_show_external_id(external_name, external_id):
res = _query_api(endpoints.search_external_show_id, {external_name: external_id})
return Show(res) if res is not None else None
def get_show(tvmaze_id, populated=False, embed=None):
embed = Embed(embed) if not populated else Embed(['seasons', 'cast', 'crew'])
res = _query_api(endpoints.show_information.format(str(tvmaze_id)), {embed.key: embed.value})
if populated:
episodes = [episode for episode in _get_show_episode_list_raw(tvmaze_id, specials=True)]
res['_embedded']['episodes'] = episodes
return Show(res) if res is not None else None
def get_show_episode_list(tvmaze_id, specials=False):
specials = 1 if specials else None
res = _get_show_episode_list_raw(tvmaze_id, specials)
return [Episode(episode) for episode in res] if res is not None else []
def _get_show_episode_list_raw(tvmaze_id, specials):
return _query_api(endpoints.show_episode_list.format(str(tvmaze_id)), {'specials': specials})
def get_show_specials(tvmaze_id):
res = _query_api(endpoints.show_episode_list.format(str(tvmaze_id)), {'specials': 1})
specials = [Episode(episode) for episode in res if episode['number'] is None] if res is not None else []
special_num = 1
for special in specials:
special.season = 0
special.number = special_num
special_num += 1
return specials
def get_show_episode(tvmaze_id, season, episode):
res = _query_api(endpoints.show_episode.format(str(tvmaze_id)), {'season': season, 'number': episode})
return Episode(res) if res is not None else None
def get_show_episodes_by_date(tvmaze_id, date_input):
if type(date_input) is str:
try:
date = parser.parse(date_input)
except parser._parser.ParserError:
return []
elif type(date_input) is datetime:
date = date_input
else:
return []
res = _query_api(endpoints.show_episodes_on_date.format(str(tvmaze_id)), {'date': date.isoformat()[:10]})
return [Episode(episode) for episode in res] if res is not None else []
def get_show_season_list(tvmaze_id):
res = _query_api(endpoints.show_season_list.format(str(tvmaze_id)))
return [Season(season) for season in res] if res is not None else []
def get_season_episode_list(tvmaze_season_id):
res = _query_api(endpoints.season_episode_list.format(str(tvmaze_season_id)))
# episode['number'] is None when it is classed as a special, for now don't include specials
return [Episode(episode) for episode in res if episode['number'] is not None] if res is not None else []
def get_show_aliases(tvmaze_id):
res = _query_api(endpoints.show_alias_list.format(str(tvmaze_id)))
return [Alias(alias) for alias in res] if res is not None else []
def get_episode_information(tvmaze_episode_id, embed=None):
embed = Embed(embed)
res = _query_api(endpoints.episode_information.format(str(tvmaze_episode_id)), {embed.key: embed.value})
return Episode(res) if res is not None else None
def get_show_cast(tvmaze_id):
res = _query_api(endpoints.show_cast.format(str(tvmaze_id)))
return [Character(cast['character'], cast['person']) for cast in res]
def get_show_crew(tvmaze_id):
res = _query_api(endpoints.show_crew.format(str(tvmaze_id)))
return [Crew(crew_member) for crew_member in res]
|
import os, sys, socket, random
from urllib import quote_plus
from panda3d.core import HTTPClient, HTTPCookie, URLSpec, Ramfile, Ostream, HTTPDate, DocumentSpec
from direct.task.Task import Task
from direct.directnotify.DirectNotifyGlobal import directNotify
notify = directNotify.newCategory('UserFunnel')
class UserFunnel:
def __init__(self):
self.hitboxAcct = 'DM53030620EW'
self.language = 'en-us'
self.cgRoot = 'ToonTown_Online'
self.cgBeta = 'Beta'
self.cgRelease = 'Release'
self.cgLocation = 'US'
self.campaignID = ''
self.cfCookieFile = 'cf.txt'
self.dynamicVRFunnel = 'http://download.toontown.com/'
self.hostDict = {0: 'Internal Disney PHP Collector Site',
1: 'ehg-dig.hitbox.com/HG?',
2: 'ehg-dig.hitbox.com/HG?',
3: 'build64.online.disney.com:5020/index.php?'}
self.CurrentHost = ''
self.URLtoSend = ''
self.gameName = 'ToonTown'
self.browserName = 'Panda3D%20(' + self.gameName + ';%20' + sys.platform + ')'
self.HTTPUserHeader = [('User-agent', 'Panda3D')]
self.osMajorver = ''
self.osMinorver = ''
self.osRevver = ''
self.osBuild = ''
self.osType = ''
self.osComments = ''
self.msWinTypeDict = {0: 'Win32s on Windows 3.1',
1: 'Windows 95/98/ME',
2: 'Windows NT/2000/XP',
3: 'Windows CE'}
self.milestoneDict = {0: 'New User',
1: 'Create Account',
2: 'View EULA',
3: 'Accept EULA',
4: 'Download Start',
5: 'Download End',
6: 'Installer Run',
7: 'Launcher Start',
8: 'Launcher Login',
9: 'Client Opens',
10: 'Create Pirate Loads',
11: 'Create Pirate Exit',
12: 'Cutscene One Start',
13: 'Cutscene One Ends',
14: 'Cutscene Two Start',
15: 'Cutscene Thee Start',
16: 'Cutscene Three Ends',
17: 'Access Cannon',
18: 'Cutscene Four Starts',
19: 'Cutscene Four Ends',
20: 'Dock - Start Game'}
self.macTypeDict = {2: 'Jaguar',
1: 'Puma',
3: 'Panther',
4: 'Tiger',
5: 'Lepard'}
self.milestone = ''
self.pandaHTTPClientVarWSS = []
self.pandaHTTPClientVarCTG = []
self.pandaHTTPClientVarDM = []
self.checkForCFfile()
self.httpSession = HTTPClient()
self.whatOSver()
def checkForCFfile(self):
if firstRun() == True:
pass
elif os.path.isfile(self.cfCookieFile) == False:
firstRun('write', True)
def whatOSver(self):
if sys.platform == 'win32':
self.osMajorver = str(sys.getwindowsversion()[0])
self.osMinorver = str(sys.getwindowsversion()[1])
self.osBuild = str(sys.getwindowsversion()[2])
self.osType = str(sys.getwindowsversion()[3])
self.osComments = str(sys.getwindowsversion()[4])
return
if sys.platform == 'darwin':
self.osMajorver = '10'
osxcmd = '/usr/sbin/system_profiler SPSoftwareDataType |/usr/bin/grep "System Version"'
infopipe = os.popen(osxcmd, 'r')
parseLine = infopipe.read()
infopipe.close()
del infopipe
notify.info('parseLine = %s' % str(parseLine))
versionStringStart = parseLine.find('10.')
notify.info('versionStringStart = %s' % str(versionStringStart))
testPlist = False
try:
self.osMinorver = parseLine[versionStringStart + 3]
self.osRevver = parseLine[versionStringStart + 5:versionStringStart + 7].strip(' ')
self.osBuild = parseLine[int(parseLine.find('(')) + 1:parseLine.find(')')]
except:
notify.info("couldn't parse the system_profiler output, using zeros")
self.osMinorver = '0'
self.osRevver = '0'
self.osBuild = '0000'
testPlist = True
del versionStringStart
del parseLine
del osxcmd
if testPlist:
try:
import plistlib
pl = plistlib.readPlist('/System/Library/CoreServices/SystemVersion.plist')
notify.info('pl=%s' % str(pl))
parseLine = pl['ProductVersion']
numbers = parseLine.split('.')
notify.info('parseline =%s numbers =%s' % (parseLine, numbers))
self.osMinorver = numbers[1]
self.osRevver = numbers[2]
self.osBuild = pl['ProductBuildVersion']
except:
notify.info('tried plist but still got exception')
self.osMinorver = '0'
self.osRevver = '0'
self.osBuild = '0000'
return
def setmilestone(self, ms):
if firstRun() == False:
self.milestone = ms
else:
self.milestone = '%s_INITIAL' % ms
def setgamename(self, gamename):
self.gameName = gamename
def printosComments(self):
return self.osComments
def setHost(self, hostID):
self.CurrentHost = hostID
def getFunnelURL(self):
if patcherVer() == ['OFFLINE']:
return
if patcherVer() == []:
patcherHTTP = HTTPClient()
if checkParamFile() == None:
patcherDoc = patcherHTTP.getDocument(URLSpec('http://download.toontown.com/english/currentVersion/content/patcher.ver'))
vconGroup('w', self.cgRelease)
else:
patcherDoc = patcherHTTP.getDocument(URLSpec(checkParamFile()))
vconGroup('w', self.cgBeta)
rf = Ramfile()
patcherDoc.downloadToRam(rf)
self.patcherURL = rf.getData()
if self.patcherURL.find('FUNNEL_LOG') == -1:
patcherVer('w', 'OFFLINE')
return
self.patcherURL = self.patcherURL.split('\n')
del rf
del patcherDoc
del patcherHTTP
while self.patcherURL:
self.confLine = self.patcherURL.pop()
if self.confLine.find('FUNNEL_LOG=') != -1 and self.confLine.find('#FUNNEL_LOG=') == -1:
self.dynamicVRFunnel = self.confLine[11:].strip('\n')
patcherVer('w', self.confLine[11:].strip('\n'))
else:
self.dynamicVRFunnel = patcherVer()[0]
return
def isVarSet(self, varInQuestion):
try:
tempvar = type(varInQuestion)
return 1
except NameError:
return 0
def buildURL(self):
if sys.platform == 'win32':
hitboxOSType = 'c3'
else:
hitboxOSType = 'c4'
if self.CurrentHost == 1:
self.URLtoSend = 'http://' + self.hostDict[self.CurrentHost] + 'hb=' + str(self.hitboxAcct) + '&n=' + str(self.milestone) + '&ln=' + self.language + '&gp=STARTGAME&fnl=TOONTOWN_FUNNEL&vcon=/' + self.cgRoot + '/' + self.cgLocation + '/' + str(vconGroup()) + '&c1=' + str(sys.platform) + '&' + str(hitboxOSType) + '=' + str(self.osMajorver) + '_' + str(self.osMinorver) + '_' + str(self.osRevver) + '_' + str(self.osBuild)
if self.CurrentHost == 2:
self.URLtoSend = 'http://' + self.hostDict[self.CurrentHost] + 'hb=' + str(self.hitboxAcct) + '&n=' + str(self.milestone) + '&ln=' + self.language + '&vcon=/' + self.cgRoot + '/' + self.cgLocation + '/' + str(vconGroup()) + '&c1=' + str(sys.platform) + '&' + str(hitboxOSType) + '=' + str(self.osMajorver) + '_' + str(self.osMinorver) + '_' + str(self.osRevver) + '_' + str(self.osBuild)
if self.CurrentHost == 0:
localMAC = str(getMAC())
self.URLtoSend = str(self.dynamicVRFunnel) + '?funnel=' + str(self.milestone) + '&platform=' + str(sys.platform) + '&sysver=' + str(self.osMajorver) + '_' + str(self.osMinorver) + '_' + str(self.osRevver) + '_' + str(self.osBuild) + '&mac=' + localMAC + '&username=' + str(loggingSubID()) + '&id=' + str(loggingAvID())
def readInPandaCookie(self):
thefile = open(self.cfCookieFile, 'r')
thedata = thefile.read().split('\n')
thefile.close()
del thefile
if thedata[0].find('Netscape HTTP Cookie File') != -1:
return
thedata.pop()
try:
while thedata:
temp = thedata.pop()
temp = temp.split('\t')
domain = temp[0]
loc = temp[1]
variable = temp[2]
value = temp[3]
if variable == 'CTG':
self.pandaHTTPClientVarCTG = [domain,
loc,
variable,
value]
self.setTheHTTPCookie(self.pandaHTTPClientVarCTG)
if variable == self.hitboxAcct + 'V6':
self.pandaHTTPClientVarDM = [domain,
loc,
variable,
value]
self.setTheHTTPCookie(self.pandaHTTPClientVarDM)
if variable == 'WSS_GW':
self.pandaHTTPClientVarWSS = [domain,
loc,
variable,
value]
self.setTheHTTPCookie(self.pandaHTTPClientVarWSS)
except IndexError:
print 'UserFunnel(Warning): Cookie Data file bad'
del thedata
def updateInstanceCookieValues(self):
a = self.httpSession.getCookie(HTTPCookie('WSS_GW', '/', '.hitbox.com'))
if a.getName():
self.pandaHTTPClientVarWSS = ['.hitbox.com',
'/',
'WSS_GW',
a.getValue()]
b = self.httpSession.getCookie(HTTPCookie('CTG', '/', '.hitbox.com'))
if b.getName():
self.pandaHTTPClientVarCTG = ['.hitbox.com',
'/',
'CTG',
b.getValue()]
c = self.httpSession.getCookie(HTTPCookie(self.hitboxAcct + 'V6', '/', 'ehg-dig.hitbox.com'))
if c.getName():
self.pandaHTTPClientVarDM = ['ehg-dig.hitbox.com',
'/',
self.hitboxAcct + 'V6',
c.getValue()]
del a
del b
del c
def setTheHTTPCookie(self, cookieParams):
c = HTTPCookie(cookieParams[2], cookieParams[1], cookieParams[0])
c.setValue(cookieParams[3])
self.httpSession.setCookie(c)
def writeOutPandaCookie(self):
try:
thefile = open(self.cfCookieFile, 'w')
if len(self.pandaHTTPClientVarWSS) == 4:
thefile.write(self.pandaHTTPClientVarWSS[0] + '\t' + self.pandaHTTPClientVarWSS[1] + '\t' + self.pandaHTTPClientVarWSS[2] + '\t' + self.pandaHTTPClientVarWSS[3] + '\n')
if len(self.pandaHTTPClientVarCTG) == 4:
thefile.write(self.pandaHTTPClientVarCTG[0] + '\t' + self.pandaHTTPClientVarCTG[1] + '\t' + self.pandaHTTPClientVarCTG[2] + '\t' + self.pandaHTTPClientVarCTG[3] + '\n')
if len(self.pandaHTTPClientVarDM) == 4:
thefile.write(self.pandaHTTPClientVarDM[0] + '\t' + self.pandaHTTPClientVarDM[1] + '\t' + self.pandaHTTPClientVarDM[2] + '\t' + self.pandaHTTPClientVarDM[3] + '\n')
thefile.close()
except IOError:
return
def prerun(self):
self.getFunnelURL()
self.buildURL()
if os.path.isfile(self.cfCookieFile) == True:
if self.CurrentHost == 1 or self.CurrentHost == 2:
self.readInPandaCookie()
def run(self):
if self.CurrentHost == 0 and patcherVer() == ['OFFLINE']:
return
self.nonBlock = self.httpSession.makeChannel(False)
self.nonBlock.beginGetDocument(DocumentSpec(self.URLtoSend))
instanceMarker = str(random.randint(1, 1000))
instanceMarker = 'FunnelLoggingRequest-%s' % instanceMarker
self.startCheckingAsyncRequest(instanceMarker)
def startCheckingAsyncRequest(self, name):
taskMgr.remove(name)
taskMgr.doMethodLater(0.5, self.pollFunnelTask, name)
def stopCheckingFunnelTask(self, name):
taskMgr.remove('pollFunnelTask')
def pollFunnelTask(self, task):
result = self.nonBlock.run()
if result == 0:
self.stopCheckingFunnelTask(task)
if self.CurrentHost == 1 or self.CurrentHost == 2:
self.updateInstanceCookieValues()
self.writeOutPandaCookie()
else:
return Task.again
def logSubmit(setHostID, setMileStone):
if __dev__:
return
trackItem = UserFunnel()
trackItem.setmilestone(quote_plus(setMileStone))
trackItem.setHost(setHostID)
trackItem.prerun()
trackItem.run()
def getVRSFunnelURL():
a = UserFunnel()
a.getFunnelURL()
class HitBoxCookie:
def __init__(self):
self.ieCookieDir = os.getenv('USERPROFILE') + '\\Cookies'
self.pythonCookieFile = 'cf.txt'
self.hitboxCookieFile = None
self.ehgdigCookieFile = None
self.hitboxAcct = 'DM53030620EW'
self.ctg = None
self.wss_gw = None
self.dmAcct = None
self.pythonCookieHeader = ' # Netscape HTTP Cookie File\n # http://www.netscape.com/newsref/std/cookie_spec.html\n # This is a generated file! Do not edit.\n\n'
return
def returnIECookieDir(self):
return self.ieCookieDir
def findIECookieFiles(self):
try:
sdir = os.listdir(self.ieCookieDir)
except WindowsError:
print 'Dir does not exist, do nothing'
return
while sdir:
temp = sdir.pop()
if temp.find('@hitbox[') != -1:
self.hitboxCookieFile = temp
if temp.find('@ehg-dig.hitbox[') != -1:
self.ehgdigCookieFile = temp
if self.hitboxCookieFile != None and self.ehgdigCookieFile != None:
return 1
if self.hitboxCookieFile == None and self.ehgdigCookieFile == None:
return 0
else:
return -1
return
def openHitboxFile(self, filename, type = 'python'):
if type == 'ie':
fullfile = self.ieCookieDir + '\\' + filename
else:
fullfile = filename
cf = open(fullfile, 'r')
data = cf.read()
cf.close()
return data
def splitIECookie(self, filestream):
return filestream.split('*\n')
def sortIECookie(self, filestreamListElement):
return [filestreamListElement.split('\n')[2], filestreamListElement.split('\n')[0], filestreamListElement.split('\n')[1]]
def sortPythonCookie(self, filestreamListElement):
return [filestreamListElement.split('\t')[0], filestreamListElement.split('\t')[5], filestreamListElement.split('\t')[6]]
def writeIEHitBoxCookies(self):
if self.ctg == None or self.wss_gw == None or self.dmAcct == None:
return
if sys.platform != 'win32':
return
self.findIECookieFiles()
iecData = self.openHitboxFile(self.ehgdigCookieFile, 'ie')
iecData = iecData.split('*\n')
x = 0
while x < len(iecData):
if iecData[x].find(self.hitboxAcct) != -1:
iecData.pop(x)
print 'Removed it from the list'
break
x += 1
iecWrite = open(self.ieCookieDir + '\\' + self.ehgdigCookieFile, 'w')
while iecData:
iecBuffer = iecData.pop() + '*\n'
iecBuffer = iecBuffer.strip('/')
if iecBuffer[0] == '.':
iecBuffer = iecBuffer[1:]
iecWrite.write(iecBuffer)
tempDMBUFFER = self.dmAcct[0]
if tempDMBUFFER[0].find('.') == 0:
tempDMBUFFER = tempDMBUFFER[1:]
iecWrite.write(self.dmAcct[1] + '\n' + self.dmAcct[2] + '\n' + tempDMBUFFER + '/\n*\n')
iecWrite.close()
del iecData
del iecWrite
del iecBuffer
iecWrite = open(self.ieCookieDir + '\\' + self.hitboxCookieFile, 'w')
iecBuffer = self.ctg[0]
if iecBuffer[0] == '.':
iecBuffer = iecBuffer[1:]
if iecBuffer.find('/') == -1:
iecBuffer = iecBuffer + '/'
iecWrite.write(self.ctg[1] + '\n' + self.ctg[2] + '\n' + iecBuffer + '\n*\n')
iecWrite.write(self.wss_gw[1] + '\n' + self.wss_gw[2] + '\n' + iecBuffer + '\n*\n')
iecWrite.close()
return
def OLDwritePythonHitBoxCookies(self, filename = 'cf.txt'):
if self.ctg == None or self.wss_gw == None or self.dmAcct == None:
return
outputfile = open(filename, 'w')
outputfile.write(self.pythonCookieHeader)
outputfile.write('.' + self.dmAcct[0].strip('/') + '\tTRUE\t/\tFALSE\t9999999999\t' + self.dmAcct[1] + '\t' + self.dmAcct[2] + '\n')
outputfile.write('.' + self.ctg[0].strip('/') + '\tTRUE\t/\tFALSE\t9999999999\t' + self.ctg[1] + '\t' + self.ctg[2] + '\n')
outputfile.write('.' + self.wss_gw[0].strip('/') + '\tTRUE\t/\tFALSE\t9999999999\t' + self.wss_gw[1] + '\t' + self.wss_gw[2] + '\n')
outputfile.close()
return
def writePythonHitBoxCookies(self, filename = 'cf.txt'):
if self.ctg == None or self.wss_gw == None or self.dmAcct == None:
return
outputfile = open(filename, 'w')
outputfile.write('.' + self.dmAcct[0].strip('/') + '\t/\t' + self.dmAcct[1] + '\t' + self.dmAcct[2] + '\n')
outputfile.write('.' + self.ctg[0].strip('/') + '\t/\t' + self.ctg[1] + '\t' + self.ctg[2] + '\n')
outputfile.write('.' + self.wss_gw[0].strip('/') + '\t/\t' + self.wss_gw[1] + '\t' + self.wss_gw[2] + '\n')
outputfile.close()
return
def loadPythonHitBoxCookies(self):
if os.path.isfile(self.pythonCookieFile) != 1:
return
pythonStandard = self.openHitboxFile(self.pythonCookieFile, 'python')
pythonStandard = pythonStandard.split('\n\n').pop(1)
pythonStandard = pythonStandard.split('\n')
for x in pythonStandard:
if x.find('\t' + self.hitboxAcct) != -1:
self.dmAcct = self.sortPythonCookie(x)
if x.find('\tCTG\t') != -1:
self.ctg = self.sortPythonCookie(x)
if x.find('\tWSS_GW\t') != -1:
self.wss_gw = self.sortPythonCookie(x)
def loadIEHitBoxCookies(self):
if self.findIECookieFiles() != 1:
return
if sys.platform != 'win32':
return
hitboxStandard = self.openHitboxFile(self.hitboxCookieFile, 'ie')
hitboxDIG = self.openHitboxFile(self.ehgdigCookieFile, 'ie')
hitboxStandard = self.splitIECookie(hitboxStandard)
hitboxDIG = self.splitIECookie(hitboxDIG)
ctg = None
wss = None
for x in hitboxStandard:
if x.find('CTG\n') != -1:
ctg = x
if x.find('WSS_GW\n') != -1:
wss = x
if ctg == None or wss == None:
return
DM = None
for x in hitboxDIG:
if x.find(self.hitboxAcct) != -1:
DM = x
if DM == None:
return
self.ctg = self.sortIECookie(ctg)
self.wss_gw = self.sortIECookie(wss)
self.dm560804E8WD = self.sortIECookie(DM)
return
def convertHitBoxIEtoPython():
if sys.platform != 'win32':
print 'Cookie Converter: Warning: System is not MS-Windows. I have not been setup to work with other systems yet. Sorry ' + sys.platform + ' user. The game client will create a cookie.'
return
if __dev__:
return
a = HitBoxCookie()
a.loadIEHitBoxCookies()
a.writePythonHitBoxCookies()
del a
def convertHitBoxPythontoIE():
if sys.platform != 'win32':
print 'System is not MS-Windows. I have not been setup to work with other systems yet. Sorry ' + sys.platform + ' user.'
return
if os.path.isfile('cf.txt') == True:
return
a = HitBoxCookie()
a.loadPythonHitBoxCookies()
a.writeIEHitBoxCookies()
del a
def getreg(regVar):
if sys.platform != 'win32':
print "System is not MS-Windows. I haven't been setup yet to work with systems other than MS-Win using MS-Internet Explorer Cookies"
return ''
siteName = 'toontown.online.disney'
cookiedir = os.getenv('USERPROFILE') + '\\Cookies'
sdir = os.listdir(cookiedir)
wholeCookie = None
while sdir:
temp = sdir.pop()
if temp.find(siteName) != -1:
wholeCookie = temp
break
if wholeCookie == None:
print 'Cookie not found for site name: ' + siteName
return ''
CompleteCookiePath = cookiedir + '\\' + wholeCookie
cf = open(CompleteCookiePath, 'r')
data = cf.read()
cf.close()
del cf
data = data.replace('%3D', '=')
data = data.replace('%26', '&')
regNameStart = data.find(regVar)
if regNameStart == -1:
return ''
regVarStart = data.find('=', regNameStart + 1)
regVarEnd = data.find('&', regNameStart + 1)
return data[regVarStart + 1:regVarEnd]
def getMAC(staticMAC = [None]):
if staticMAC[0] == None:
if sys.platform == 'win32':
correctSection = 0
try:
ipconfdata = os.popen('/WINDOWS/SYSTEM32/ipconfig /all').readlines()
except:
staticMAC[0] = 'NO_MAC'
return staticMAC[0]
for line in ipconfdata:
if line.find('Local Area Connection') >= 0:
correctSection = 1
if line.find('Physical Address') >= 0 and correctSection == 1:
pa = line.split(':')[-1].strip()
correctSection = 0
staticMAC[0] = pa
return pa
if sys.platform == 'darwin':
macconfdata = os.popen('/usr/sbin/system_profiler SPNetworkDataType |/usr/bin/grep MAC').readlines()
result = '-1'
if macconfdata:
if macconfdata[0].find('MAC Address') != -1:
pa = macconfdata[0][macconfdata[0].find(':') + 2:macconfdata[0].find(':') + 22].strip('\n')
staticMAC[0] = pa.replace(':', '-')
result = staticMAC[0]
return result
if sys.platform != 'darwin' and sys.platform != 'win32':
print 'System is not running OSX or MS-Windows.'
return '-2'
else:
return staticMAC[0]
return
def firstRun(operation = 'read', newPlayer = None, newPlayerBool = [False]):
if operation != 'read':
if len(newPlayerBool) != 0:
newPlayerBool.pop()
newPlayerBool.append(newPlayer)
return newPlayerBool[0]
def patcherVer(operation = 'read', url = None, patchfile = []):
if operation != 'read':
if len(patchfile) != 0:
patchfile.pop()
patchfile.append(url)
return patchfile
def loggingAvID(operation = 'read', newId = None, localAvId = [None]):
if operation == 'write':
localAvId[0] = newId
else:
return localAvId[0]
def loggingSubID(operation = 'read', newId = None, localSubId = [None]):
if operation == 'write':
localSubId[0] = newId
else:
return localSubId[0]
def vconGroup(operation = 'read', group = None, staticStore = []):
if operation != 'read':
if len(staticStore) != 0:
staticStore.pop()
staticStore.append(group)
try:
return staticStore[0]
except IndexError:
return None
return None
def printUnreachableLen():
import gc
gc.set_debug(gc.DEBUG_SAVEALL)
gc.collect()
unreachableL = []
for it in gc.garbage:
unreachableL.append(it)
return len(str(unreachableL))
def printUnreachableNum():
import gc
gc.set_debug(gc.DEBUG_SAVEALL)
gc.collect()
return len(gc.garbage)
def reportMemoryLeaks():
if printUnreachableNum() == 0:
return
import bz2, gc
gc.set_debug(gc.DEBUG_SAVEALL)
gc.collect()
uncompressedReport = ''
for s in gc.garbage:
try:
uncompressedReport += str(s) + '&'
except TypeError:
pass
reportdata = bz2.compress(uncompressedReport, 9)
headers = {'Content-type': 'application/x-bzip2',
'Accept': 'text/plain'}
try:
baseURL = patcherVer()[0].split('/lo')[0]
except IndexError:
print 'Base URL not available for leak submit'
return
basePort = 80
if baseURL.count(':') == 2:
basePort = baseURL[-4:]
baseURL = baseURL[:-5]
baseURL = baseURL[7:]
if basePort != 80:
finalURL = 'http://' + baseURL + ':' + str(basePort) + '/logging/memory_leak.php?leakcount=' + str(printUnreachableNum())
else:
finalURL = 'http://' + baseURL + '/logging/memory_leak.php?leakcount=' + str(printUnreachableNum())
reporthttp = HTTPClient()
reporthttp.postForm(URLSpec(finalURL), reportdata)
def checkParamFile():
if os.path.exists('parameters.txt') == 1:
paramfile = open('parameters.txt', 'r')
contents = paramfile.read()
paramfile.close()
del paramfile
contents = contents.split('\n')
newURL = ''
while contents:
checkLine = contents.pop()
if checkLine.find('PATCHER_BASE_URL=') != -1 and checkLine[0] == 'P':
newURL = checkLine.split('=')[1]
newURL = newURL.replace(' ', '')
break
if newURL == '':
return
else:
return newURL + 'patcher.ver'
|
import bisect
from tests import test_chop
def chop(val, seq):
pos = bisect.bisect_left(seq, val)
return pos if len(seq) > pos and seq[pos] == val else -1
if __name__ == '__main__':
test_chop(chop)
|
"""
A basic calculator made with tkinter library,
inspired by @pildorasinformaticas and made by @Davichet-e
"""
import math
import cmath
import tkinter as tk
from typing import Callable, Iterator, List, Tuple, Union
class Calculator:
"""
Basic tkinter calculator
"""
def __init__(self, master=None) -> None:
self._frame: tk.Frame = tk.Frame(master=master)
self._frame.grid()
self._operation: str = ""
self._reset_screen: bool = False
self._result: Union[float, complex] = 0
self._number_stored: Union[float, complex] = 0
self._substract_counter: int = 0
self._multiply_counter: int = 0
self._division_counter: int = 0
self._modulo_counter: int = 0
self._buttons: List[tk.Button] = []
master.title("Calculator")
master.resizable(width=False, height=False)
self._number_screen = tk.StringVar()
self._operation_str_var = tk.StringVar()
self._screen = tk.Entry(
self._frame,
textvariable=self._number_screen,
state="readonly",
readonlybackground="black",
bd=20,
relief="flat",
fg="#9FEAF4",
)
self._screen2 = tk.Entry(
self._frame,
textvariable=self._operation_str_var,
state="readonly",
width=4,
readonlybackground="black",
bd=20,
relief="flat",
fg="#9FEAF4",
)
self._screen2.grid(row=0, column=0, sticky="e")
self._screen2.config(justify="left")
self._screen.grid(row=0, column=1, columnspan=5, sticky="we")
self._screen.config(justify="right")
self._number_screen.set("0")
self._config_buttons()
@property
def _number_on_screen(self) -> Union[float, complex]:
number: str = self._number_screen.get()
# I considered to use ast.literal_eval for safety reasons,
# but since I manage the input, for performance reasons,
# I prefer using the built-in eval function
return eval(number)
def _press_number(self, num: str) -> None:
number_on_screen: str = self._number_screen.get()
if (
number_on_screen == "0"
and num not in "0."
and not number_on_screen.count(".")
):
self._number_screen.set("")
self._operation_str_var.set("")
# Update the changes on the screen
number_on_screen = self._number_screen.get()
if self._reset_screen:
self._number_screen.set(num)
self._operation_str_var.set("")
self._reset_screen = False
else:
if (
num not in "0."
or (num == "0" and number_on_screen != "0")
or (num == "." and not number_on_screen.count("."))
):
self._number_screen.set(number_on_screen + num)
def _add_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
self._result = number + self._number_stored
self._operation_str_var.set("+")
self._operation = "+"
self._reset_screen = True
self._number_screen.set(self._result)
def _sign_func(self):
num: str = self._number_screen.get()
if "-" in num:
self._number_screen.set(num.strip("-"))
else:
self._number_screen.set("-" + num)
def _substract_func(self) -> None:
screen_display: str = self._number_screen.get()
if screen_display == "-":
return
number: Union[float, complex] = self._number_on_screen
self._operation_str_var.set("-")
if self._substract_counter == 0:
self._number_stored = number
else:
self._result -= number
self._number_screen.set(self._result)
self._substract_counter += 1
self._operation = "-"
self._reset_screen = True
def _factorial_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
self._operation_str_var.set("n!")
if isinstance(number, float):
# See https://es.wikipedia.org/wiki/Funci%C3%B3n_gamma
self._number_screen.set(math.gamma(number + 1))
elif isinstance(number, int):
self._number_screen.set(math.factorial(number))
else:
self._number_screen.set("USE ONLY REAL NUMBERS")
self._reset_screen = True
def _multiply_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
self._operation_str_var.set("x")
if not self._multiply_counter:
self._number_stored = number
else:
self._result = self._number_stored * number
self._number_screen.set(self._result)
self._multiply_counter += 1
self._operation = "*"
self._reset_screen = True
def _division_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
self._operation_str_var.set("➗")
if not self._division_counter:
self._number_stored = number
else:
if self._division_counter == 1:
self._result = self._number_stored / number
else:
self._result /= number
self._number_screen.set(self._result)
self._division_counter += 1
self._operation = "/"
self._reset_screen = True
def _modulo_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
if isinstance(number, complex):
self._number_screen.set("MOD OPERATOR NOT DEFINED FOR COMPLEX NUMBERS")
return
self._operation_str_var.set("%")
if not self._modulo_counter:
self._number_stored = number
else:
if self._modulo_counter == 1:
self._result = self._number_stored % number
else:
self._result %= number
self._number_screen.set(self._result)
self._modulo_counter += 1
self._operation = "%"
self._reset_screen = True
def _sqrt_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
self._operation_str_var.set("√n")
if isinstance(number, complex) or number < 0:
self._number_screen.set(cmath.sqrt(number))
else:
self._number_screen.set(math.sqrt(number))
self._reset_screen = True
def _inverse_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
self._operation_str_var.set("1/x")
self._number_screen.set(1 / number)
self._reset_screen = True
def _square_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
self._operation_str_var.set("x^2")
self._number_screen.set(number ** 2)
self._reset_screen = True
def _logarithmic_func(self) -> None:
number: Union[float, complex] = self._number_on_screen
self._operation_str_var.set("ln(x)")
if isinstance(number, complex):
self._number_screen.set(cmath.log(number))
else:
if number > 0:
self._number_screen.set(math.log(number))
else:
self._number_screen.set("USE ONLY POSITIVE NUMBERS")
self._reset_screen = True
def _trigonometric_func(self, function: str) -> None:
self._operation_str_var.set("trig func")
number: Union[float, complex] = self._number_on_screen
# Depending on if it's a complex number, use the appropriate library
if isinstance(number, complex):
self._number_screen.set(getattr(cmath, function)(number))
else:
self._number_screen.set(getattr(math, function)(number))
self._reset_screen = True
##############################################
def _constants(self, constant: float) -> None:
self._number_screen.set(constant)
self._reset_screen = True
##############################################
def _results(self) -> None:
number: Union[float, complex] = self._number_on_screen
operation_done: str = self._operation
res: Union[float, complex] = number
if operation_done == "+":
res = self._result + number
self._result = 0
elif operation_done == "-":
res = self._number_stored - number
self._substract_counter = 0
elif operation_done == "*":
res = self._number_stored * number
self._multiply_counter = 0
elif operation_done == "/":
res = self._number_stored / number
self._division_counter = 0
elif operation_done == "%":
res = self._number_stored % number
self._modulo_counter = 0
self._number_screen.set(res)
self._number_stored = 0
self._operation = ""
def _reset(self) -> None:
self._result = 0
self._number_stored = 0
self._substract_counter = 0
self._multiply_counter = 0
self._division_counter = 0
self._modulo_counter = 0
self._number_screen.set("0")
self._operation_str_var.set("")
def _config_buttons(self) -> None:
functions_with_it_symbol: List[Tuple[Callable[..., None], str]] = [
(self._constants, "π"),
(self._reset, "AC"),
(self._sqrt_func, "√n"),
(self._factorial_func, "n!"),
(self._modulo_func, "%"),
(self._constants, "e"),
(self._press_number, "7"),
(self._press_number, "8"),
(self._press_number, "9"),
(self._division_func, "➗"),
(lambda: self._trigonometric_func("cos"), "cos(x)"),
(self._inverse_func, "1/x"),
(self._press_number, "4"),
(self._press_number, "5"),
(self._press_number, "6"),
(self._multiply_func, "✖"),
(lambda: self._trigonometric_func("sin"), "sin(x)"),
(self._sign_func, "±"),
(self._press_number, "1"),
(self._press_number, "2"),
(self._press_number, "3"),
(self._substract_func, "➖"),
(lambda: self._trigonometric_func("tan"), "tan(x)"),
(self._logarithmic_func, "ln(x)"),
(self._press_number, "0"),
(self._press_number, "."),
(self._results, "="),
(self._add_func, "➕"),
(self._square_func, "x^2"),
]
constants: Iterator[float] = iter((math.pi, math.e))
columns: Iterator[int] = iter(
[0, 1, 3, 4, 5] + [number for _ in range(4) for number in range(6)]
)
rows: Iterator[int] = iter(
[1, 1, 1, 1, 1] + [number for number in range(2, 6) for _ in range(6)]
)
button_indexes: Iterator[int] = iter(range(29))
for function, symbol in functions_with_it_symbol:
if function == self._press_number:
self._buttons.append(
tk.Button(
self._frame,
text=symbol,
bg="#81BEF7",
command=lambda symbol=symbol: self._press_number(symbol),
)
)
elif function == self._constants:
self._buttons.append(
tk.Button(
self._frame,
text=symbol,
command=lambda constant=next(constants): self._constants(
constant
),
bg="#8A0808",
fg="white",
)
)
elif function == self._reset:
self._buttons.append(
tk.Button(
self._frame,
text=symbol,
command=self._reset,
bg="#252440",
fg="white",
)
)
self._buttons[-1].grid(row=1, column=1, columnspan=2, ipadx=53)
self._buttons[-1].config(height=4)
else:
self._buttons.append(
tk.Button(
self._frame,
text=symbol,
bg="#585858",
fg="white",
command=function,
)
)
index_of_button: int = next(button_indexes)
row: int = next(rows)
column: int = next(columns)
if function != self._reset:
self._buttons[index_of_button].config(height=4, width=8)
self._buttons[index_of_button].grid(row=row, column=column)
if __name__ == "__main__":
WINDOW = tk.Tk()
CALCULATOR = Calculator(WINDOW)
WINDOW.mainloop()
|
import re
import socket
class FilterModule(object):
def filters(self):
return {
'kube_lookup_hostname': self.kube_lookup_hostname,
}
def kube_lookup_hostname(self, ip, hostname, many=False):
ips = set()
ip = ip.split(':')[0]
if ip and ip != "":
if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip):
ips.add(ip)
try:
(_, _, iplist) = socket.gethostbyname_ex(hostname)
ips |= set(iplist)
except socket.error as e:
pass
if many:
ips.add(hostname)
return sorted(list(ips))
else:
return sorted(list(ips))[0]
|
import torch
def giou_loss(pred_bboxes, target_bboxes, reduction="elementwise_mean"):
pass
|
from typing import List
from collections import Counter
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# Test for empty array
if not strs:
return ""
for currString in range(len(strs)):
if strs[currString] == "":
return ""
# Create dictionary and get the smallest element
setDict = {}
for currString in range(len(strs)):
setDict[strs[currString]] = len(strs[currString])
c = Counter(setDict)
smallestString = c.most_common()[len(strs)-1][0]
if len(strs) == 1:
print (smallestString)
# Test each subscript. update tmpstr if true and all counts equal on subscripts
tmpStr = []
isFound = False
for x in range(len(smallestString)-1):
for lstArray in range(len(strs)):
if strs[lstArray][x] != smallestString[x]:
isFound = False
break
else:
isFound = True
if isFound:
tmpStr.append(strs[lstArray][x])
isFound = False
count = 0
# convert to string and print
print(''.join(tmpStr))
if __name__ == '__main__':
newSoln = Solution()
#inpArray = ["flower", "flow", "flight"]
#inpArray = ["dog","racecar","car"]
#inpArray = ["a"]
#inpArray = ["",""]
#inpArray = ["a","b"]
inpArray = ["c","c"]
#inpArray = []
newSoln.longestCommonPrefix(inpArray)
|
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#!/usr/bin/env python3
# pyre-strict
from pytorch_lightning.callbacks import ModelCheckpoint
from torchrecipes.core.base_train_app import BaseTrainApp
from torchrecipes.core.conf import TrainerConf
from torchrecipes.core.test_utils.test_base import BaseTrainAppTestCase
class TestTrainApp(BaseTrainAppTestCase):
def test_ckpt_callback_fallback_to_default(self) -> None:
app = BaseTrainApp(None, TrainerConf(), None)
app._set_trainer_params(trainer_params={})
self.assertIsNotNone(app._checkpoint_callback)
self.assertIsNone(app._checkpoint_callback.monitor)
def test_ckpt_callback_user_provided(self) -> None:
app = BaseTrainApp(None, TrainerConf(), None)
self.mock_callable(app, "get_callbacks").to_return_value(
[ModelCheckpoint(monitor="some_metrics")]
)
app._set_trainer_params(trainer_params={})
self.assertIsNotNone(app._checkpoint_callback)
self.assertEqual(app._checkpoint_callback.monitor, "some_metrics")
|
"""
Given a sorted array and a target value,
return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
"""
# taking the input from the user
x = list(map(int, input("Enter the elements in the list: ").strip().split()))
target = int(input("Enter the Element whose index has to be found: "))
# finding whether the target value is in the list or not
if target in x:
a = x.index(target)
print(
"The number is present at the index {}.".format(a)
) # if target is present then printing the index
else:
x.append(target) # adding the target in the list
x.sort() # sorting the list
a = x.index(target)
print(
"Number not found. It can be inserted at index {}.".format(a)
) # printing the target index
|
# coding: utf-8
"""Tests to Access"""
import json
from django.test import TestCase, Client
from django.urls import reverse
from core.access.factories import UserFactory
class LoginViewTest(TestCase):
def setUp(self):
self.client = Client()
UserFactory(username='admin')
def test_get(self):
response = self.client.get(reverse('login'))
self.assertEqual(response.status_code, 200)
def test_post(self):
response = self.client.post(reverse('login'), {
'username': 'admin',
'password': 'password'
})
self.assertEqual(302, response.status_code)
self.assertEqual(response.url, '/property/')
def test_post_failure(self):
response = self.client.post(reverse('login'), {
'username': 'foo',
'password': 'bar'
})
self.assertEqual(response.status_code, 200)
class LogoutViewTest(TestCase):
def setUp(self):
self.client = Client()
def test_get(self):
response = self.client.get(reverse('logout'))
self.assertEqual(302, response.status_code)
self.assertEqual(response.url, '/property/available/')
|
"""bareasgi_session"""
from .helpers import add_session_middleware, session_data
from .storage import SessionStorage, MemorySessionStorage
__all__ = [
"add_session_middleware",
"session_data",
"SessionStorage",
"MemorySessionStorage"
]
|
from .meta import *
from .attribute_adapter import *
|
import torch
import torch.nn as nn
# import torch.nn.functional as f
import torch.optim as optim
import numpy as np
import time
import os
from models.rnn_mlp import RNN_MLP
from models.social_attention import SocialAttention
from models.spatial_attention import SpatialAttention
from models.s2s_social_attention import S2sSocialAtt
from models.s2s_spatial_attention import S2sSpatialAtt
from models.cnn_mlp import CNN_MLP
import random
from classes.training_class import NetTraining
import helpers.helpers_training as helpers
import sys
import json
def main():
# set pytorch manual seed
torch.manual_seed(10)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("using gpu: ",torch.cuda.is_available())
#loading parameters
parameters_path = "./src/parameters/project.json"
parameters_project = json.load(open(parameters_path))
data_processed_parameters = json.load(open(parameters_project["data_processed_parameters"]))
training_parameters = json.load(open(parameters_project["training_parameters"]))
models_parameters = json.load(open(parameters_project["models_parameters"]))
processed_parameters = json.load(open(parameters_project["data_processed_parameters"]))
raw_parameters = json.load(open(parameters_project["data_raw_parameters"]))
# loading training data
data_file = parameters_project["training_hdf5"]
# scene lists for train, eval and test
eval_scenes = data_processed_parameters["eval_scenes"]
train_eval_scenes = data_processed_parameters["train_scenes"]
test_scenes = data_processed_parameters["test_scenes"]
train_scenes = [scene for scene in train_eval_scenes if scene not in eval_scenes]
scenes = [train_eval_scenes,train_scenes,test_scenes,eval_scenes]
# loading models hyperparameters
model_name = training_parameters["model"]
net_params = json.load(open(models_parameters[model_name]))
net_type = None
args_net = {}
# set network arguments depending on its type
if model_name == "rnn_mlp":
args_net = {
"device" : device,
"batch_size" : training_parameters["batch_size"],
"input_dim" : net_params["input_dim"],
"hidden_size" : net_params["hidden_size"],
"recurrent_layer" : net_params["recurrent_layer"],
"mlp_layers" : net_params["mlp_layers"],
"output_size" : net_params["output_size"],
"t_pred":processed_parameters["t_pred"],
"t_obs":processed_parameters["t_obs"],
"use_images":net_params["use_images"],
"use_neighbors":net_params["use_neighbors"],
"offsets":training_parameters["offsets"],
"offsets_input" : training_parameters["offsets_input"],
"model_name":model_name
}
net_type = RNN_MLP
elif model_name == "cnn_mlp":
args_net = {
"device" : device,
"batch_size" : training_parameters["batch_size"],
"input_length" : processed_parameters["t_obs"],
"output_length" : processed_parameters["t_pred"],
"num_inputs" : net_params["input_dim"],
"mlp_layers" : net_params["mlp_layers"],
"output_size" : net_params["output_size"],
"input_dim" : net_params["input_dim"],
"kernel_size": net_params["kernel_size"],
"nb_conv": net_params["nb_conv"],
"nb_kernel": net_params["nb_kernel"],
"cnn_feat_size": net_params["cnn_feat_size"],
"use_images":net_params["use_images"],
"use_neighbors":net_params["use_neighbors"],
"offsets":training_parameters["offsets"],
"offsets_input" : training_parameters["offsets_input"],
"model_name":model_name
}
net_type = CNN_MLP
elif model_name == "social_attention":
args_net = {
"device" : device,
"input_dim" : net_params["input_dim"],
"input_length" : processed_parameters["t_obs"],
"output_length" : processed_parameters["t_pred"],
"dmodel" : net_params["dmodel"],
"predictor_layers" : net_params["predictor_layers"],
"pred_dim" : processed_parameters["t_pred"] * net_params["input_dim"] ,
"nb_conv": net_params["nb_conv"],
"nb_kernel": net_params["nb_kernel"],
"cnn_feat_size": net_params["cnn_feat_size"],
"kernel_size" : net_params["kernel_size"],
# "dropout_tfr" : net_params["dropout_tfr"],
"projection_layers":net_params["projection_layers"],
"use_images":net_params["use_images"],
"use_neighbors":net_params["use_neighbors"],
"offsets":training_parameters["offsets"],
"offsets_input" : training_parameters["offsets_input"],
"model_name":model_name,
"use_mha": net_params["use_mha"],
"h": net_params["h"],
"mha_dropout": net_params["mha_dropout"],
"joint_optimisation": training_parameters["joint_optimisation"],
"tfr_feed_forward_dim": net_params["tfr_feed_forward_dim"],
"tfr_num_layers": net_params["tfr_num_layers"],
"condition_on_trajectory": net_params["condition_on_trajectory"]
}
net_type = SocialAttention
elif model_name == "spatial_attention":
args_net = {
"device" : device,
"input_dim" : net_params["input_dim"],
"input_length" : processed_parameters["t_obs"],
"output_length" : processed_parameters["t_pred"],
"pred_dim" : processed_parameters["t_pred"] * net_params["input_dim"] ,
"dmodel" : net_params["dmodel"],
"predictor_layers" : net_params["predictor_layers"],
"nb_conv": net_params["nb_conv"],
"nb_kernel": net_params["nb_kernel"],
"cnn_feat_size": net_params["cnn_feat_size"],
"kernel_size" : net_params["kernel_size"],
"projection_layers":net_params["projection_layers"],
"spatial_projection":net_params["spatial_projection"],
"model_name":model_name,
"use_images":net_params["use_images"],
"use_neighbors":net_params["use_neighbors"],
"offsets":training_parameters["offsets"],
"offsets_input" : training_parameters["offsets_input"],
"use_mha": net_params["use_mha"],
"h": net_params["h"],
"mha_dropout": net_params["mha_dropout"],
"joint_optimisation": training_parameters["joint_optimisation"],
"froze_cnn": net_params["froze_cnn"],
"tfr_feed_forward_dim": net_params["tfr_feed_forward_dim"],
"tfr_num_layers": net_params["tfr_num_layers"],
"condition_on_trajectory": net_params["condition_on_trajectory"]
}
net_type = SpatialAttention
elif model_name == "s2s_social_attention":
args_net = {
"device" : device,
"input_dim" : net_params["input_dim"],
"input_length" : processed_parameters["t_obs"],
"pred_length" : processed_parameters["t_pred"],
"pred_dim" : processed_parameters["t_pred"] * net_params["input_dim"] ,
"enc_hidden_size" : net_params["enc_hidden_size"],
"enc_num_layers" : net_params["enc_num_layers"],
"dec_hidden_size" : net_params["dec_hidden_size"],
"dec_num_layer" : net_params["dec_num_layer"],
"embedding_size" : net_params["embedding_size"],
"output_size" : net_params["output_size"],
"projection_layers" : net_params["projection_layers"],
"enc_feat_embedding" : net_params["enc_feat_embedding"],
"condition_decoder_on_outputs" : net_params["condition_decoder_on_outputs"],
"model_name":model_name,
"use_images":net_params["use_images"],
"use_neighbors":net_params["use_neighbors"],
"offsets":training_parameters["offsets"],
"offsets_input" : training_parameters["offsets_input"],
"joint_optimisation": training_parameters["joint_optimisation"]
}
net_type = S2sSocialAtt
elif model_name == "s2s_spatial_attention":
args_net = {
"device" : device,
"input_dim" : net_params["input_dim"],
"input_length" : processed_parameters["t_obs"],
"pred_length" : processed_parameters["t_pred"],
"pred_dim" : processed_parameters["t_pred"] * net_params["input_dim"] ,
"enc_hidden_size" : net_params["enc_hidden_size"],
"enc_num_layers" : net_params["enc_num_layers"],
"dec_hidden_size" : net_params["dec_hidden_size"],
"dec_num_layer" : net_params["dec_num_layer"],
"embedding_size" : net_params["embedding_size"],
"output_size" : net_params["output_size"],
"projection_layers" : net_params["projection_layers"],
"att_feat_embedding" : net_params["att_feat_embedding"],
"spatial_projection" : net_params["spatial_projection"],
"condition_decoder_on_outputs" : net_params["condition_decoder_on_outputs"],
"model_name":model_name,
"use_images":net_params["use_images"],
"use_neighbors":net_params["use_neighbors"],
"offsets":training_parameters["offsets"],
"offsets_input" : training_parameters["offsets_input"],
"froze_cnn": net_params["froze_cnn"]
}
net_type = S2sSpatialAtt
# init neural network
net = net_type(args_net)
train_loader,eval_loader,_,_ = helpers.load_data_loaders(parameters_project, raw_parameters, processed_parameters,training_parameters,args_net,data_file,scenes)
net = net.to(device)
optimizer = optim.Adam(net.parameters(),lr = training_parameters["lr"],weight_decay=training_parameters["weight_decay"])
criterion = helpers.MaskedLoss(nn.MSELoss(reduction="none"))
args_training = {
"n_epochs" : training_parameters["n_epochs"],
"batch_size" : training_parameters["batch_size"],
"device" : device,
"train_loader" : train_loader,
"eval_loader" : eval_loader,
"criterion" : criterion,
"optimizer" : optimizer,
"use_neighbors" : net_params["use_neighbors"],
"plot" : training_parameters["plot"],
"load_path" : training_parameters["load_path"],
"plot_every" : training_parameters["plot_every"],
"save_every" : training_parameters["save_every"],
"offsets" : training_parameters["offsets"],
"offsets_input" : training_parameters["offsets_input"],
"net" : net,
"print_every" : training_parameters["print_every"],
"nb_grad_plots" : training_parameters["nb_grad_plots"],
"train" : training_parameters["train"],
"gradients_reports": parameters_project["gradients_reports"],
"losses_reports": parameters_project["losses_reports"],
"models_reports": parameters_project["models_reports"],
"joint_optimisation": training_parameters["joint_optimisation"]
}
# starting training
trainer = NetTraining(args_training)
trainer.training_loop()
if __name__ == "__main__":
main()
|
import numpy as np
import gammapy.modeling as modeling
import emcee
from gammapy.modeling.sampling import (
par_to_model,
uniform_prior,
)
import scipy.stats as stats
from ecpli.ECPLiBase import ECPLiBase, LimitTarget
class _EnsembleMCMCBase(ECPLiBase):
"""Base class for all affine invariant ensemble MCMC methods.
Attributes:
dataset: Gammapy dataset from which the model parameter constraint
is to be derived.
burn_in: Number of samples to be burned.
walker_factor: The number of walkers is this factor times the number
of free parameters.
n_threads: Number of CPU threads used for sampling.
n_samples: Number of samples to be drawn.
"""
def __init__(self,
limit_target: LimitTarget,
data: modeling.Dataset,
models: modeling.models.Models,
CL: float,
n_samples: int,
n_burn: int):
"""Args:
limit_target: Instance of LimitTarget to specify parameter and
model to be constrained.
data: Gammapy dataset from which the model parameter constraint
is to be derived.
models: Models which are to be fit to the data.
CL: Confidence level (e.g. 0.95) for the limit.
n_samples: Number of samples to draw.
n_burn: Number of burn in samples.
"""
super().__init__(limit_target, data, models, CL)
self.dataset = data.copy()
self.dataset.models = models
self.burn_in = n_burn
self.walker_factor = 20
self.n_threads = 1
self.n_samples = n_samples
if self.limit_target.parameter_name != "lambda_":
info = "Currently only supporting limits on lambda_"
raise RuntimeError(info)
@property
def _lambda_index(self) -> int:
"""Returns the index of the target parameter in the
self.dataset.models.parameters.free_parameters list.
"""
index_counter = 0
target_index = None
for mod in self.dataset.models:
for parameter in mod.parameters.free_parameters:
if parameter.name == self.limit_target.parameter_name:
if mod.name == self.limit_target.model.name:
target_index = index_counter
index_counter += 1
if target_index is None:
info = "Model " + self.target_model_name + " not found"
raise RuntimeError(info)
return target_index
def _lambda_chain(self) -> np.ndarray:
"""Returns the list of samples of the target parameter.
"""
burn_in = self.burn_in
chain = self.sampler.chain
sampler = np.zeros_like(chain)
"""
chain.shape[0]: Number of walkers
chain.shape[1]: Number of samples
chain.shape[2]: Number of free parameters
"""
free_parameter_list = self.dataset.models.parameters.free_parameters
n_walkers = chain.shape[0]
n_samples = chain.shape[1]
for i_walker in range(n_walkers):
for i_sample in range(n_samples):
pars = chain[i_walker, i_sample, :]
par_to_model(self.dataset, pars)
par_values = [p.value for p in free_parameter_list]
sampler[i_walker, i_sample, :] = par_values
target_index = self._lambda_index
samples_after_burn = sampler[:, burn_in:, target_index]
result = samples_after_burn.flatten()
negative_lambda = result[result < 0]
if len(negative_lambda) > 0:
info = "Have " + str(len(negative_lambda))
info += " negative lambda samples"
info += ": " + str(negative_lambda)
self._logger.debug(info)
else:
info = "All " + str(len(result)) + " samples are positive"
self._logger.debug(info)
return result
def _initial_samples(self) -> np.ndarray:
"""Runs the Markov chain initially for self.n_samples.
"""
dataset = self.dataset
self._logger.debug("Dataset before initial fit: ")
self._logger.debug(dataset)
self._logger.debug("Free parameters:")
for par in dataset.models.parameters.free_parameters:
info = par.name + ": value: " + str(par.value)
info += ", min: " + str(par.min) + ", max: " + str(par.max)
self._logger.debug(info)
self._logger.debug("---------------------------------------------")
fit_mcmc = modeling.Fit([dataset])
_ = fit_mcmc.run()
self._logger.debug("Dataset after initial fit:")
self._logger.debug(dataset)
self._logger.debug("Free parameters:")
for par in dataset.models.parameters.free_parameters:
info = par.name + ": value: " + str(par.value)
info += ", min: " + str(par.min) + ", max: " + str(par.max)
self._logger.debug(info)
self._logger.debug("---------------------------------------------")
nwalk = self.walker_factor
nwalk *= len(dataset.models.parameters.free_parameters)
walker_positions = self._sample(n_walkers=nwalk,
n_samples=self.n_samples)
return walker_positions
def autocorrelation(self) -> float:
"""Estimates the autocorrelation time of the Markov chain.
"""
tau = None
walker_positions = self._initial_samples()
finish = False
n_trials = 0
n_trials_max = 100
while not finish:
if n_trials > 0:
n_samples = self.sampler.chain.shape[1]
print("Getting " + str(n_samples) + " more samples")
walker_positions = self._continue_sampling(walker_positions,
n_samples)
try:
with np.errstate(all="ignore"):
tau = self.sampler.get_autocorr_time()
info = "Estimated autocorrelation time: " + str(tau)
print(info)
finish = True
except Exception as e:
info = "Couldn't estimate autocorrelation time: "
info += str(e)
self._logger.debug(info)
n_trials += 1
info = "Tried " + str(n_trials) + " times. Will retry ..."
self._logger.debug(info)
if n_trials > n_trials_max:
break
continue
return tau
@property
def ul(self) -> float:
"""Returns the upper limit on the LimitTarget.
"""
info = "Burn in: " + str(self.burn_in)
self._logger.debug(info)
info = "Walker factor: " + str(self.walker_factor)
self._logger.debug(info)
info = "Number of samples/nrun: " + str(self.n_samples)
self._logger.debug(info)
_ = self._initial_samples()
samp_lambda = self._lambda_chain()
lambda_ul = np.quantile(samp_lambda, self.CL)
info = "Mean acceptance fraction over all walkers: "
info += str(np.mean(self.sampler.acceptance_fraction))
self._logger.debug(info)
return lambda_ul
def ul_precision(self, n_chains: int = 10):
"""Estimate the precision of the limit given the configuration,
e.g. with regards to the number of samples.
The precision is estimated as standard deviation between
the limit derived in different and fully independent
Markov chains with equal configuration.
"""
ul_list = []
for i in range(n_chains):
info = "Calculating limit " + str(i+1)
info += "/" + str(n_chains)
self._logger.debug(info)
method_name = globals()[type(self).__name__]
method = method_name(self.dataset,
self.limit_target.model,
self.limit_target.parameter_name,
n_samples=self.n_samples,
n_burn=self.burn_in)
ul_list.append(method.ul)
std = np.std(ul_list, ddof=1)
relative_std = std / np.mean(ul_list) * 100.
return std, relative_std, ul_list
def _prior(self):
return NotImplementedError
def _lnposterior(self, pars: np.ndarray, dataset: modeling.Dataset):
free_pars = dataset.models.parameters.free_parameters
for factor, par in zip(pars, free_pars):
par.factor = factor
prior = self._prior()
log_likelihood = -0.5 * dataset.stat_sum()
"""
note the difference to the gammapy implementation (factor 0.5)!
"""
return log_likelihood + prior
def _walker_init(self, n_walkers: int):
"""
Initialize walkers as ball around current values.
"""
parameter_variance = []
parameter = []
spread = 0.5 / 100.
spread_pos = 0.1 # in degrees
for par in self.dataset.parameters.free_parameters:
parameter.append(par.factor)
if par.name in ["lon_0", "lat_0"]:
parameter_variance.append(spread_pos / par.scale)
else:
parameter_variance.append(spread * par.factor)
"""
Produce a ball of inital walkers around the inital values p0
"""
p0 = emcee.utils.sample_ball(parameter, parameter_variance, n_walkers)
ndim = len(parameter)
return ndim, p0
def _sample(self, n_walkers: int, n_samples: int) -> np.ndarray:
"""Draws n_samples from the markov chain.
"""
self.dataset.parameters.autoscale()
ndim, p0 = self._walker_init(n_walkers)
sampler = emcee.EnsembleSampler(n_walkers, ndim, self._lnposterior,
args=[self.dataset],
threads=self.n_threads)
info = "Starting MCMC sampling: "
info += "# walkers=" + str(n_walkers)
info += ", # samples=" + str(n_samples)
self._logger.debug(info)
for idx, result in enumerate(sampler.sample(p0, iterations=n_samples)):
if idx % (n_samples / 10) == 0:
info = "Sampled " + str(round(idx/n_samples * 100)) + " %"
self._logger.debug(info)
walker_positions = result[0]
self._logger.debug("Sampling complete")
self.sampler = sampler
return walker_positions
def _continue_sampling(self,
walker_positions: np.ndarray,
n_samples: int) -> np.ndarray:
"""Continues sampling for another n_samples.
"""
info = "Continuing to get " + str(n_samples) + " samples"
self._logger.debug(info)
for idx, result in enumerate(self.sampler.sample(walker_positions,
iterations=n_samples)
):
if idx % (n_samples / 10) == 0:
info = "Sampled " + str(round(idx / n_samples * 100)) + " %"
self._logger.debug(info)
walker_positions = result[0]
self._logger.debug("Sampling complete")
return walker_positions
def trace(self, burn: bool):
def _tracedata():
tracedata_list = []
target_index_list = []
i = 0
for mod in self.dataset.models:
for parameter in mod.parameters.free_parameters:
_tracedata = {"model_name": mod.name,
"parameter_name": parameter.name,
"burn": self.burn_in}
target_index_list.append(i)
tracedata_list.append(_tracedata)
i += 1
chain = self.sampler.chain
sampler = np.zeros_like(chain)
models = self.dataset.models
free_parameter_list = models.parameters.free_parameters
n_walkers = chain.shape[0]
n_samples = chain.shape[1]
for i_walker in range(n_walkers):
for i_sample in range(n_samples):
pars = chain[i_walker, i_sample, :]
par_to_model(self.dataset, pars)
par_values = [p.value for p in free_parameter_list]
sampler[i_walker, i_sample, :] = par_values
for target_index in target_index_list:
samples_before_burn = sampler[:, :, target_index]
tracedata_list[target_index][
"trace_unburned"] = samples_before_burn
return tracedata_list
_trace_list = []
for tracedata in _tracedata():
trace = tracedata["trace_unburned"].transpose()
"""
After transpose: Now trace is an array of dimension
(n_walkers, n_runs),
so each row has the data for all walker positions in a sampler step
"""
trace = trace.flatten()
"""
After flattening: Now trace is of the form
(walker1_step1, walker2_step1, ...,
walker1_step2, walker2_step2, ...)
-> Need to burn the first burn_in * n_walker entries
"""
if burn:
trace = trace[self.burn_in * self.n_walker:]
_trace_list.append(trace)
return _trace_list
class UniformPriorEnsembleMCMC(_EnsembleMCMCBase):
"""Ensemble MCMC with uniform priors.
"""
def __init__(self,
limit_target: LimitTarget,
data: modeling.Dataset,
models: modeling.models.Models,
CL: float,
n_samples: int,
n_burn: int):
super().__init__(limit_target, data, models, CL,
n_samples, n_burn)
for par in self.dataset.parameters.free_parameters:
if par.name == self.limit_target.parameter_name:
par.min = self.limit_target.parmin
par.max = self.limit_target.parmax
elif par.name == "index":
par.min = 1.
par.max = 4.
elif par.name == "amplitude":
par.max = 1.e-7
par.min = 1.e-16
else:
print("Freezing " + par.name)
par.frozen = True
def _prior(self):
logprob = 0.
for par in self.dataset.models.parameters.free_parameters:
logprob += uniform_prior(par.value, par.min, par.max)
return logprob
class WeakPriorEnsembleMCMC(_EnsembleMCMCBase):
"""Ensemble MCMC with gamma distributed priors.
"""
def __init__(self,
limit_target: LimitTarget,
data: modeling.Dataset,
models: modeling.models.Models,
CL: float,
n_samples: int,
n_burn: int):
super().__init__(limit_target, data, models, CL,
n_samples, n_burn)
# Fixing only for the ML fit
for par in self.dataset.parameters.free_parameters:
if par.name == self.limit_target.parameter_name:
par.min = self.limit_target.parmin
par.max = self.limit_target.parmax
elif par.name == "index":
par.min = 1.
par.max = 4.
elif par.name == "amplitude":
par.max = 1.e-7
par.min = 1.e-16
else:
print("Freezing " + par.name)
par.frozen = True
def _prior(self):
logprob = 0
for par in self.dataset.models.parameters.free_parameters:
if par.name == "lambda_":
shape = 1.1
mean = 1. / 5.
scale = mean / shape
prior = stats.gamma
prior_value = prior.pdf(x=par.value, a=shape, scale=scale)
elif par.name == "index":
shape = 7
mean = 2.5
scale = mean / shape
prior = stats.gamma
prior_value = prior.pdf(x=par.value, a=shape, scale=scale)
elif par.name == "amplitude":
shape = 1.3
mean = 5.e-11
shape = mean / shape
prior = stats.gamma
prior_value = prior.pdf(x=par.value, a=shape, scale=scale)
else:
raise RuntimeError("Unknown parameter " + str(par.value))
if prior_value <= 0.:
log_prior = -np.inf
else:
log_prior = np.log(prior_value)
logprob += log_prior
return logprob
|
import abc
from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Type, Union
from qrcode.image.styles.moduledrawers.base import QRModuleDrawer
if TYPE_CHECKING:
from qrcode.main import ActiveWithNeighbors, QRCode
DrawerAliases = Dict[str, Tuple[Type[QRModuleDrawer], Dict[str, Any]]]
class BaseImage:
"""
Base QRCode image output class.
"""
kind: Optional[str] = None
allowed_kinds: Optional[Tuple[str]] = None
needs_context = False
needs_processing = False
def __init__(self, border, width, box_size, *args, **kwargs):
self.border = border
self.width = width
self.box_size = box_size
self.pixel_size = (self.width + self.border * 2) * self.box_size
self._img = self.new_image(**kwargs)
self.init_new_image()
@abc.abstractmethod
def drawrect(self, row, col):
"""
Draw a single rectangle of the QR code.
"""
def drawrect_context(self, row: int, col: int, qr: "QRCode"):
"""
Draw a single rectangle of the QR code given the surrounding context
"""
raise NotImplementedError("BaseImage.drawrect_context") # pragma: no cover
def process(self):
"""
Processes QR code after completion
"""
raise NotImplementedError("BaseImage.drawimage") # pragma: no cover
@abc.abstractmethod
def save(self, stream, kind=None):
"""
Save the image file.
"""
def pixel_box(self, row, col):
"""
A helper method for pixel-based image generators that specifies the
four pixel coordinates for a single rect.
"""
x = (col + self.border) * self.box_size
y = (row + self.border) * self.box_size
return (
(x, y),
(x + self.box_size - 1, y + self.box_size - 1),
)
@abc.abstractmethod
def new_image(self, **kwargs) -> Any:
"""
Build the image class. Subclasses should return the class created.
"""
def init_new_image(self):
pass
def get_image(self, **kwargs):
"""
Return the image class for further processing.
"""
return self._img
def check_kind(self, kind, transform=None):
"""
Get the image type.
"""
if kind is None:
kind = self.kind
allowed = not self.allowed_kinds or kind in self.allowed_kinds
if transform:
kind = transform(kind)
if not allowed:
allowed = kind in self.allowed_kinds
if not allowed:
raise ValueError(f"Cannot set {type(self).__name__} type to {kind}")
return kind
def is_eye(self, row: int, col: int):
"""
Find whether the referenced module is in an eye.
"""
return (
(row < 7 and col < 7)
or (row < 7 and self.width - col < 8)
or (self.width - row < 8 and col < 7)
)
class BaseImageWithDrawer(BaseImage):
default_drawer_class: Type[QRModuleDrawer]
drawer_aliases: DrawerAliases = {}
def get_default_module_drawer(self) -> QRModuleDrawer:
return self.default_drawer_class()
def get_default_eye_drawer(self) -> QRModuleDrawer:
return self.default_drawer_class()
needs_context = True
module_drawer: "QRModuleDrawer"
eye_drawer: "QRModuleDrawer"
def __init__(
self,
*args,
module_drawer: Union[QRModuleDrawer, str] = None,
eye_drawer: Union[QRModuleDrawer, str] = None,
**kwargs,
):
self.module_drawer = self.get_drawer(module_drawer) or self.get_default_module_drawer()
# The eye drawer can be overridden by another module drawer as well,
# but you have to be more careful with these in order to make the QR
# code still parseable
self.eye_drawer = self.get_drawer(eye_drawer) or self.get_default_eye_drawer()
super().__init__(*args, **kwargs)
def get_drawer(self, drawer: Union[QRModuleDrawer, str, None]) -> Optional[QRModuleDrawer]:
if not isinstance(drawer, str):
return drawer
drawer_cls, kwargs = self.drawer_aliases[drawer]
return drawer_cls(**kwargs)
def init_new_image(self):
self.module_drawer.initialize(img=self)
self.eye_drawer.initialize(img=self)
return super().init_new_image()
def drawrect_context(self, row: int, col: int, qr: "QRCode"):
box = self.pixel_box(row, col)
drawer = self.eye_drawer if self.is_eye(row, col) else self.module_drawer
is_active: Union[bool, ActiveWithNeighbors] = (
qr.active_with_neighbors(row, col)
if drawer.needs_neighbors
else bool(qr.modules[row][col])
)
drawer.drawrect(box, is_active)
|
from election_anomaly import db_routines as dbr
from election_anomaly import user_interface as ui
import pandas as pd
import re
import os
import numpy as np
class MungeError(Exception):
pass
def clean_raw_df(raw,munger):
"""Replaces nulls, strips whitespace, changes any blank entries in non-numeric columns to 'none or unknown'.
Appends munger suffix to raw column names to avoid conflicts"""
# TODO put all info about data cleaning into README.md (e.g., whitespace strip)
# change all nulls to blank
raw = raw.fillna('')
# strip whitespace from non-integer columns
non_numerical = {raw.columns.get_loc(c):c for idx,c in enumerate(raw.columns) if raw[c].dtype != 'int64'}
for location,name in non_numerical.items():
raw.iloc[:,location] = raw.iloc[:,location].apply(lambda x:x.strip())
# TODO keep columns named in munger formulas; keep count columns; drop all else.
if munger.header_row_count > 1:
cols_to_munge = [x for x in raw.columns if x[munger.field_name_row] in munger.field_list]
else:
cols_to_munge = [x for x in raw.columns if x in munger.field_list]
# TODO error check- what if cols_to_munge is missing something from munger.field_list?
# recast count columns as integer where possible.
# (recast leaves columns with text entries as non-numeric).
num_columns = [raw.columns[idx] for idx in munger.count_columns]
for c in num_columns:
try:
raw[c] = raw[c].astype('int64',errors='raise')
except ValueError:
raise
raw = raw[cols_to_munge + num_columns]
# recast all cols_to_munge to strings,
# change all blanks to "none or unknown"
for c in cols_to_munge:
raw[c] = raw[c].apply(str)
raw[c] = raw[c].replace('','none or unknown')
# rename columns to munge by adding suffix
renamer = {x:f'{x}_{munger.field_rename_suffix}' for x in cols_to_munge}
raw.rename(columns=renamer,inplace=True)
return raw
def text_fragments_and_fields(formula):
"""Given a formula with fields enclosed in angle brackets,
return a list of text-fragment,field pairs (in order of appearance) and a final text fragment.
E.g., if formula is <County>;<Precinct>, returned are [(None,County),(';',Precinct)] and None."""
# use regex to apply formula (e.g., decode '<County>;<Precinct>'
p = re.compile('(?P<text>[^<>]*)<(?P<field>[^<>]+)>') # pattern to find text,field pairs
q = re.compile('(?<=>)[^<]*$') # pattern to find text following last pair
text_field_list = re.findall(p,formula)
last_text = re.findall(q,formula)
return text_field_list,last_text
def add_munged_column(raw,munger,element,mode='row',inplace=True):
"""Alters dataframe <raw>, adding or redefining <element>_raw column
via the <formula>. Assumes some preprocessing of <raw> .
Does not alter row count."""
# TODO what preprocessing exactly? Improve description
if raw.empty:
return raw
if inplace:
working = raw
else:
working = raw.copy()
formula = munger.cdf_elements.loc[element,'raw_identifier_formula']
if mode == 'row':
for field in munger.field_list:
formula = formula.replace(f'<{field}>',f'<{field}_{munger.field_rename_suffix}>')
elif mode == 'column':
for i in range(munger.header_row_count):
formula = formula.replace(f'<{i}>',f'<variable_{i}>')
text_field_list,last_text = text_fragments_and_fields(formula)
if last_text:
working.loc[:,f'{element}_raw'] = last_text[0]
else:
working.loc[:,f'{element}_raw'] = ''
text_field_list.reverse()
for t,f in text_field_list:
assert f != f'{element}_raw',f'Column name conflicts with element name: {f}'
working.loc[:,f'{element}_raw'] = t + working.loc[:,f] + working.loc[:,f'{element}_raw']
return working
def replace_raw_with_internal_ids(
row_df,juris,table_df,element,internal_name_column,unmatched_dir,drop_unmatched=False,mode='row'):
"""replace columns in <row_df> with raw_identifier values by columns with internal names and Ids
from <table_df>, which has structure of a db table for <element>.
# TODO If <element> is BallotMeasureContest or CandidateContest,
# contest_type column is added/updated
"""
assert os.path.isdir(unmatched_dir), f'Argument {unmatched_dir} is not a directory'
if drop_unmatched:
how='inner'
else:
how='left'
# join the 'cdf_internal_name' from the raw_identifier table -- this is the internal name field value,
# no matter what the name field name is in the internal element table (e.g. 'Name', 'BallotName' or 'Selection')
# use dictionary.txt from jurisdiction
raw_identifiers = pd.read_csv(os.path.join(juris.path_to_juris_dir,'dictionary.txt'),sep='\t')
# error/warning for unmatched elements to be dropped
raw_ids_for_element = raw_identifiers[raw_identifiers['cdf_element'] == element]
if drop_unmatched:
to_be_dropped = row_df[~row_df[f'{element}_raw'].isin(raw_ids_for_element['raw_identifier_value'])]
if to_be_dropped.shape[0] == row_df.shape[0]:
raise MungeError(f'No {element} was found in \'dictionary.txt\'')
elif not to_be_dropped.empty:
print(
f'Warning: Results for {to_be_dropped.shape[0]} rows '
f'with unmatched {element}s will not be loaded to database.')
row_df = row_df.merge(raw_ids_for_element,how=how,
left_on=f'{element}_raw',
right_on='raw_identifier_value',suffixes=['',f'_{element}_ei'])
# Note: if how = left, unmatched elements get nan in fields from dictionary table
# TODO how do these nans flow through?
if mode == 'column':
# drop rows that melted from unrecognized columns, EVEN IF drop_unmatched=False.
# These rows are ALWAYS extraneous. Drop cols where raw_identifier is not null
# but no cdf_internal_name was found
row_df = row_df[(row_df['raw_identifier_value'].isnull()) | (row_df['cdf_internal_name'].notnull())]
# TODO more efficient to drop these earlier, before melting
# drop extraneous cols from mu.raw_identifier, and drop original raw
row_df = row_df.drop(['raw_identifier_value','cdf_element',f'{element}_raw'],axis=1)
# ensure that there is a column in raw called by the element
# containing the internal name of the element
if f'_{element}_ei' in row_df.columns:
row_df.rename(columns={f'_{element}_ei':element},inplace=True)
else:
row_df.rename(columns={'cdf_internal_name':element},inplace=True)
# join the element table Id and name columns.
# This will create two columns with the internal name field,
# whose names will be element (from above)
# and either internal_name_column or internal_name_column_table_name
row_df = row_df.merge(
table_df[['Id',internal_name_column]],how='left',left_on=element,right_on=internal_name_column)
row_df=row_df.drop([internal_name_column],axis=1)
row_df.rename(columns={'Id':f'{element}_Id'},inplace=True)
return row_df
def enum_col_from_id_othertext(df,enum,enum_df,drop_old=True):
"""Returns a copy of dataframe <df>, replacing id and othertext columns
(e.g., 'CountItemType_Id' and 'OtherCountItemType)
with a plaintext <type> column (e.g., 'CountItemType')
using the enumeration given in <enum_df>"""
assert f'{enum}_Id' in df.columns,f'Dataframe lacks {enum}_Id column'
assert f'Other{enum}' in df.columns,f'Dataframe lacks Other{enum} column'
assert 'Txt' in enum_df.columns,'Enumeration dataframe should have column \'Txt\''
# ensure Id is in the index of enum_df (otherwise df index will be lost in merge)
if 'Id' in enum_df.columns:
enum_df = enum_df.set_index('Id')
df = df.merge(enum_df,left_on=f'{enum}_Id',right_index=True)
# if Txt value is 'other', use Other{enum} value instead
df['Txt'].mask(df['Txt']!='other', other=df[f'Other{enum}'])
df.rename(columns={'Txt':enum},inplace=True)
if drop_old:
df.drop([f'{enum}_Id',f'Other{enum}'],axis=1,inplace=True)
return df
def enum_col_to_id_othertext(df,type_col,enum_df,drop_old=True):
"""Returns a copy of dataframe <df>, replacing a plaintext <type_col> column (e.g., 'CountItemType') with
the corresponding two id and othertext columns (e.g., 'CountItemType_Id' and 'OtherCountItemType
using the enumeration given in <enum_df>"""
if df.empty:
# add two columns
df[f'{type_col}_Id'] = df[f'Other{type_col}'] = df.iloc[:,0]
else:
assert type_col in df.columns
assert 'Txt' in enum_df.columns,'Enumeration dataframe should have a \'Txt\' column'
# ensure Id is a column, not the index, of enum_df (otherwise df index will be lost in merge)
if 'Id' not in enum_df.columns:
enum_df['Id'] = enum_df.index
for c in ['Id','Txt']:
if c in df.columns:
# avoid conflict by temporarily renaming the column in the main dataframe
assert c*3 not in df.colums, 'Column name '+c*3+' conflicts with variable used in code'
df.rename(columns={c:c*3},inplace=True)
df = df.merge(enum_df,how='left',left_on=type_col,right_on='Txt')
df.rename(columns={'Id':f'{type_col}_Id'},inplace=True)
df.loc[:,f'Other{type_col}']=''
other_id_df = enum_df[enum_df['Txt']=='other']
if not other_id_df.empty:
other_id = other_id_df.iloc[0]['Id']
df[f'{type_col}_Id'] = df[f'{type_col}_Id'].fillna(other_id)
df.loc[
df[f'{type_col}_Id'] == other_id,'Other'+type_col] = df.loc[df[f'{type_col}_Id'] == other_id,type_col]
df = df.drop(['Txt'],axis=1)
for c in ['Id','Txt']:
if c*3 in df.columns:
# avoid restore name renaming the column in the main dataframe
df.rename(columns={c*3:c},inplace=True)
if drop_old:
df = df.drop([type_col],axis=1)
return df
def enum_value_from_id_othertext(enum_df,idx,othertext):
"""Given an enumeration dframe (with cols 'Id' and 'Txt', or index and column 'Txt'),
along with an (<id>,<othertext>) pair, find and return the plain language
value for that enumeration (e.g., 'general')."""
# ensure Id is a column, not the index, of enum_df (otherwise df index will be lost in merge)
if 'Id' not in enum_df.columns:
enum_df['Id'] = enum_df.index
if othertext != '':
enum_val = othertext
else:
enum_val = enum_df[enum_df.Id == idx].loc[:,'Txt'].to_list()[0]
return enum_val
def enum_value_to_id_othertext(enum_df,value):
"""Given an enumeration dframe,
along with a plain language value for that enumeration
(e.g., 'general'), return the (<id>,<othertext>) pair."""
# ensure Id is in the index of enum_df (otherwise df index will be lost in merge)
if 'Id' in enum_df.columns:
enum_df = enum_df.set_index('Id')
if value in enum_df.Txt.to_list():
idx = enum_df[enum_df.Txt == value].first_valid_index()
other_txt = ''
else:
idx = enum_df[enum_df.Txt == 'other'].first_valid_index()
other_txt = value
return idx,other_txt
def fk_plaintext_dict_from_db_record(session,element,db_record,excluded=None):
"""Return a dictionary of <name>:<value> for any <name>_Id that is a foreign key
in the <element> table, excluding any foreign key in the list <excluded>"""
fk_dict = {}
fk_df = dbr.get_foreign_key_df(session,element)
if excluded:
for i,r in fk_df.iterrows():
# TODO normalize: do elts of <excluded> end in '_Id' or not?
if i not in excluded and i[:-3] not in excluded:
fk_dict[i] = dbr.name_from_id(session,r['foreign_table_name'],db_record[i])
else:
for i,r in fk_df.iterrows():
fk_dict[i] = dbr.name_from_id(session,r['foreign_table_name'],db_record[i])
return fk_dict
def enum_plaintext_dict_from_db_record(session,element,db_record):
"""Return a dictionary of <enum>:<plaintext> for all enumerations in
<db_record>, which is itself a dictionary of <field>:<value>"""
enum_plaintext_dict = {}
element_df_columns = pd.read_sql_table(element,session.bind,index_col='Id').columns
# TODO INEFFICIENT don't need all of element_df; just need columns
# identify enumerations by existence of `<enum>Other` field
enum_list = [x[5:] for x in element_df_columns if x[:5] == 'Other']
for e in enum_list:
enum_df = pd.read_sql_table(e,session.bind)
enum_plaintext_dict[e] = enum_value_from_id_othertext(enum_df,db_record[f'{e}_Id'],db_record[f'Other{e}'])
return enum_plaintext_dict
def db_record_from_file_record(session,element,file_record):
db_record = file_record.copy()
enum_list = dbr.get_enumerations(session,element)
for e in enum_list:
enum_df = pd.read_sql_table(e,session.bind)
db_record[f'{e}_Id'],db_record[f'Other{e}'] = \
enum_value_to_id_othertext(enum_df,db_record[e])
db_record.pop(e)
fk_df = dbr.get_foreign_key_df(session,element)
for fk in fk_df.index:
if fk[:-3] not in enum_list:
db_record[fk] = dbr.name_to_id(session,fk_df.loc[fk,'foreign_table_name'],file_record[fk[:-3]])
db_record.pop(fk[:-3])
return db_record
def good_syntax(s):
"""Returns true if formula string <s> passes certain syntax main_routines(s)"""
good = True
# check that angle brackets match
# split the string by opening angle bracket:
split = s.split('<')
lead = split[0] # must be free of close angle brackets
if '>' in lead:
good = False
return good
else:
p1 = re.compile(r'^\S') # must start with non-whitespace
p2 = re.compile(r'^[^>]*\S>[^>]*$') # must contain exactly one >, preceded by non-whitespace
for x in split[1:]:
if not (p1.search(x) and p2.search(x)):
good = False
return good
return good
def munge_and_melt(mu,raw,count_cols):
"""Does not alter raw; returns Transformation of raw:
all row- and column-sourced mungeable info into columns (but doesn't translate via dictionary)
new column names are, e.g., ReportingUnit_raw, Candidate_raw, etc.
"""
working = raw.copy()
# apply munging formula from row sources (after renaming fields in raw formula as necessary)
for t in mu.cdf_elements[mu.cdf_elements.source == 'row'].index:
working = add_munged_column(working,mu,t,mode='row')
# remove original row-munge columns
munged = [x for x in working.columns if x[-len(mu.field_rename_suffix):] == mu.field_rename_suffix]
working.drop(munged,axis=1,inplace=True)
# if there is just one numerical column, melt still creates dummy variable col
# in which each value is 'value'
# TODO how to ensure such files munge correctly?
# reshape
non_count_cols = [x for x in working.columns if x not in count_cols]
working = working.melt(id_vars=non_count_cols)
# rename count to Count
# if only one header row, rename variable to variable_0 for consistency
# NB: any unnecessary numerical cols (e.g., Contest Group ID) will not matter
# as they will be be missing from raw_identifiers.txt and hence will be ignored.
# TODO check and correct: no num col names conflict with raw identifiers of column-source
# elements!
working.rename(columns={'variable':'variable_0','value':'Count'},inplace=True)
# apply munge formulas for column sources
for t in mu.cdf_elements[mu.cdf_elements.source == 'column'].index:
working = add_munged_column(working,mu,t,mode='column')
# remove unnecessary columns
not_needed = [f'variable_{i}' for i in range(mu.header_row_count)]
working.drop(not_needed,axis=1,inplace=True)
return working
def add_constant_column(df,col_name,col_value):
new_col = pd.DataFrame([col_value]*df.shape[0],columns=[col_name])
new_df = pd.concat([df,new_col],axis=1)
return new_df
def raw_elements_to_cdf(session,project_root,juris,mu,raw,count_cols,ids=None):
"""load data from <raw> into the database.
Note that columns to be munged (e.g. County_xxx) have mu.field_rename_suffix (e.g., _xxx) added already"""
working = raw.copy()
# enter elements from sources outside raw data, including creating id column(s)
# TODO what if contest_type (BallotMeasure or Candidate) has source 'other'?
if not ids:
for t,r in mu.cdf_elements[mu.cdf_elements.source == 'other'].iterrows():
# add column for element id
# TODO allow record to be passed as a parameter
idx, db_record, enum_d, fk_d = ui.pick_or_create_record(session,project_root,t)
working = add_constant_column(working,f'{t}_Id',idx)
else:
working = add_constant_column(working,'Election_Id',ids[1])
working = add_constant_column(working,'_datafile_Id',ids[0])
working = munge_and_melt(mu,working,count_cols)
# append ids for BallotMeasureContests and CandidateContests
working = add_constant_column(working,'contest_type','unknown')
for c_type in ['BallotMeasure','Candidate']:
df_contest = pd.read_sql_table(f'{c_type}Contest',session.bind)
working = replace_raw_with_internal_ids(
working,juris,df_contest,f'{c_type}Contest',dbr.get_name_field(f'{c_type}Contest'),mu.path_to_munger_dir,
drop_unmatched=False)
# set contest_type where id was found
working.loc[working[f'{c_type}Contest_Id'].notnull(),'contest_type'] = c_type
# drop column with munged name
working.drop(f'{c_type}Contest',axis=1,inplace=True)
# drop rows with unmatched contests
to_be_dropped = working[working['contest_type'] == 'unknown']
working_temp = working[working['contest_type'] != 'unknown']
if working_temp.empty:
raise MungeError('No contests in database matched. No results will be loaded to database.')
elif not to_be_dropped.empty:
print(f'Warning: Results for {to_be_dropped.shape[0]} rows '
f'with unmatched contests will not be loaded to database.')
working = working_temp
# get ids for remaining info sourced from rows and columns
element_list = [t for t in mu.cdf_elements[mu.cdf_elements.source != 'other'].index if
(t[-7:] != 'Contest' and t[-9:] != 'Selection')]
for t in element_list:
# capture id from db in new column and erase any now-redundant cols
df = pd.read_sql_table(t,session.bind)
name_field = dbr.get_name_field(t)
# set drop_unmatched = True for fields necessary to BallotMeasure rows,
# drop_unmatched = False otherwise to prevent losing BallotMeasureContests for BM-inessential fields
if t == 'ReportingUnit' or t == 'CountItemType':
drop = True
else:
drop = False
working = replace_raw_with_internal_ids(working,juris,df,t,name_field,mu.path_to_munger_dir,drop_unmatched=drop)
working.drop(t,axis=1,inplace=True)
# working = add_non_id_cols_from_id(working,df,t)
# append BallotMeasureSelection_Id, drop BallotMeasureSelection
df_selection = pd.read_sql_table(f'BallotMeasureSelection',session.bind)
working = replace_raw_with_internal_ids(
working,juris,df_selection,'BallotMeasureSelection',dbr.get_name_field('BallotMeasureSelection'),
mu.path_to_munger_dir,
drop_unmatched=False,
mode=mu.cdf_elements.loc['BallotMeasureSelection','source'])
# drop records with a BMC_Id but no BMS_Id (i.e., keep if BMC_Id is null or BMS_Id is not null)
working = working[(working['BallotMeasureContest_Id'].isnull()) | (working['BallotMeasureSelection_Id']).notnull()]
working.drop('BallotMeasureSelection',axis=1,inplace=True)
# append CandidateSelection_Id
# First must load CandidateSelection table (not directly munged, not exactly a join either)
# Note left join, as not every record in working has a Candidate_Id
# TODO maybe introduce Selection and Contest tables, have C an BM types refer to them?
c_df = pd.read_sql_table('Candidate',session.bind)
c_df.rename(columns={'Id':'Candidate_Id'},inplace=True)
cs_df, err = dbr.dframe_to_sql(c_df,session,'CandidateSelection',return_records='original')
# add CandidateSelection_Id column, merging on Candidate_Id
working = working.merge(
cs_df[['Candidate_Id','Id']],how='left',left_on='Candidate_Id',right_on='Candidate_Id')
working.rename(columns={'Id':'CandidateSelection_Id'},inplace=True)
# drop records with a CC_Id but no CS_Id (i.e., keep if CC_Id is null or CS_Id is not null)
working = working[(working['CandidateContest_Id'].isnull()) | (working['CandidateSelection_Id']).notnull()]
# TODO: warn user if contest is munged but candidates are not
# TODO warn user if BallotMeasureSelections not recognized in dictionary.txt
for j in ['BallotMeasureContestSelectionJoin','CandidateContestSelectionJoin','ElectionContestJoin']:
working = append_join_id(project_root,session,working,j)
# Fill VoteCount and ElectionContestSelectionVoteCountJoin
# To get 'VoteCount_Id' attached to the correct row, temporarily add columns to VoteCount
# add ElectionContestSelectionVoteCountJoin columns to VoteCount
# Define ContestSelectionJoin_Id field needed in ElectionContestSelectionVoteCountJoin
ref_d = {'ContestSelectionJoin_Id':['BallotMeasureContestSelectionJoin_Id','CandidateContestSelectionJoin_Id']}
working = append_multi_foreign_key(working,ref_d)
# add extra columns to VoteCount table temporarily to allow proper join
extra_cols = ['ElectionContestJoin_Id','ContestSelectionJoin_Id','_datafile_Id']
dbr.add_integer_cols(session,'VoteCount',extra_cols)
# upload to VoteCount table, pull Ids
working_fat, err = dbr.dframe_to_sql(working,session,'VoteCount',raw_to_votecount=True)
working_fat.rename(columns={'Id':'VoteCount_Id'},inplace=True)
session.commit()
# TODO check that all candidates in munged contests (including write ins!) are munged
# upload to ElectionContestSelectionVoteCountJoin
data, err = dbr.dframe_to_sql(working_fat,session,'ElectionContestSelectionVoteCountJoin')
# drop extra columns
dbr.drop_cols(session,'VoteCount',extra_cols)
return
def append_join_id(project_root,session,working,j):
"""Upload join data to db, get Ids,
Append <join>_Id to <working>. Unmatched rows are kept"""
j_path = os.path.join(
project_root,'election_anomaly/CDF_schema_def_info/joins',j,'foreign_keys.txt')
join_fk = pd.read_csv(j_path,sep='\t',index_col='fieldname')
join_fk.loc[:,'refers_to_list'] = join_fk.refers_to.str.split(';')
# create dataframe with cols named to match join table, content from corresponding column of working
refs = set().union(*join_fk.refers_to_list) # all referents of cols in join table
ref_ids = [f'{x}_Id' for x in refs]
j_cols = list(join_fk.index)
# drop dupes and any null rows
join_df = working[ref_ids].drop_duplicates(keep='first') # take only nec cols from working and dedupe
ref_d = {}
for fn in join_fk.index:
ref_d[fn] = [f'{x}_Id' for x in join_fk.loc[fn,'refers_to_list']]
join_df = append_multi_foreign_key(join_df,ref_d)
working = append_multi_foreign_key(working,ref_d)
# remove any join_df rows with any *IMPORTANT* null and load to db
unnecessary = [x for x in ref_ids if x not in j_cols]
join_df.drop(unnecessary,axis=1,inplace=True)
# remove any row with a null value in all columns
join_df = join_df[join_df.notnull().any(axis=1)]
# warn user of rows with null value in some columns
bad_rows = join_df.isnull().any(axis=1)
if bad_rows.any():
print(f'Warning: there are null values, which may indicate a problem.')
ui.show_sample(
join_df[join_df.isnull().any(axis=1)],f'rows proposed for {j}','have null values')
# remove any row with a null value in any column
join_df = join_df[join_df.notnull().all(axis=1)]
# add column for join id
if join_df.empty:
working[f'{j}_Id'] = np.nan
else:
join_df, err = dbr.dframe_to_sql(join_df,session,j)
working = working.merge(join_df,how='left',left_on=j_cols,right_on=j_cols)
working.rename(columns={'Id':f'{j}_Id'},inplace=True)
return working
def append_multi_foreign_key(df,references):
"""<references> is a dictionary whose keys are fieldnames for the new column
and whose value for any key is the list of reference targets.
If a row in df has more than one non-null value, only the first will be taken.
Return the a copy of <df> with a column added for each fieldname in <references>.keys()"""
# TODO inefficient if only one ref target
df_copy = df.copy()
for fn in references.keys():
if df_copy[references[fn]].isnull().all().all():
# if everything is null, just add the necessary column with all null values
df_copy.loc[:,fn] = np.nan
else:
# expect at most one non-null entry in each row; find the value of that one
df_copy.loc[:,fn] = df_copy[references[fn]].fillna(-1).max(axis=1)
# change any -1s back to nulls (if all were null, return null)
df_copy.loc[:,fn]=df_copy[fn].replace(-1,np.NaN)
return df_copy
if __name__ == '__main__':
pass
exit()
|
# Copyright 2016 Cisco Systems, 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.
"""
This module implements all the server actions
"""
import time
from imcsdk.imcexception import ImcOperationError
from imcsdk.mometa.compute.ComputeRackUnit import ComputeRackUnit,\
ComputeRackUnitConsts
from imcsdk.mometa.equipment.EquipmentChassis import EquipmentChassis
from imcsdk.mometa.compute.ComputeServerNode import ComputeServerNodeConsts
from imcsdk.mometa.equipment.EquipmentLocatorLed \
import EquipmentLocatorLed, EquipmentLocatorLedConsts
from imcsdk.mometa.equipment.EquipmentChassisLocatorLed \
import EquipmentChassisLocatorLed, EquipmentChassisLocatorLedConsts
from imcsdk.imccoreutils import get_server_dn, IMC_PLATFORM, _set_server_dn
from imcsdk.apis.utils import _is_valid_arg
def _set_power_state(handle, server_dn, state):
server_mo = handle.query_dn(server_dn)
if handle.platform == IMC_PLATFORM.TYPE_CLASSIC:
mo_class = ComputeRackUnitConsts
elif handle.platform == IMC_PLATFORM.TYPE_MODULAR:
mo_class = ComputeServerNodeConsts
else:
raise ImcOperationError("Set Power State", "Unknown platform:%s found" %
handle.platform)
state_dict = {
"up": mo_class.ADMIN_POWER_UP,
"down": mo_class.ADMIN_POWER_DOWN,
"graceful-down": mo_class.ADMIN_POWER_SOFT_SHUT_DOWN,
"cycle": mo_class.ADMIN_POWER_CYCLE_IMMEDIATE
}
server_mo.admin_power = state_dict[state]
handle.set_mo(server_mo)
def server_power_state_get(handle, server_id=1):
"""
This method will return the oper power status of the rack server
Args:
handle (ImcHandle)
server_id (int): Server Id to be specified for C3260 platforms
Examples:
For classic or non-C3260 series servers:-
server_power_state_get(handle)
For modular or C3260 series servers, server_id should also be passed
in the params:-
server_power_state_get(handle, server_id=1)
If server_id is not specified, this will assume server_id="1"
Returns:
oper power state(string)
"""
server_dn = get_server_dn(handle, server_id)
server_mo = handle.query_dn(server_dn)
if server_mo:
return server_mo.oper_power
raise ImcOperationError("Get Server Power State",
"Managed Object not found for dn:%s" % server_dn)
def _wait_for_power_state(handle, state, timeout=60, interval=5, server_id=1):
"""
This method should be called after a power state change has been triggered.
It will poll the server and return when the desired state is achieved.
Args:
handle(ImcHandle)
state(str)
timeout(int)
interval(int)
server_id (int): Server Id to be specified for C3260 platforms
Returns:
bool
"""
# Verify desired state is valid
if state not in ("on", "off"):
raise ValueError("ERROR invalid state: {0}".format(state))
# Verify interval not set to zero
if interval < 1 or type(interval) is not int:
raise ValueError("ERROR: interval must be positive integer")
wait_time = 0
while server_power_state_get(handle, server_id) != state:
# Raise error if we've reached timeout
if wait_time > timeout:
raise ImcOperationError(
'Power State Change',
'{%s}: ERROR - Power {%s} did not complete within '
'{%s} sec' % (handle.ip, state, timeout)
)
# Wait interval sec between checks
time.sleep(interval)
wait_time += interval
def server_power_up(handle, timeout=60, interval=5, server_id=1, **kwargs):
"""
This method will send the server the power up signal, and then polls
the server every $interval until either $timeout or it comes online.
Args:
handle(ImcHandle)
timeout (int)
interval (int)
server_id (int): Server Id to be specified for C3260 platforms
kwargs: key=value paired arguments
Returns:
ComputeRackUnit object for non-C3260 platform
ComputeServerNode object for C3260 platform
Example:
server_power_up(handle)
server_power_up(handle, timeout=120, interval=10)
server_power_up(handle, server_id=2, timeout=60)
"""
server_dn = get_server_dn(handle, server_id)
# Turn power on only if not already powered up
if server_power_state_get(handle, server_id) != "on":
_set_power_state(handle, server_dn, "up")
# Poll until the server is powered up
_wait_for_power_state(handle, "on", timeout=timeout,
interval=interval, server_id=server_id)
# Return object with current state
return handle.query_dn(server_dn)
def server_power_down(handle, timeout=60, interval=5, server_id=1, **kwargs):
"""
This method will power down the rack server, even if tasks are still
running on it. Then polls the server every $interval until either $timeout
or it comes online.
Args:
handle(ImcHandle)
timeout(int)
interval(int)
server_id (int): Server Id to be specified for C3260 platforms
kwargs: key=value paired arguments
Returns:
ComputeRackUnit object for non-C3260 platform
ComputeServerNode object for C3260 platform
Example:
server_power_down(handle)
server_power_down(handle, timeout=120, interval=10)
server_power_down(handle, server_id=2, timeout=60)
"""
server_dn = get_server_dn(handle, server_id)
# Turn power off only if not already powered down
if server_power_state_get(handle, server_id) != "off":
_set_power_state(handle, server_dn, "down")
# Poll until the server is powered up
_wait_for_power_state(handle, "off", timeout=timeout,
interval=interval, server_id=server_id)
return handle.query_dn(server_dn)
def server_power_down_gracefully(handle, timeout=120, interval=5,
server_id=1, **kwargs):
"""
This method will power down the rack server gracefully
Args:
handle(ImcHandle)
server_id (int): Server Id to be specified for C3260 platforms
kwargs: key=value paired arguments
Returns:
ComputeRackUnit object for non-C3260 platform
ComputeServerNode object for C3260 platform
Example:
server_power_down_gracefully(handle)
server_power_down_gracefully(handle, timeout=120, interval=10)
server_power_down_gracefully(handle, server_id=2, timeout=60)
"""
server_dn = get_server_dn(handle, server_id)
# Gracefully power off only if not already powered down
if server_power_state_get(handle, server_id) != "off":
_set_power_state(handle, server_dn, "graceful-down")
# Poll until the server is powered up
_wait_for_power_state(handle, "off", timeout=timeout,
interval=interval, server_id=server_id)
return handle.query_dn(server_dn)
def server_power_cycle(handle, timeout=120, interval=5, server_id=1, **kwargs):
"""
This method will power cycle the rack server immediately.
Args:
handle(ImcHandle)
server_id (int): Server Id to be specified for C3260 platforms
kwargs: key=value paired arguments
Returns:
ComputeRackUnit object for non-C3260 platform
ComputeServerNode object for C3260 platform
Example:
server_power_cycle(handle) for non-C3260 platforms
server_power_cycle(handle, timeout=120, interval=10) \
for non-C3260 platforms
server_power_cycle(handle, server_id=2, timeout=60) for C3260 platforms
"""
server_dn = get_server_dn(handle, server_id)
_set_power_state(handle, server_dn, "cycle")
# Poll until the server is powered up
_wait_for_power_state(handle, "on", timeout=timeout,
interval=interval, server_id=server_id)
return handle.query_dn(server_dn)
def _set_chassis_locator_led_state(handle, enabled, kwargs):
chassis_id = str(kwargs["chassis_id"])
chassis_dn = "sys/chassis-" + chassis_id
led_mo = EquipmentChassisLocatorLed(parent_mo_or_dn=chassis_dn)
led_mo.admin_state = (EquipmentChassisLocatorLedConsts.ADMIN_STATE_OFF,
EquipmentChassisLocatorLedConsts.ADMIN_STATE_ON)\
[enabled]
handle.set_mo(led_mo)
def _set_server_locator_led_state(handle, enabled, kwargs):
server_dn = _set_server_dn(handle, kwargs)
led_mo = EquipmentLocatorLed(parent_mo_or_dn=server_dn)
led_mo.admin_state = (EquipmentLocatorLedConsts.ADMIN_STATE_OFF,
EquipmentLocatorLedConsts.ADMIN_STATE_ON)[enabled]
handle.set_mo(led_mo)
def locator_led_on(handle, **kwargs):
"""
This method will turn on the locator led on the server or chassis
Args:
handle(ImcHandle)
kwargs: key=value paired arguments
Returns:
None
Example:
locator_led_on(handle) for non-C3260 platforms.
Turns on locator led on the server.
locator_led_on(handle, server_id=1) for C3260 platforms.
Turns on locator led on the specified server.
locator_led_on(handle, chassis_id=1) for C3260 platforms.
Turns on locator led on the chassis.
"""
if _is_valid_arg("chassis_id", kwargs):
_set_chassis_locator_led_state(handle, True, kwargs)
if _is_valid_arg("server_id", kwargs) or \
handle.platform == IMC_PLATFORM.TYPE_CLASSIC:
_set_server_locator_led_state(handle, True, kwargs)
def locator_led_off(handle, **kwargs):
"""
This method will turn off the locator led on the server or on the chassis
Args:
handle(ImcHandle)
kwargs: key=value paired arguments
Returns:
None
Example:
locator_led_off(handle) for non-C3260 platforms.
Turns off locator led on the server.
locator_led_off(handle, server_id=1) for C3260 platforms.
Turns off locator led on the specified server.
locator_led_off(handle, chassis_id=1) for C3260 platforms.
Turns off locator led on the chassis.
"""
if _is_valid_arg("chassis_id", kwargs):
_set_chassis_locator_led_state(handle, False, kwargs)
if _is_valid_arg("server_id", kwargs) or \
handle.platform == IMC_PLATFORM.TYPE_CLASSIC:
_set_server_locator_led_state(handle, False, kwargs)
def tag_server(handle, tag):
"""
This method will tag the server with the label specified.
Applicable to non-C3260 platforms
Args:
handle(ImcHandle)
tag (str): Label to be used to tag the asset
Returns:
ComputeRackUnit object
Example:
tag_server(handle, tag="Row21-Rack10-Slot5")
"""
mo = ComputeRackUnit(parent_mo_or_dn="sys", server_id='1')
mo.asset_tag = str(tag)
handle.set_mo(mo)
return handle.query_dn(mo.dn)
def tag_chassis(handle, tag):
"""
This method will tag the chassis with the label specified.
Applicable to C3260 platforms
Args:
handle(ImcHandle)
tag (str): Label to be used to tag the asset
Returns:
EquipmentChassis object
Example:
tag_server(handle, tag="Row21-Rack10-Slot10")
"""
mo = EquipmentChassis(parent_mo_or_dn="sys")
mo.asset_tag = str(tag)
handle.set_mo(mo)
return handle.query_dn(mo.dn)
|
""" This module loads all the classes from the vtkAddon library into its
namespace."""
from vtkAddonPython import *
|
import pickle
from batch_adversarial_search import BatchPredictorAdversarialBFS
from common import Config, VocabType
from argparse import ArgumentParser
from interactive_predict import InteractivePredictor
from interactive_predict_adversarial_search import InteractivePredictorAdvMonoSearch, \
InteractivePredictorAdvSimilarSearch, InteractivePredictorAdversarialBFS
from model import Model
import sys
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument("-d", "--data", dest="data_path",
help="path to preprocessed dataset", required=False)
parser.add_argument("-te", "--test", dest="test_path",
help="path to test file", metavar="FILE", required=False)
parser.add_argument("-tfold", "--test_folder", dest="test_folder", action='store_true',
help="set this flag to do test on folder", required=False)
parser.add_argument("-tadv", "--test_adversarial", dest="test_adversarial", action='store_true',
help="set this flag to do test with adversarial", required=False)
parser.add_argument("-tadvdep", "--adversarial_depth", dest="adversarial_depth", default=2,
help="set this flag to determine the depth of BFS search", required=False)
parser.add_argument("-tadvtopk", "--adversarial_topk", dest="adversarial_topk", default=2,
help="set this flag to determine the width of BFS search", required=False)
parser.add_argument("-tadvtype", "--adversarial_type", dest="adversarial_type",
help="choose the type of attack. can be 'targeted' or 'non-targeted'", required=False)
parser.add_argument("-tadvtrgt", "--adversarial_target", dest="adversarial_target",
help="choose desired target. or choose 'random-uniform'/'random-unigram' to select random target uniformly/unigramly", required=False)
parser.add_argument("-tadvdead", "--adversarial_deadcode", dest="adversarial_deadcode", action='store_true', default=False,
help="set this flag to use dead-code attack (dataset preprocessed with deadcode required)", required=False)
parser.add_argument("-grd", "--guard_input", dest="guard_input", type=float,
help="set this flag to use input guard",
required=False)
parser.add_argument("-ldict", "--load_dict", dest="load_dict_path",
help="path to dict file", metavar="FILE", required=False)
is_training = '--train' in sys.argv or '-tr' in sys.argv
parser.add_argument("-s", "--save", dest="save_path",
help="path to save file", metavar="FILE", required=False)
parser.add_argument("-w2v", "--save_word2v", dest="save_w2v",
help="path to save file", metavar="FILE", required=False)
parser.add_argument("-t2v", "--save_target2v", dest="save_t2v",
help="path to save file", metavar="FILE", required=False)
parser.add_argument("-l", "--load", dest="load_path",
help="path to save file", metavar="FILE", required=False)
parser.add_argument('--save_w2v', dest='save_w2v', required=False,
help="save word (token) vectors in word2vec format")
parser.add_argument('--save_t2v', dest='save_t2v', required=False,
help="save target vectors in word2vec format")
parser.add_argument('--release', action='store_true',
help='if specified and loading a trained model, release the loaded model for a lower model '
'size.')
parser.add_argument('--predict', action='store_true')
args = parser.parse_args()
config = Config.get_default_config(args)
model = Model(config)
print('Created model')
if config.TRAIN_PATH:
if not args.test_adversarial:
model.train()
else:
model.adversarial_training()
if args.save_w2v is not None:
model.save_word2vec_format(args.save_w2v, source=VocabType.Token)
print('Origin word vectors saved in word2vec text format in: %s' % args.save_w2v)
if args.save_t2v is not None:
model.save_word2vec_format(args.save_t2v, source=VocabType.Target)
print('Target word vectors saved in word2vec text format in: %s' % args.save_t2v)
if config.TEST_PATH and not args.data_path:
if not args.test_folder and not args.test_adversarial:
eval_results = model.evaluate(guard_input=args.guard_input)
if eval_results is not None:
results, precision, recall, f1 = eval_results
print(results)
print('Precision: ' + str(precision) + ', recall: ' + str(recall) + ', F1: ' + str(f1))
elif args.test_folder:
eval_results = model.evaluate_folder()
with open("total_results_" + config.TEST_PATH.replace("/","").replace("\\","") + ".pickle", 'wb') as handle:
pickle.dump(eval_results, handle)
# print(eval_results)
elif args.test_adversarial:
eval_results = model.evaluate_and_adverse(int(args.adversarial_depth),
int(args.adversarial_topk),
targeted_attack=args.adversarial_type=="targeted",
adversarial_target_word=args.adversarial_target,
deadcode_attack=args.adversarial_deadcode,
guard_input=args.guard_input,
data_dict_path=args.load_dict_path)
with open("total_adversarial_results_" + config.TEST_PATH.replace("/", "").replace("\\", "") + ".pickle",
'wb') as handle:
pickle.dump(eval_results, handle)
if args.predict:
if not args.test_adversarial:
# manual adversarial search
predictor = InteractivePredictor(config, model)
else:
predictor = InteractivePredictorAdversarialBFS(config, model,
# predictor = BatchPredictorAdversarialBFS(config, model,
int(args.adversarial_topk),
int(args.adversarial_depth),
args.guard_input, False)
# automatic search for something
# predictor = InteractivePredictorAdvMonoSearch(config, model)
# automatic search similar name
# predictor = InteractivePredictorAdvSimilarSearch(config, model)
predictor.predict()
model.close_session()
|
INPUT_NAME = 'publisher'
OUTPUT_NAME = 'output1'
OUTPUT_UPDATER_NAME = "outputUpdater"
DATA_KEY = "data"
TYPE_KEY = "type"
TELEMETRY_TYPE = "telemetry"
WARNING_TYPE = "warning"
ALERT_TYPE = "alert"
# datas
DATA_DATE_NAME = 'timestamp' |
"""
Group end goals
===============
This module takes the outputs of the genetic algorithm and groups them into clusters of metabolic end goals.
"""
import warnings
import os
from os.path import join
from os import listdir
from BOFdat.util import dijkstra
from BOFdat.util.update import _import_model
from BOFdat.util.update import _get_biomass_objective_function
import cobra
import pandas as pd
import numpy as np
from sklearn.cluster import AgglomerativeClustering
#Visualization librairies
from pylab import rcParams
import matplotlib.pyplot as plt
import seaborn as sb
def _distance_metric(distance_df,fitness):
distance_df = distance_df[distance_df[1]<1000]
metrics = (fitness,distance_df[1].sum(),distance_df[1].mean(),distance_df[1].median())
return metrics
def _get_hof_data(outpath):
hofs=[]
for f in listdir(outpath):
if f.startswith('hof'):
try:
hofs.append(pd.read_csv(join(outpath, f),index_col=0))
except:
warnings.warn('Unable to load file %s'%(f,))
return hofs
def _make_list(m):
l = []
for i in m.split(','):
i = i.replace("'",'')
i = i.replace("[",'')
i = i.replace("]",'')
i = i.replace(" ",'')
l.append(i)
return l
def _filter_hofs(hofs, THRESHOLD):
"""
Selects the best individuals accross HOF generated from multiple evolutions.
HOF are combined together and an arbitrary threshold is set to select the best individuals.
The purpose of this operation is to ensure downstream analysis using metabolite frequency
is relevant (the metabolites with higher frequency allow to obtain better MCC value).
:param hofs: list of HOF dataframes with individuals and their associated fitness
:param THRESHOLD: the percentage best indviduals to select (default is 20%)
:return:
"""
#Pool the hall of fame together
pooled_hof = pd.concat(hofs)
sorted_pooled_hof = pooled_hof.sort_values('Fitness',ascending=False)
#Take the 20% best individuals
final_index = int(len(pooled_hof)*THRESHOLD)
metrics_df = sorted_pooled_hof.iloc[0:final_index,]
#Get the list of metabolites contained in the best all of fames
best_bof = []
for i in range(len(metrics_df)):
l = _make_list(metrics_df.iloc[i,0])
for m in l:
best_bof.append(m)
return best_bof
def _make_freq_df(best_bof):
def occurence(metab, best_bof):
return float(len([m for m in best_bof if m == metab])) / len(best_bof)
#Generate the frequency of each metabolite in hall of fames
frequency_data = []
for m in set(best_bof):
f_m = occurence(m, best_bof)
frequency_data.append((m, f_m))
#Convert to DataFrame and sort by frequency
freq_df = pd.DataFrame.from_records(frequency_data,
columns=['Metab', 'Frequency'],
index=[m for m in set(best_bof)])
freq_df.sort_values('Frequency',inplace=True)
return freq_df
def _generate_result_matrix(freq_df,dist_matrix):
#Select the metabolites based on their apparition frequency in the HALL of FAME
THRESHOLD = freq_df.mean()[0]
selected_metab = [m for m in freq_df[freq_df.iloc[:, 1] > THRESHOLD].iloc[:, 0]]
all_metab = set(selected_metab)
#Generate the reduced distance matrix used for clustering of metabolic end goals
best_bof_dist = dist_matrix[dist_matrix.index.isin(all_metab)]
transposed_bbd = best_bof_dist.T
r = transposed_bbd[transposed_bbd.index.isin(all_metab)]
result_matrix = r.replace(np.nan,1000.)
return result_matrix
def _dbscan_clustering(result_matrix,eps):
from sklearn.cluster import dbscan
# Cluster the distance with DBSCAN clustering algorithm
dbscan_result = dbscan(result_matrix, eps=eps, min_samples=1)
cluster_dict = {result_matrix.index[i]: dbscan_result[1][i] for i in range(len(dbscan_result[1]))}
clusters = []
for k,v in cluster_dict.iteritems():
clusters.append((v,k))
cluster_df = pd.DataFrame.from_records(clusters, columns=['cluster', 'metab'])
#Group metabolites into their respective clusters
grouped = cluster_df.groupby('cluster')
grouped_clusters = grouped.agg(lambda x: ', '.join(x))
return grouped_clusters,cluster_dict
def _display_occurence(freq_df,fig_name):
"""
Plot the frequency of apparition of every metabolites in the Hall of Fames
:param freq_df: dataframe of metabolites and their associated frequency
:param fig_name: the name of the figure to generate
"""
from pylab import rcParams
#Set general ploting parameters
default_param = {'figsize':(10,20),
'sb_style':'whitegrid',
'linestyle':':',
'marker':'',
'baseline_color':'r'
}
rcParams['figure.figsize'] = default_param.get('figsize')
freq_df.sort_values('Frequency',inplace=True,ascending=True)
freq_df.plot(kind='barh')
THRESHOLD = freq_df.mean()[0]
plt.plot((THRESHOLD,THRESHOLD),(0,len(freq_df)),
default_param.get('baseline_color')
,label=default_param.get('baseline_label'),lw=2.5,alpha=0.8,linestyle='-')
number_of_evol = 24
plt.title('Metabolite frequency in best individuals over %s evolutions'%(number_of_evol,),fontsize=24)
plt.xlabel('Metabolite',fontsize=20)
plt.xticks(fontsize=9)
plt.ylabel('Number of apparitions',fontsize=20)
plt.savefig(fig_name)
plt.show()
def _find(x,my_palette,grouped_clusters):
#1- Find the cluster to which x belongs
def find_cluster(x,grouped_clusters):
for i in range(len(grouped_clusters)):
if x in grouped_clusters.loc[i][0].split(', '):
return grouped_clusters.loc[i].name
cluster_id = find_cluster(x,grouped_clusters)
return my_palette.get(cluster_id)
def _display_result_matrix(cluster_matrix, cluster_dict, freq_df, fig_name):
"""
Plot the result of spatial clustering with DBSCAN.
:param grouped_clusters:
:param cluster_matrix: the result of f
:param figname: the name of the figure to generate
:return:
"""
from pylab import rcParams
# General ploting parameters
default_param = {'figsize': (15, 15),
'sb_style': 'whitegrid',
'fontsize': 12}
rcParams['figure.figsize'] = default_param.get('figsize')
rcParams['font.size'] = default_param.get('fontsize')
# Arrange the cluster matrix so that the clusters from DBSCAN are together
# Add a cluster column to the matrix
cluster_matrix['cluster'] = [cluster_dict.get(cluster_matrix.index[i]) for i in range(len(cluster_matrix))]
# Calculate each cluster's frequency
# The cluster frequency is the sum of all individual metabolite frequency
# Convert frequency dataframe to dictionary
freq_dict = {row['Metab']: row['Frequency'] for i, row in freq_df.iterrows()}
# Sort to ensure the rows are in order of cluster
cluster_matrix.sort_values('cluster', inplace=True)
metab_frequency = [freq_dict.get(i) for i in cluster_matrix.index]
cluster_matrix['metabolite frequency'] = metab_frequency
# Make a dictionary that maps cluster identifier number to their sum frequency
cluster_frequency_dict = cluster_matrix.groupby('cluster').sum()['metabolite frequency'].to_dict()
cluster_matrix['cluster frequency'] = [cluster_frequency_dict.get(i) for i in cluster_matrix.cluster]
# Organize matrix for ploting
cluster_matrix.sort_values('cluster frequency', ascending=False, inplace=True)
cluster_matrix.replace(1000., 20., inplace=True)
new_index = [i for i in cluster_matrix.index]
# Transpose and associate metabolites to their respective clusters
transposed_cluster_matrix = cluster_matrix.T
transposed_cluster_matrix.drop(['cluster frequency',
'metabolite frequency', 'cluster'],
axis=0,
inplace=True)
ploting_matrix = transposed_cluster_matrix.reindex(new_index)
# Initialize figure
fig, ax = plt.subplots()
# Plot the heatmap
sb.heatmap(ploting_matrix.T, cbar=False, cmap="mako")
ax.xaxis.set_ticks_position('top')
i = 0
for tick_label in ax.xaxis.get_ticklabels():
# Change the xticks labels
# tick_label.set_color(reversed_row_colors[i])
tick_label.set_rotation(90)
tick_label.set_fontsize(18)
i += 1
i = 0
for tick_label in ax.yaxis.get_ticklabels():
# Change the xticks labels
# tick_label.set_color(reversed_row_colors[i])
tick_label.set_fontsize(18)
i += 1
fig_path = os.path.join('/home/jean-christophe/Documents/Doctorat/BOFdat_paper/Figures_Drive/Figure 5/', fig_name)
# plt.savefig(fig_path)
plt.show()
def _select_metabolites(freq_df,grouped_clusters,best_bof):
#Add selection of the clusters above average
step3 = []
for i in grouped_clusters.metab:
cluster = i.split(', ')
mini_step3 = []
for m in cluster:
if m in best_bof:
mini_step3.append(1)
else:
mini_step3.append(0)
step3.append(sum(mini_step3))
better_results_df = pd.DataFrame({'Step 3 clusters': step3})
compare_cluster_ga = pd.concat([grouped_clusters, better_results_df], axis=1)
bd3_unique = []
for i, row in compare_cluster_ga.iterrows():
mini_unique = [(m, freq_df.loc[m]['Frequency']) for m in row['metab'].split(', ')]
cluster = pd.DataFrame.from_records(mini_unique, columns=['metab', 'freq'])
cluster.index = cluster.metab
del cluster['metab']
for m in cluster.index[cluster['freq'] == cluster.max()[0]]:
bd3_unique.append(m)
return bd3_unique
def _select_metabolites_method2(freq_df, cluster_matrix, best_bof):
"""
Function that selects the metabolites to add to the BOF
Returns a list of metabolites
"""
# 1- Convert frequency dataframe to dictionary
freq_dict = {row['Metab']: row['Frequency'] for i, row in freq_df.iterrows()}
# 2- Sort to ensure the rows are in order of cluster
cluster_matrix.sort_values('cluster', inplace=True)
metab_frequency = [freq_dict.get(i) for i in cluster_matrix.index]
cluster_matrix['metabolite frequency'] = metab_frequency
# 3- Make a dictionary that maps cluster identifier number to their sum frequency
cluster_frequency_dict = cluster_matrix.groupby('cluster').sum()['metabolite frequency'].to_dict()
cluster_matrix['cluster frequency'] = [cluster_frequency_dict.get(i) for i in cluster_matrix.cluster]
# 4- Remove the columns with distance, keeping only cluster and metabolite frequencies
selection_matrix = cluster_matrix.iloc[:, -3:]
# 5- Make a dictionary of max value and cluster identifier
# Get the maximum metabolite frequency for each cluster
grouped = selection_matrix.groupby('cluster').max()
# max_metab_freq = [i for i in grouped['metabolite frequency']]
cluster_frequency = [i for i in grouped['cluster frequency']]
clusters = [i for i in grouped.index]
# max_metab_dict = dict(zip(clusters,max_metab_freq))
cluster_freq_dict = dict(zip(clusters, cluster_frequency))
# Normalize cluster frequency
cluster_freq = pd.DataFrame(cluster_freq_dict.items(), columns=['Cluster', 'Frequency'])
from scipy.stats import zscore
weight = []
for z in zscore(cluster_freq['Frequency']):
if z > 1:
weight.append(3)
elif 1 > z > 0:
weight.append(2)
else:
weight.append(1)
cluster_weight_dict = dict(zip([c for c in cluster_freq['Cluster']], weight))
# 6- Add w metabolites from each cluster where w is the weight
# determined based on the z-score of cluster frequency
selected_metab = []
for i, row in selection_matrix.iterrows():
cluster = row['cluster']
number_of_metab = cluster_weight_dict.get(cluster)
for i in selection_matrix[selection_matrix['cluster'] == cluster].sort_values('metabolite frequency',
ascending=False)[
:number_of_metab].index:
selected_metab.append(i)
return set(selected_metab)
def cluster_metabolites(outpath,
path_to_model,
CONNECTIVITY_THRESHOLD,
THRESHOLD,
eps,
show_frequency,
show_matrix,
frequency_fig_name,
matrix_fig_name):
"""
:param outpath:
:param path_to_model:
:param CONNECTIVITY_THRESHOLD:
:param show_frequency:
:return:
"""
#Get inputs
hofs = _get_hof_data(outpath)
model = _import_model(path_to_model)
#Generate distance matrix
distance_matrix = dijkstra.generate_distance_matrix(model,CONNECTIVITY_THRESHOLD)
#Analyze
#1- Get the best biomass objective functions accross all evolutions
best_bof = _filter_hofs(hofs,THRESHOLD)
#2- Get the frequency of each metabolite
freq_df = _make_freq_df(best_bof)
#3- Cluster the metabolites
result_matrix = _generate_result_matrix(freq_df,distance_matrix)
grouped_clusters, cluster_dictionary = _dbscan_clustering(result_matrix,eps)
#4- Display
if show_frequency:
_display_occurence(freq_df,frequency_fig_name)
if show_matrix:
_display_result_matrix(result_matrix,
cluster_dictionary,
freq_df,
matrix_fig_name)
#Select metabolites based on frequency of apparition in hall of fame
list_of_metab = _select_metabolites(freq_df,grouped_clusters,best_bof)
return list_of_metab |
import pandas as pd
import matplotlib.pyplot as plt
def plotHeatmap(s, col, fillValue=None, ynTicks=10, xnTicks=8, cbar_label=None,
scaling=1, vmin=None, vmax=None, fig=None, ax = None, with_cbar=True,
cbar_nTicks=None, transpose=True):
'''
Plot a heatmap from time series data.
Usage for dataframe df with timestamps in column "date_time" and data to
plot in column "col" (grouped by frequency 'freq':
df_hmap = df.groupby(pd.Grouper(key='date_time', freq=freq,
axis=1)).mean().fillna(method='pad',limit=fillna_limit)
plotting.plotHeatmap(df_hmap, col)
@param pandas.DataFrame s the data frame with the data to plot
@param string col the column in df with the data to plot
@param float fillValue the value to use to fill holes
@param int nTicks the number of y ticks for the plot
@param cbar_label string the label for the color bar
@param float scaling a parameter to rescale the data
@param float vmin min value for color bar
@param float vmax max value for color bar
'''
if fillValue is None:
fillValue = s[col].min()
if cbar_label is None:
cbar_label = col
if cbar_label == "forceNone":
cbar_label = None
df_heatmap = pd.DataFrame(
{"date": s.index.date, "time": s.index.time,
"value_col": s[col].values*scaling}
)
if vmin is None:
vmin = df_heatmap.value_col.min()
if vmax is None:
vmax = df_heatmap.value_col.max()
df_heatmap = df_heatmap.pivot(index="date", columns='time',
values="value_col")
df_heatmap.fillna(value=fillValue,inplace=True) # fill holes for plotting
if fig is None:
fig = plt.figure(figsize=(10,10))
if ax is None:
ax = plt.gca()
if transpose:
df_heatmap = df_heatmap.transpose()
cax = ax.pcolor(df_heatmap, cmap='jet', vmin=vmin, vmax=vmax)
ax.invert_yaxis()
ynTicks = min(len(df_heatmap.index), ynTicks)
xnTicks = min(len(df_heatmap.columns), xnTicks)
ytickPos = range(0,len(df_heatmap.index),
int(len(df_heatmap.index)/ynTicks))
xtickPos = range(0,len(df_heatmap.columns),
int(len(df_heatmap.columns)/xnTicks))
if transpose:
if with_cbar:
if cbar_label is not None:
cb = plt.colorbar(cax, label=cbar_label,
orientation='horizontal')
else:
cb = plt.colorbar(cax, orientation='horizontal')
plt.xticks(xtickPos, [el.strftime('%m-%y') for el in
df_heatmap.columns[xtickPos]])
plt.yticks(ytickPos, [el.hour for el in df_heatmap.index[ytickPos]]);
plt.ylabel('hour')
plt.xlabel('day')
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')
else:
if with_cbar:
if cbar_label is not None:
cb = plt.colorbar(cax, label=cbar_label)
else:
cb = plt.colorbar(cax)
plt.yticks(ytickPos, df_heatmap.index[ytickPos])
plt.xticks(xtickPos, [el.hour for el in df_heatmap.columns[xtickPos]]);
plt.ylabel('day')
plt.xlabel('hour')
if with_cbar and cbar_nTicks is not None:
from matplotlib import ticker
tick_locator = ticker.MaxNLocator(nbins=cbar_nTicks, prune='both')
cb.locator = tick_locator
cb.update_ticks()
if with_cbar:
if transpose:
cb.ax.set_xticklabels([l.get_text().strip('$') for l in
cb.ax.xaxis.get_ticklabels()])
else:
cb.ax.set_yticklabels([l.get_text().strip('$') for l in
cb.ax.yaxis.get_ticklabels()])
def reset_fonts(style="small", SMALL_SIZE=None, MEDIUM_SIZE= None,
BIGGER_SIZE=None):
if style == "big":
SMALL_SIZE = 22
MEDIUM_SIZE = 24
BIGGER_SIZE = 26
if SMALL_SIZE is None:
SMALL_SIZE = 16
if MEDIUM_SIZE is None:
MEDIUM_SIZE = 18
if BIGGER_SIZE is None:
BIGGER_SIZE = 20
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title |
"""
type definitions for opencl types (mapping to ctypes).
This is based on:
https://www.khronos.org/registry/cl/sdk/1.0/docs/man/xhtml/scalarDataTypes.html
And to some point it will be based on data in headers
"""
from __future__ import print_function, absolute_import, division
import ctypes
if ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_int32):
c_intptr_t = ctypes.c_int32
else:
assert (ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_int64))
c_intptr_t = ctypes.c_int64
cl_char = ctypes.c_int8 # signed two's complement 8-bit integer
cl_uchar = ctypes.c_uint8 # unsigned 8-bit integer
cl_short = ctypes.c_int16 # signed two's complement 16-bit integer
cl_ushort = ctypes.c_uint16 # unsigend 16-bit integer
cl_int = ctypes.c_int32 # signed two's complement 32-bit integer
cl_uint = ctypes.c_uint32 # unsigned 32-bit integer
cl_long = ctypes.c_int64 # signed two's complement 64-bit integer
cl_ulong = ctypes.c_uint64 # unsigned 64-bit integer
cl_platform_id = ctypes.c_void_p
cl_device_id = ctypes.c_void_p
cl_context = ctypes.c_void_p
cl_command_queue = ctypes.c_void_p
cl_mem = ctypes.c_void_p
cl_program = ctypes.c_void_p
cl_kernel = ctypes.c_void_p
cl_event = ctypes.c_void_p
cl_sampler = ctypes.c_void_p
# The ones below may need to be tweaked per platform (looked up on header files)
cl_bitfield = cl_ulong
cl_command_queue_properties = cl_bitfield
cl_device_type = cl_bitfield
cl_mem_flags = cl_bitfield
cl_platform_info = cl_uint
cl_device_info = cl_uint
cl_context_info = cl_uint
cl_program_info = cl_uint
cl_kernel_info = cl_uint
cl_mem_info = cl_uint
cl_event_info = cl_uint
cl_command_type = cl_uint
cl_device_fp_config = cl_bitfield
cl_device_exec_capabilities = cl_bitfield
cl_device_mem_cache_type = cl_uint
cl_device_local_mem_type = cl_uint
cl_context_properties = c_intptr_t
cl_kernel_work_group_info = cl_uint
cl_command_queue_info = cl_uint
cl_mem_object_type = cl_uint
cl_buffer_create_type = cl_uint
cl_program_build_info = cl_uint
cl_build_status = cl_uint
cl_bool = cl_uint # this probably can change from platform to platform |
from genetic import *
from image import *
from snn import *
import math, random
import numpy
def convert_binary(data, w, h, t):
ans = [[0 for x in xrange(w)] for x in xrange(h)]
for x in xrange(h):
for y in xrange(w):
if data[x][y] > t:
ans[x][y] = 1
else:
ans[x][y] = 0
return ans
def convert_mat(data, w, h, thresh):
ans = [[0 for x in xrange(w)] for x in xrange(h)]
for x in xrange(h):
for y in xrange(w):
if data[x][y] > thresh[x][y]:
ans[x][y] = 1
else:
ans[x][y] = 0
return ans
def shenon_entropy(data, w, h):
black, white = 0,0
for x in xrange(h):
for y in xrange(w):
if data[x][y]:
white += 1
else:
black += 1
total = w*h
prob_white = white / (total*1.0)
prob_black = black / (total*1.0)
formula = - (prob_black * math.log(prob_black,2) + prob_white * math.log(prob_white, 2))
return formula
def fitness(population, data, w, h):
fitness_dict = {}
for x in population:
ans = convert_binary(data, w, h, x)
entropy = shenon_entropy(ans, w, h)
if entropy in fitness_dict:
entropy = entropy + random.random()/1000
fitness_dict[entropy] = x
# imagewrite(ans, w, h)
# print entropy, x
return fitness_dict
def fitness_mat(population, data, w, h):
fitness_dict = {}
for x in population:
ans = convert_mat(data, w, h, x)
entropy = shenon_entropy( ans , w, h)
if entropy in fitness_dict:
entropy = entropy + random.random()/1000
fitness_dict[entropy] = x
return fitness_dict
def fitness_weight(population, w, h, t, ind):
fitness_dict = {}
for y, x in enumerate(population):
ans = convert_binary(x, w, h, t)
entropy = shenon_entropy(ans, w, h)
if entropy in fitness_dict:
entropy = entropy + random.random()/1000
fitness_dict[entropy] = ind[y]
return fitness_dict
# read image
pixel, w, h = imageread('test8.jpg')
# convert to snn
pixel_mat = snn_response(pixel, w, h, 10, 0.05)
d=3
def weight(x1,y1,x,y):
w = 10*math.exp(- ( ( math.pow((x1-x),2)+math.pow((y1-y),2) + math.pow(pixel[x1][y1]-pixel[x][y],2 )/d ) ) )
return w
def second_layer_locality():
second_layer = [[0 for x in xrange(w+2)] for x in xrange(h+2)]
for x in xrange(1,h-1):
for y in xrange(1,w-1):
temp = {}
for i in xrange(x-1, x+1):
for j in xrange(y-1, y+1):
temp[pixel_mat[i][j]] = weight(x,y,i,j)
second_layer[x][y] = response_time(temp)
second_layer = numpy.delete(second_layer, (0), axis=0)
second_layer = numpy.delete(second_layer, len(second_layer)-1, axis=0)
second_layer = numpy.delete(second_layer, (0), axis=1)
second_layer = numpy.delete(second_layer, len(second_layer[0])-1, axis=1)
return second_layer
def second_layer(w_mat):
second_layer = [[0 for x in xrange(w+2)] for x in xrange(h+2)]
for x in xrange(h):
for y in xrange(w):
second_layer[x][y] = response_time({pixel_mat[x][y]:w_mat[x][y]})
return second_layer
def median_filter(mat, w, h):
for x in xrange(h):
for y in xrange(w):
if mat[x][y] < numpy.median(mat):
mat[x][y]=0
return mat
# ==================== SNN Weight ====================
# print "Started "
# population1 = init_three_dim_mat(1, 3,3, 9)
# print population1
# ==================== SNN Matrix ====================
print "Starting GA ..."
population1 = init_mat(10,w,h)
print "Population created ..."
t = 5.0
final = []
for x in xrange(16):
print "Performing Iteration :", x+1
sl = []
for pop in population1:
temp = second_layer(pop)
sl.append(temp)
a = fitness_weight(sl, w, h, t , population1)
population1, m, max = crossover_mat( a, w, h )
print "Maximum fitness for this generation :",max
print "======================================"
sl = second_layer(m)
ans = convert_binary(sl, w, h, t)
final = sl
if x % 4 == 0:
imagesave(ans, w, h, 't6test8gen ' + str(x) + ' fit ' )
imagewrite(ans, w, h)
# print len(final)
# x = median_filter(final, w, h)
# print 'shannon entropy : ',shenon_entropy( x , w, h)
# imagewrite(x, w, h)
# if x % 5 == 0:
# # ans = convert_mat(pixel_mat, w, h, m)
# imagesave(ans, w, h, 'gen ' + str(x) + ' fit ' )
# for x in xrange(11):
# # a = fitness_mat(population1, pixel_mat, w, h)
# a = fitness_mat(population1, second_layer, w, h)
# population1, m, max = crossover_mat( a, w, h )
# print max
# if x % 5 == 0:
# # ans = convert_mat(pixel_mat, w, h, m)
# ans = convert_mat(second_layer, w, h, m)
# imagewrite(ans, w, h)
# imagesave(ans, w, h, 'gen ' + str(x) + ' fit ' )
# print "==========="
# ==================== SNN Int =======================
# imagewrite(ans, w, h)
# initialize population
# population1 = init_num(8)
# for x in xrange(11):
# a = fitness(population1, second_layer, w, h)
# population1, m, max = crossover_num( a )
# if x % 5 == 0:
# ans = convert_binary(second_layer, w, h, m)
# imagewrite(ans, w, h)
# imagesave(ans, w, h, 'gen ' + str(x) + ' fit ' + str(m))
# print "==========="
# print max |
"""Bazel-specific intellij aspect."""
load(
":intellij_info_impl.bzl",
"intellij_info_aspect_impl",
"make_intellij_info_aspect",
)
def tool_label(tool_name):
"""Returns a label that points to a tool target in the bundled aspect workspace."""
return Label("//aspect/tools:" + tool_name)
def get_go_import_path(ctx):
"""Returns the import path for a go target."""
import_path = getattr(ctx.rule.attr, "importpath", None)
if import_path:
return import_path
prefix = None
if hasattr(ctx.rule.attr, "_go_prefix"):
prefix = ctx.rule.attr._go_prefix.go_prefix
if not prefix:
return None
import_path = prefix
if ctx.label.package:
import_path += "/" + ctx.label.package
if ctx.label.name != "go_default_library":
import_path += "/" + ctx.label.name
return import_path
semantics = struct(
tool_label = tool_label,
go = struct(
get_import_path = get_go_import_path,
),
)
def _aspect_impl(target, ctx):
return intellij_info_aspect_impl(target, ctx, semantics)
intellij_info_aspect = make_intellij_info_aspect(_aspect_impl, semantics)
|
class Node:
def __init__(self, data, point=None):
"""
Create Node that alows to store two data in head and pointer.
Example : \n
>>> node = Node(5)
>>> node.point = Node(3)
>>> node
5-->3-->
:param data: Values to be stored in head
:param point: Values to be pointed
:return: None
"""
self.head = data
self.point = point
def __str__(self):
if self.head is None:
return 'Node is empty'
else:
itr = self
string_itr = ''
while itr:
string_itr += f'{itr.head}-->'
itr = itr.point
return string_itr
class LinkedList:
def __init__(self):
"""
Initialize linked list class to used in instance
Example : \n
>>> linked_list = LinkedList()
>>> linked_list.to_linked([1, 2, 3])
>>> linked_list
1-->2-->3-->
"""
self.node = None
def __str__(self):
if self.node is None:
return 'Linked list is empty'
else:
itr = self.node
string_itr = ''
while itr:
string_itr += f'{itr.head}-->'
itr = itr.point
return string_itr
def __len__(self):
if self.node is None:
return 0
else:
counter = 0
itr = self.node
while itr:
counter += 1
itr = itr.point
return counter
def __iter__(self):
itr = self.node
while itr:
yield itr
itr = itr.point
def to_linked(self, array):
"""
Convert normal python iterable into linked list
Example : \n
>>> linked_list = LinkedList()
>>> linked_list.to_linked([1,2,3])
>>> linked_list
1-->2-->3-->
:param array: Iterable, ex : list, tuple, set
:return: None
"""
for i in array:
self.append(i)
def append(self, data):
"""
Append data values from any type into linked list.\n
Example:\n
>>> linked_list = LinkedList()
>>> linked_list.to_linked([1,2,3])
>>> linked_list.append('Can be anything')
>>> linked_list
1-->2-->3-->Can be anything-->
:param data: Values to be appended in any type.
:return: None
"""
if self.node is None:
self.node = Node(data)
else:
itr = self.node
while itr:
if itr.point is None:
itr.point = Node(data)
break
itr = itr.point
def insert_start(self, data):
"""
Insert values to linked list at the start (index zero)
Example : \n
>>> linked_list = LinkedList()
>>> linked_list.to_linked([1, 2, 3])
>>> linked_list.insert_start(7)
>>> linked_list
7-->1-->2-->3-->
:param data: Values to be appended
:return: None
"""
if self.node is None:
self.node = Node(data, None)
else:
self.node = Node(data, self.node)
def insert_at(self, index, data):
"""
Insert values into specific index of linked list
Example : \n
>>> linked_list = LinkedList()
>>> linked_list.to_linked([1, 2, 3])
>>> linked_list.insert_at(2,12)
>>> linked_list
1-->2-->12-->3-->
:param index: Index / position of the linked list
:param data: Values to be appended
:return: None
"""
if self.node is None:
self.node = Node(data, None)
else:
counter = 0
itr = self.node
while itr:
counter += 1
if counter == index:
itr.point = Node(data, itr.point)
break
itr = itr.point
def remove_at(self, index):
"""
Remove values from linked list by the index
Example : \n
>>> linked_list = LinkedList()
>>> linked_list.to_linked([1, 2, 3])
>>> linked_list.remove_at(2)
>>> linked_list
1-->2-->
:param index: Index of linked list
:return: None
"""
if self.node is None:
pass
else:
counter = 0
itr = self.node
while itr:
counter += 1
if counter == index:
itr.point = itr.point.point
break
itr = itr.point
if __name__ == '__main__':
li = LinkedList()
li.to_linked([1, 2, 3])
li.remove_at(2)
print(f'Linked list : {li}')
print(f'Len of linked list : {len(li)}')
|
#!/bin/python
# -*- coding: utf8 -*-
import logging
import unittest
from builtins import range
from tablestore.client import *
from tablestore.metadata import *
from tablestore.error import *
from lib.mock_connection import MockConnection
from lib.test_config import *
class SDKParamTest(unittest.TestCase):
def setUp(self):
logger = logging.getLogger('test')
handler=logging.FileHandler("test.log")
formatter = logging.Formatter("[%(asctime)s] [%(process)d] [%(levelname)s] " \
"[%(filename)s:%(lineno)s] %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
OTSClient.connection_pool_class = MockConnection
self.client = OTSClient(OTS_ENDPOINT, OTS_ID, OTS_SECRET, OTS_INSTANCE)
def tearDown(self):
pass
def test_list_table(self):
try:
self.client.list_table('one');
self.assertTrue(False)
except TypeError:
pass
def test_create_table(self):
try:
self.client.create_table('one', 'two', 'three')
self.assertTrue(False)
except OTSClientError:
pass
try:
table_meta = TableMeta('test_table', ['PK1', 'STRING'])
capacity_unit = CapacityUnit(10, 10)
self.client.create_table(table_meta, TableOptions(), capacity_unit)
self.assertTrue(False)
except OTSClientError:
pass
try:
table_meta = TableMeta('test_table', [('PK1', 'STRING'), ('PK2', 'INTEGER')])
capacity_unit = CapacityUnit(10, None)
self.client.create_table(table_meta, TableOptions(), capacity_unit)
self.assertTrue(False)
except OTSClientError:
pass
try:
capacity_unit = CapacityUnit(10, 10)
self.client.create_table('test_table', TableOptions(), capacity_unit)
self.assertTrue(False)
except OTSClientError:
pass
try:
table_meta = TableMeta('test_table', [('PK1', 'STRING'), ('PK2', 'INTEGER')])
self.client.create_table(table_meta, TableOptions(), [1, 2])
self.assertTrue(False)
except OTSClientError:
pass
def test_delete_table(self):
try:
self.client.delete_table('one', 'two')
self.assertTrue(False)
except:
pass
try:
capacity_unit = CapacityUnit(10, 10)
self.client.delete_table(capacity_unit)
self.assertTrue(False)
except OTSClientError:
pass
def test_update_table(self):
try:
self.client.update_table('one', 'two', 'three')
self.assertTrue(False)
except:
pass
try:
self.client.update_table('test_table', TableOptions(), (10, 10))
self.assertTrue(False)
except OTSClientError:
pass
try:
capacity_unit = CapacityUnit(None, None)
self.client.update_table('test_table', TableOptions(),capacity_unit)
self.assertTrue(False)
except OTSClientError:
pass
def test_describe_table(self):
try:
self.client.describe_table('one', 'two')
self.assertTrue(False)
except:
pass
try:
response = self.client.describe_table(['test_table'])
self.assertTrue(False)
except OTSClientError:
pass
def test_put_row(self):
try:
self.client.put_row('one', 'two')
self.assertTrue(False)
except:
pass
try:
primary_key = [('PK1','hello'), ('PK2',100)]
attribute_columns = [('COL1','world'), ('COL2',1000)]
condition = Condition('InvalidCondition')
consumed = self.client.put_row('test_table', condition, primary_key, attribute_columns)
self.assertTrue(False)
except OTSClientError:
pass
try:
primary_key = [('PK1','hello'), ('PK2',100)]
attribute_columns = [('COL1','world'), ('COL2',1000)]
consumed = self.client.put_row('test_table', [RowExistenceExpectation.IGNORE], primary_key, attribute_columns)
self.assertTrue(False)
except:
pass
try:
condition = Condition(RowExistenceExpectation.IGNORE)
consumed = self.client.put_row('test_table', condition, 'primary_key', 'attribute_columns')
self.assertTrue(False)
except:
pass
def test_get_row(self):
try:
self.client.get_row('one', 'two')
self.assertTrue(False)
except:
pass
try:
consumed, resp_pks, resp_attribute_columns = self.client.get_row('test_table', 'primary_key', 'columns_to_get')
self.assertTrue(False)
except:
pass
def test_update_row(self):
try:
self.client.update_row('one', 'two', 'three')
self.assertTrue(False)
except:
pass
try:
condition = Condition(RowExistenceExpectation.IGNORE)
consumed = self.client.update_row('test_table', condition, [('PK1', 'STRING'), ('PK2', 'INTEGER')], 'update_of_attribute_columns')
self.assertTrue(False)
except OTSClientError as e:
pass
try:
condition = Condition(RowExistenceExpectation.IGNORE)
consumed = self.client.update_row('test_table', condition, [('PK1', 'STRING'), ('PK2', 'INTEGER')], [('ncv', 1)])
self.assertTrue(False)
except OTSClientError as e:
pass
try:
condition = Condition(RowExistenceExpectation.IGNORE)
consumed = self.client.update_row('test_table', condition, [('PK1', 'STRING'), ('PK2', 'INTEGER')], {'put' : []})
self.assertTrue(False)
except OTSClientError as e:
pass
try:
condition = Condition(RowExistenceExpectation.IGNORE)
consumed = self.client.update_row('test_table', condition, [('PK1', 'STRING'), ('PK2', 'INTEGER')], {'delete' : []})
self.assertTrue(False)
except OTSClientError as e:
pass
def test_delete_row(self):
try:
self.client.delete_row('one', 'two', 'three', 'four')
self.assertTrue(False)
except:
pass
try:
condition = Condition(RowExistenceExpectation.IGNORE)
consumed = self.client.delete_row('test_table', condition, 'primary_key')
self.assertTrue(False)
except:
pass
def test_batch_get_row(self):
try:
self.client.batch_get_row('one', 'two')
self.assertTrue(False)
except:
pass
try:
response = self.client.batch_get_row('batches')
self.assertTrue(False)
except OTSClientError:
pass
def test_batch_write_row(self):
try:
self.client.batch_write_row('one', 'two')
self.assertTrue(False)
except:
pass
try:
response = self.client.batch_write_row('batches')
self.assertTrue(False)
except OTSClientError:
pass
batch_list = [('test_table')]
try:
response = self.client.batch_write_row(batch_list)
self.assertTrue(False)
except OTSClientError:
pass
batch_list = [{'table_name':None}]
try:
response = self.client.batch_write_row(batch_list)
self.assertTrue(False)
except OTSClientError:
pass
batch_list = [{'table_name':'abc', 'put':None}]
try:
response = self.client.batch_write_row(batch_list)
self.assertTrue(False)
except OTSClientError:
pass
batch_list = [{'table_name':'abc', 'put':['xxx']}]
try:
response = self.client.batch_write_row(batch_list)
self.assertTrue(False)
except OTSClientError:
pass
batch_list = [{'table_name':'abc', 'Put':[]}]
try:
response = self.client.batch_write_row(batch_list)
self.assertTrue(False)
except OTSClientError:
pass
batch_list = [{'table_name':'abc', 'Any':[]}]
try:
response = self.client.batch_write_row(batch_list)
self.assertTrue(False)
except OTSClientError:
pass
def test_get_range(self):
try:
self.client.get_range('one', 'two')
self.assertTrue(False)
except:
pass
try:
start_primary_key = [('PK1','hello'),('PK2',100)]
end_primary_key = [('PK1',INF_MAX),('PK2',INF_MIN)]
columns_to_get = ['COL1','COL2']
response = self.client.get_range('table_name', 'InvalidDirection',
start_primary_key, end_primary_key,
columns_to_get, limit=100, max_version=1
)
self.assertTrue(False)
except OTSClientError:
pass
try:
start_primary_key = ['PK1','hello','PK2',100]
end_primary_key = [('PK1',INF_MAX), ('PK2',INF_MIN)]
columns_to_get = ['COL1', 'COL2']
response = self.client.get_range('table_name', 'FORWARD',
start_primary_key, end_primary_key,
columns_to_get, limit=100, max_version=1
)
self.assertTrue(False)
except:
pass
try:
start_primary_key = [('PK1','hello'),('PK2',100)]
end_primary_key = [('PK1',INF_MAX), ('PK2',INF_MIN)]
columns_to_get = ['COL1', 'COL2']
response = self.client.get_range('table_name', 'FORWARD',
start_primary_key, end_primary_key,
columns_to_get, limit=100, max_version=-1
)
self.assertTrue(False)
except:
pass
try:
response = self.client.get_range('table_name', 'FORWARD',
'primary_key', 'primary_key', 'columns_to_get', 100)
self.assertTrue(False)
except:
pass
def test_xget_range(self):
try:
self.client.xget_range('one', 'two')
self.assertTrue(False)
except:
pass
try:
iter = self.client.xget_range('one', 'two', 'three', 'four', 'five', 'six', 'seven')
#iter.next()
next(iter)
self.assertTrue(False)
except OTSClientError:
pass
def assert_client_error(self, error, message):
self.assertEqual(str(error), message)
def test_condition(self):
Condition(RowExistenceExpectation.IGNORE)
Condition(RowExistenceExpectation.EXPECT_EXIST)
Condition(RowExistenceExpectation.EXPECT_NOT_EXIST)
try:
cond = Condition('errr')
self.assertTrue(False)
except OTSClientError as e:
self.assertEqual("Expect input row_existence_expectation should be one of ['RowExistenceExpectation.IGNORE', 'RowExistenceExpectation.EXPECT_EXIST', 'RowExistenceExpectation.EXPECT_NOT_EXIST'], but 'errr'", str(e))
try:
cond = Condition(RowExistenceExpectation.IGNORE, "")
self.assertTrue(False)
except OTSClientError as e:
self.assertEqual("The input column_condition should be an instance of ColumnCondition, not str", str(e))
try:
cond = Condition(RowExistenceExpectation.IGNORE, SingleColumnCondition("", "", ""))
self.assertTrue(False)
except OTSClientError as e:
self.assertEqual("Expect input comparator of SingleColumnCondition should be one of ['ComparatorType.EQUAL', 'ComparatorType.NOT_EQUAL', 'ComparatorType.GREATER_THAN', 'ComparatorType.GREATER_EQUAL', 'ComparatorType.LESS_THAN', 'ComparatorType.LESS_EQUAL'], but ''", str(e))
def test_column_condition(self):
cond = SingleColumnCondition("uid", 100, ComparatorType.EQUAL)
self.assertEqual(ColumnConditionType.SINGLE_COLUMN_CONDITION, cond.get_type())
cond = CompositeColumnCondition(LogicalOperator.AND)
self.assertEqual(ColumnConditionType.COMPOSITE_COLUMN_CONDITION, cond.get_type())
def test_relation_condition(self):
SingleColumnCondition("uid", 100, ComparatorType.EQUAL)
SingleColumnCondition("uid", 100, ComparatorType.NOT_EQUAL)
SingleColumnCondition("uid", 100, ComparatorType.GREATER_THAN)
SingleColumnCondition("uid", 100, ComparatorType.GREATER_EQUAL)
SingleColumnCondition("uid", 100, ComparatorType.LESS_THAN)
SingleColumnCondition("uid", 100, ComparatorType.LESS_EQUAL)
try:
cond = SingleColumnCondition("uid", 100, "")
self.assertTrue(False)
except OTSClientError as e:
self.assertEqual("Expect input comparator of SingleColumnCondition should be one of ['ComparatorType.EQUAL', 'ComparatorType.NOT_EQUAL', 'ComparatorType.GREATER_THAN', 'ComparatorType.GREATER_EQUAL', 'ComparatorType.LESS_THAN', 'ComparatorType.LESS_EQUAL'], but ''", str(e))
try:
cond = SingleColumnCondition("uid", 100, ComparatorType.LESS_EQUAL, "True")
self.assertTrue(False)
except OTSClientError as e:
self.assertEqual("The input pass_if_missing of SingleColumnCondition should be an instance of Bool, not str", str(e))
def test_composite_condition(self):
CompositeColumnCondition(LogicalOperator.NOT)
CompositeColumnCondition(LogicalOperator.AND)
CompositeColumnCondition(LogicalOperator.OR)
try:
cond = CompositeColumnCondition("")
self.assertTrue(False)
except OTSClientError as e:
self.assertEqual("Expect input combinator should be one of ['LogicalOperator.NOT', 'LogicalOperator.AND', 'LogicalOperator.OR'], but ''", str(e))
if __name__ == '__main__':
unittest.main()
|
def test_healthcheck(survey_runner):
response = survey_runner.test_client().get('/healthcheck')
assert response.status_code == 200
assert "success" in response.get_data(as_text=True)
|
from mtq.job import Job
from mtq.utils import is_str
class QueueError(Exception):
pass
class Queue(object):
'''
A queue to enqueue an pop tasks
Do not create directly use MTQConnection.queue
'''
def __str__(self):
return self.name
def __repr__(self):
return '<mtq.Queue name:%s tags:%r>' % (self.name, self.tags)
def __init__(self, factory, name='default', tags=(), priority=0):
self.name = name or 'default'
self.factory = factory
self.tags = tuple(tags) if tags else ()
self.priority = priority
def enqueue(self, func_or_str, *args, **kwargs):
'''
Creates a job to represent the delayed function call and enqueues
it.
Expects the function to call, along with the arguments and keyword
arguments.
The function argument `func_or_str` may be a function or a string representing the location of a function
'''
return self.enqueue_call(func_or_str, args, kwargs)
def enqueue_call(self, func_or_str, args=(), kwargs=None, tags=(), priority=None, timeout=None, mutex=None):
'''
Creates a job to represent the delayed function call and enqueues
it.
It is much like `.enqueue()`, except that it takes the function's args
and kwargs as explicit arguments. Any kwargs passed to this function
contain options for MQ itself.
'''
if not is_str(func_or_str):
name = getattr(func_or_str, '__name__', None)
module = getattr(func_or_str, '__module__', None)
if not (name and module):
raise QueueError('can not enqueue %r (type %r)' % (func_or_str, type(func_or_str)))
func_or_str = '%s.%s' % (module, name)
if args is None:
args = ()
elif not isinstance(args, (list, tuple)):
raise TypeError('argument args must be a tuple')
if kwargs is None:
kwargs = {}
elif not isinstance(kwargs, dict):
raise TypeError('argument kwargs must be a dict')
execute = {'func_str': func_or_str, 'args':tuple(args), 'kwargs': dict(kwargs)}
if priority is None:
priority = self.priority
tags = self.tags + tuple(tags)
doc = Job.new(self.name, tags, priority, execute, timeout, mutex)
collection = self.factory.queue_collection
collection.insert(doc)
return Job(self.factory, doc)
@property
def count(self):
'The number of jobs in this queue (filtering by tags too)'
collection = self.factory.queue_collection
query = self.factory.make_query([self.name], self.tags, self.priority)
return collection.find(query).count()
@property
def num_failed(self):
'The number of jobs in this queue (filtering by tags too)'
collection = self.factory.queue_collection
query = self.factory.make_query([self.name], self.tags, failed=True, processed=None)
return collection.find(query).count()
def is_empty(self):
'The number of jobs in this queue (filtering by tags too)'
return bool(self.count == 0)
@property
def all_tags(self):
'All the unique tags of jobs in this queue'
collection = self.factory.queue_collection
return set(collection.find({'qname':self.name}).distinct('tags'))
def pop(self, worker_id=None):
'Pop a job off the queue'
return self.factory.pop_item(worker_id, [self.name], self.tags, self.priority)
@property
def jobs(self):
return self.factory.items([self.name], self.tags, self.priority)
@property
def finished_jobs(self):
return self.factory.items([self.name], self.tags, self.priority,
processed=True, limit=30, reverse=True)
@property
def all_jobs(self):
return self.factory.items([self.name], self.tags, self.priority, processed=None, limit=30, reverse=True)
|
"""
Module: 'flowlib.units._dual_button' on M5 FlowUI v1.4.0-beta
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-284-g5d8e1c867 on 2019-08-30', machine='ESP32 module with ESP32')
# Stubber: 1.3.1 - updated
from typing import Any
class Dual_button:
""""""
def deinit(self, *argv) -> Any:
pass
portMethod = 15
btn = None
unit = None
|
import unittest
from tests.integration.exchange import BacktestExchangeBaseIntegrationTest
from tests.integration.run import (
ParseParamsAndExecuteAlgorithmIntegrationTests, MainLoopIntegrationTest,
ExecuteAlgorithmIntegrationTests)
def test_suite():
suite = unittest.TestSuite([
unittest.makeSuite(BacktestExchangeBaseIntegrationTest),
unittest.makeSuite(ExecuteAlgorithmIntegrationTests),
unittest.makeSuite(MainLoopIntegrationTest),
unittest.makeSuite(ParseParamsAndExecuteAlgorithmIntegrationTests),
])
return suite
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import os.path
import re
from cs.CsDatabag import CsDataBag
from CsProcess import CsProcess
from CsFile import CsFile
import CsHelper
HAPROXY_CONF_T = "/etc/haproxy/haproxy.cfg.new"
HAPROXY_CONF_P = "/etc/haproxy/haproxy.cfg"
class CsLoadBalancer(CsDataBag):
""" Manage Load Balancer entries """
def process(self):
if "config" not in self.dbag.keys():
return
if 'configuration' not in self.dbag['config'][0].keys():
return
config = self.dbag['config'][0]['configuration']
file1 = CsFile(HAPROXY_CONF_T)
file1.empty()
for x in config:
[file1.append(w, -1) for w in x.split('\n')]
file1.commit()
file2 = CsFile(HAPROXY_CONF_P)
if not file2.compare(file1):
CsHelper.copy(HAPROXY_CONF_T, HAPROXY_CONF_P)
proc = CsProcess(['/var/run/haproxy.pid'])
if not proc.find():
logging.debug("CsLoadBalancer:: will restart HAproxy!")
CsHelper.service("haproxy", "restart")
else:
logging.debug("CsLoadBalancer:: will reload HAproxy!")
CsHelper.service("haproxy", "reload")
add_rules = self.dbag['config'][0]['add_rules']
remove_rules = self.dbag['config'][0]['remove_rules']
stat_rules = self.dbag['config'][0]['stat_rules']
self._configure_firewall(add_rules, remove_rules, stat_rules)
def _configure_firewall(self, add_rules, remove_rules, stat_rules):
firewall = self.config.get_fw()
logging.debug("CsLoadBalancer:: configuring firewall. Add rules ==> %s" % add_rules)
logging.debug("CsLoadBalancer:: configuring firewall. Remove rules ==> %s" % remove_rules)
logging.debug("CsLoadBalancer:: configuring firewall. Stat rules ==> %s" % stat_rules)
for rules in add_rules:
path = rules.split(':')
ip = path[0]
port = path[1]
firewall.append(["filter", "", "-A INPUT -p tcp -m tcp -d %s --dport %s -m state --state NEW -j ACCEPT" % (ip, port)])
for rules in remove_rules:
path = rules.split(':')
ip = path[0]
port = path[1]
firewall.append(["filter", "", "-D INPUT -p tcp -m tcp -d %s --dport %s -m state --state NEW -j ACCEPT" % (ip, port)])
for rules in stat_rules:
path = rules.split(':')
ip = path[0]
port = path[1]
firewall.append(["filter", "", "-A INPUT -p tcp -m tcp -d %s --dport %s -m state --state NEW -j ACCEPT" % (ip, port)])
|
import angr
class GetProcessHeap(angr.SimProcedure):
def run(self):
return 1 # fake heap handle
class HeapCreate(angr.SimProcedure):
def run(self, flOptions, dwInitialSize, dwMaximumSize): #pylint:disable=arguments-differ, unused-argument
return 1 # still a fake heap handle
class HeapAlloc(angr.SimProcedure):
def run(self, HeapHandle, Flags, Size): #pylint:disable=arguments-differ, unused-argument
addr = self.state.heap._malloc(Size)
# conditionally zero the allocated memory
if self.state.solver.solution(Flags & 8, 8):
if isinstance(self.state.heap, angr.SimHeapPTMalloc):
# allocated size might be greater than requested
data_size = self.state.solver.eval_one(
self.state.heap.chunk_from_mem(addr).get_data_size()
)
else:
data_size = self.state.heap._conc_alloc_size(Size)
data = self.state.solver.BVV(0, data_size * 8)
self.state.memory.store(addr, data, size=data_size, condition=Flags & 8 == 8)
return addr
class HeapReAlloc(angr.SimProcedure):
def run(self, hHeap, dwFlags, lpMem, dwBytes): #pylint:disable=arguments-differ, unused-argument
return self.state.heap._realloc(lpMem, dwBytes)
class GlobalAlloc(HeapAlloc):
def run(self, Flags, Size):
return super(GlobalAlloc, self).run(1, Flags, Size)
class HeapFree(angr.SimProcedure):
def run(self, HeapHandle, Flags, lpMem): #pylint:disable=arguments-differ, unused-argument
return 1
|
# Generated by Django 2.2.5 on 2019-11-04 18:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('affiliate_marketing', '0010_brand_vendor_code'),
]
operations = [
migrations.AddField(
model_name='brand',
name='storefront_category',
field=models.CharField(blank=True, default=None, max_length=64, null=True),
),
]
|
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import abc
from typing import (
Any, Dict, Iterator, Optional, Union,
)
from pyhocon import ConfigTree
from databuilder.extractor.base_extractor import Extractor
class ElasticsearchBaseExtractor(Extractor):
"""
Extractor to extract index metadata from Elasticsearch
"""
ELASTICSEARCH_CLIENT_CONFIG_KEY = 'client'
ELASTICSEARCH_EXTRACT_TECHNICAL_DETAILS = 'extract_technical_details'
CLUSTER = 'cluster'
SCHEMA = 'schema'
def __init__(self) -> None:
super(ElasticsearchBaseExtractor, self).__init__()
def init(self, conf: ConfigTree) -> None:
self.conf = conf
self._extract_iter = self._get_extract_iter()
self.es = self.conf.get(ElasticsearchBaseExtractor.ELASTICSEARCH_CLIENT_CONFIG_KEY)
def _get_indexes(self) -> Dict:
result = dict()
try:
_indexes = self.es.indices.get('*')
for k, v in _indexes.items():
if not k.startswith('.'):
result[k] = v
except Exception:
pass
return result
def _get_index_mapping_properties(self, index: Dict) -> Optional[Dict]:
mappings = index.get('mappings', dict())
try:
properties = list(mappings.values())[0].get('properties', dict())
except Exception:
properties = dict()
return properties
def extract(self) -> Any:
try:
result = next(self._extract_iter)
return result
except StopIteration:
return None
@property
def database(self) -> str:
return 'elasticsearch'
@property
def cluster(self) -> str:
return self.conf.get(ElasticsearchBaseExtractor.CLUSTER)
@property
def schema(self) -> str:
return self.conf.get(ElasticsearchBaseExtractor.SCHEMA)
@property
def _extract_technical_details(self) -> bool:
try:
return self.conf.get(ElasticsearchBaseExtractor.ELASTICSEARCH_EXTRACT_TECHNICAL_DETAILS)
except Exception:
return False
@abc.abstractmethod
def _get_extract_iter(self) -> Iterator[Union[Any, None]]:
pass
|
import os, io
from google.cloud import vision
import pandas as pd
from numpy import random
from colormap import rgb2hex
credential_path = '/home/mcw/subha/DSC/dsc_django/app/dl_scripts/gvision_attributes/servicetokenjson.json'
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path
client = vision.ImageAnnotatorClient()
def faces(content):
image = vision.types.Image(content=content)
response1 = client.face_detection(image=image)
faceAnnotations = response1.face_annotations
#likehood = ('Unknown', 'Very Unlikely', 'Unlikely', 'Possibly', 'Likely', 'Very Likely')
print('Faces:')
face = faceAnnotations[0]
df = pd.DataFrame(columns=['Angry', 'Joy', 'Sorrow','Surprised','Headwear','Exposed','Blurred','Confidence'])
df = df.append(
dict(
Angry=face.anger_likelihood*20,
Joy=face.joy_likelihood*20,
Sorrow=face.sorrow_likelihood*20,
Surprised=face.surprise_likelihood*20,
Headwear=face.headwear_likelihood*20,
Exposed=face.under_exposed_likelihood*20,
Blurred=face.blurred_likelihood*20,
Confidence=round(face.detection_confidence,2)*100
), ignore_index=True)
return df
def labels(content):
image = vision.types.Image(content=content)
response3 = client.label_detection(image=image)
labels = response3.label_annotations
df = pd.DataFrame(columns=['description', 'score'])
print("Labels:")
for label in labels:
df = df.append(
dict(
description=label.description,
score=round(label.score,2)*100,
), ignore_index=True)
return df
def object(content):
image = vision.types.Image(content=content)
response = client.object_localization(image=image)
localized_object_annotations = response.localized_object_annotations
df = pd.DataFrame(columns=['name', 'score'])
for obj in localized_object_annotations:
df = df.append(
dict(
name=obj.name,
score=round(obj.score,2)*100
),
ignore_index=True)
return df
def safesearch(content):
image = vision.types.Image(content=content)
response = client.safe_search_detection(image=image)
safe_search = response.safe_search_annotation
df = pd.DataFrame(columns=['Adult', 'Spoof', 'Medical','Violence','Racy'])
df = df.append(
dict(
Adult=safe_search.adult*20,
Spoof=safe_search.spoof*20,
Medical=safe_search.medical*20,
Violence=safe_search.violence*20,
Racy=safe_search.racy*20
), ignore_index=True)
return df
def properties(content):
image = vision.types.Image(content=content)
response2 = client.image_properties(image=image).image_properties_annotation
dominant_colors = response2.dominant_colors
df = pd.DataFrame(columns=['color','score'])
for color in dominant_colors.colors:
hex_value = rgb2hex(int(color.color.red),int(color.color.green),int(color.color.blue))
df = df.append(
dict(
color=hex_value,
score=color.score*100
), ignore_index=True)
return df
def get_gvision(image_path):
with io.open(image_path, 'rb') as image_file:
content = image_file.read()
face_df = faces(content)
label_df = labels(content)
object_df = object(content)
safe_df = safesearch(content)
cloth_color_df = properties(content)
return face_df, label_df, object_df, safe_df, cloth_color_df |
#!/usr/bin/env python3
from argparse import RawTextHelpFormatter, ArgumentParser
from stem.control import Controller
import time
import os
import logging
logger = logging.getLogger(__name__)
def get_controller(addr, port):
cont = Controller.from_port(addr, port)
cont.authenticate()
return cont
def get_is_bootstrapped(cont, timeout=60):
start_time = time.time()
while start_time + timeout > time.time():
line = cont.get_info('status/bootstrap-phase')
state, _, progress, *_ = line.split()
progress = int(progress.split('=')[1])
if state == 'NOTICE' and progress == 100:
logger.debug('Tor is bootstrapped')
return True
time.sleep(1)
logger.debug("Tor didn't bootstrap before timeout. Last line: %s", line)
return False
def get_has_full_consensus(cont, network_size, timeout=60):
start_time = time.time()
while start_time + timeout > time.time():
relays = [r for r in cont.get_network_statuses()]
if len(relays) == network_size:
logger.debug('Tor has correct network size %d',
network_size)
return True
elif len(relays) > network_size:
logger.warning('Tor has more relays than expected. %d vs %d',
len(relays), network_size)
return True
time.sleep(1)
logger.debug('Tor didn\'t reach expected network size %d before '
'timeout', network_size)
return False
def is_tor_ready(addr, port, network_size):
name = '{}:{}'.format(addr, port)
with get_controller(addr, port) as cont:
if not get_is_bootstrapped(cont):
logger.warning('%s not bootstrapped, Tor not ready', name)
return False
if not get_has_full_consensus(cont, network_size):
logger.warning('%s doesn\'t have full consensus, Tor not ready',
name)
return False
logger.info('%s is ready', name)
return True
def extract_control_port_info(torrc_fname):
with open(torrc_fname, 'rt') as fd:
for line in fd:
if 'ControlPort' not in line:
continue
line = line.strip()
info = line.split()[1]
addr, port = info.split(':')
return addr, int(port)
def main(args):
for datadir in args.datadir:
logger.info('Checking if %s is ready', datadir)
addr, port = extract_control_port_info(os.path.join(datadir, 'torrc'))
if not is_tor_ready(addr, port, network_size=args.size):
return 1
# If we got to this point, it seems like every relay is completely ready.
# Do one more check to make sure that's still the case.
for datadir in args.datadir:
logger.info('Verifying %s is still ready', datadir)
addr, port = extract_control_port_info(os.path.join(datadir, 'torrc'))
if not is_tor_ready(addr, port, network_size=args.size):
return 1
return 0
if __name__ == '__main__':
desc = '''
Given the data directories for a local tor network, connect to the control
socket in each directory and verify that the tor on the other end of the socket
is fully bootstrapped and has the right size of consensus.
The "right size of consensus" is determined based on the number of data
directories given to check. If that is not okay to assume (for example, there
are some Tor client [non-relay] data directories given to check), then specify
the size manually with --size.
Waits up to 60 seconds for each check for each tor.
- In the worst case, this script will take a long time to run (if every tor
suddenly passes each check after 59 seconds).
- In the normal failure case, this script will take about 60 seconds to run
(the first tor is not ready and fails its checks).
- In the normal case, it will run very quickly (every tor is bootstrapped and
ready).
Exits with 0 if everything is good. Otherwise exits with a postive integer.
'''
parser = ArgumentParser(
formatter_class=RawTextHelpFormatter, description=desc)
parser.add_argument('-s', '--size', type=int, help='If given, don\'t '
'assume the network size based on the number of '
'datadirs, but use this size instead.')
parser.add_argument('-d', '--debug', action='store_true')
parser.add_argument('datadir', nargs='+', type=str)
args = parser.parse_args()
if args.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.WARNING)
ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
if not args.size:
args.size = len(args.datadir)
try:
exit(main(args))
except KeyboardInterrupt:
pass
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2016-2017 Eugene Frolov <eugene@frolov.net.ru>
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import csv
from datetime import datetime
import time
from helix.dm import models
class TickInfo(object):
def __init__(self, timestamp, ask, bid, ask_volume, bid_volume):
super(TickInfo, self).__init__()
self._timestamp = timestamp
self._ask = float(ask)
self._bid = float(bid)
self._ask_volume = float(ask_volume)
self._bid_volume = float(bid_volume)
@property
def timestamp(self):
return self._timestamp
@property
def ask(self):
return self._ask
@property
def bid(self):
return self._bid
@property
def ask_volume(self):
return self._ask_volume
@property
def bid_volume(self):
return self._bid_volume
class TickStreamReader(object):
def __init__(self, file_path):
super(TickStreamReader, self).__init__()
self._file_path = file_path
self._fp = open(file_path, 'r')
self._reader = csv.DictReader(self._fp)
def stream(self):
for record in self._reader:
dt = datetime.strptime(record['time'] + " UTC",
'%d.%m.%Y %H:%M:%S.%f %Z')
timestamp = round(
time.mktime(dt.timetuple()) + dt.microsecond / 1e6,
3)
yield TickInfo(timestamp=timestamp, ask=record['ask'],
bid=record['bid'], ask_volume=record['ask_volume'],
bid_volume=record['bid_volume'])
def close(self):
self._fp.close()
|
#!/usr/bin/python3
# This file is part of libmodulemd
# Copyright (C) 2017-2018 Stephen Gallagher
#
# Fedora-License-Identifier: MIT
# SPDX-2.0-License-Identifier: MIT
# SPDX-3.0-License-Identifier: MIT
#
# This program is free software.
# For more information on the license, see COPYING.
# For more information on free software, see
# <https://www.gnu.org/philosophy/free-sw.en.html>.
import sys
try:
import unittest
import gi
gi.require_version('Modulemd', '2.0')
from gi.repository import Modulemd
from gi.repository import GLib
except ImportError:
# Return error 77 to skip this test on platforms without the necessary
# python modules
sys.exit(77)
from base import TestBase
import datetime
class TestServiceLevel(TestBase):
def test_constructors(self):
# Test that the new() function works
sl = Modulemd.ServiceLevel.new('foo')
assert sl
assert sl.props.name == 'foo'
assert sl.get_name() == 'foo'
assert sl.get_eol() is None
assert sl.get_eol_as_string() is None
# Test that standard object instatiation works with a name
sl = Modulemd.ServiceLevel(name='foo')
assert sl
assert sl.props.name == 'foo'
assert sl.get_name() == 'foo'
assert sl.get_eol() is None
assert sl.get_eol_as_string() is None
# Test that we fail if we call new() with a None name
try:
sl = Modulemd.ServiceLevel.new(None)
assert False
except TypeError as e:
assert 'does not allow None as a value' in e.__str__()
# Test that we fail if object is instantiated without a name
with self.expect_signal():
sl = Modulemd.ServiceLevel()
# Test that we fail if object is instantiated with a None name
with self.expect_signal():
sl = Modulemd.ServiceLevel(name=None)
def test_copy(self):
sl = Modulemd.ServiceLevel.new('foo')
assert sl
assert sl.props.name == 'foo'
assert sl.get_name() == 'foo'
assert sl.get_eol() is None
assert sl.get_eol_as_string() is None
sl_copy = sl.copy()
assert sl_copy
assert sl_copy.props.name == 'foo'
assert sl_copy.get_name() == 'foo'
assert sl_copy.get_eol() is None
assert sl_copy.get_eol_as_string() is None
sl.set_eol_ymd(2018, 11, 13)
sl_copy = sl.copy()
assert sl_copy
assert sl_copy.props.name == 'foo'
assert sl_copy.get_name() == 'foo'
assert sl_copy.get_eol() is not None
assert sl_copy.get_eol_as_string() == '2018-11-13'
def test_get_name(self):
sl = Modulemd.ServiceLevel.new('foo')
assert sl.get_name() == 'foo'
assert sl.props.name == 'foo'
# This property is not writable, make sure it fails to attempt it
with self.expect_signal():
sl.props.name = 'bar'
def test_get_set_eol(self):
sl = Modulemd.ServiceLevel.new('foo')
if '_overrides_module' in dir(Modulemd):
# Test that EOL is initialized to None
assert sl.get_eol() is None
# Test the set_eol() method
eol = datetime.date(2018, 11, 7)
sl.set_eol(eol)
returned_eol = sl.get_eol()
assert returned_eol is not None
assert returned_eol == eol
assert sl.get_eol_as_string() == '2018-11-07'
# Test the set_eol_ymd() method
sl.set_eol_ymd(2019, 12, 3)
returned_eol = sl.get_eol()
assert returned_eol is not None
assert returned_eol.day == 3
assert returned_eol.month == 12
assert returned_eol.year == 2019
assert sl.get_eol_as_string() == '2019-12-03'
# There is no February 31
sl.set_eol_ymd(2011, 2, 31)
assert sl.get_eol() is None
else:
# Test that EOL is initialized to None
assert sl.get_eol() is None
# Test the set_eol() method
eol = GLib.Date.new_dmy(7, 11, 2018)
sl.set_eol(eol)
returned_eol = sl.get_eol()
assert returned_eol is not None
assert returned_eol.get_day() == eol.get_day()
assert returned_eol.get_month() == eol.get_month()
assert returned_eol.get_year() == eol.get_year()
assert sl.get_eol_as_string() == '2018-11-07'
# Test the set_eol_ymd() method
sl.set_eol_ymd(2019, 12, 3)
returned_eol = sl.get_eol()
assert returned_eol is not None
assert returned_eol.get_day() == 3
assert returned_eol.get_month() == 12
assert returned_eol.get_year() == 2019
assert sl.get_eol_as_string() == '2019-12-03'
# Try setting some invalid dates
# An initialized but unset date
eol = GLib.Date.new()
sl.set_eol(eol)
assert sl.get_eol() is None
# There is no February 31
sl.set_eol_ymd(2011, 2, 31)
assert sl.get_eol() is None
if __name__ == '__main__':
unittest.main()
|
from rect import Rect
from bullet import Bullet
import pygame
#pistol rifle
class Gun(Rect):
Images = { "pistol" : pygame.image.load("images/pistol.png"),
"pistol_two" : pygame.image.load("images/pistol_two.png"),
"rifle" : pygame.image.load("images/rifle.png") }
def __init__(self, damage, bullet_type):
self.damage = damage
self.bullet_type = bullet_type
self.images = { "E" : pygame.transform.rotate(Gun.Images[bullet_type], -90),
"W" : pygame.transform.rotate(Gun.Images[bullet_type], 90),
"N" : pygame.transform.rotate(Gun.Images[bullet_type], 0),
"S" : pygame.transform.rotate(Gun.Images[bullet_type], 180) }
self.sound = pygame.mixer.Sound("sounds/shot.wav")
self.sound.set_volume(0.1)
super(Gun, self).__init__(0, 0, 0, 0)
def draw(self, screen, player):
if player.direction == "E":
#self.width = 20
#self.height = 5
#pygame.draw.rect(screen, (0, 0, 0), (player.x_center + self.width / 2, player.y_center, self.width, self.height))
screen.blit(self.images[player.direction], (player.x + self.images[player.direction].get_width() / 2, player.y))
elif player.direction == "W":
#self.width = 20
#self.height = 5
#pygame.draw.rect(screen, (0, 0, 0), (player.x - self.width / 2, player.y_center, self.width, self.height))
screen.blit(self.images[player.direction], (player.x - self.images[player.direction].get_width() / 2, player.y))
elif player.direction == "N":
#self.width = 5
#self.height = 20
#pygame.draw.rect(screen, (0, 0, 0), (player.x_center, player.y_center - self.height, self.width, self.height))
screen.blit(self.images[player.direction], (player.x, player.y - self.images[player.direction].get_height() / 2 ))
elif player.direction == "S":
#self.width = 5
#self.height = 20
#pygame.draw.rect(screen, (0, 0, 0), (player.x_center, player.y_center + self.height, self.width, self.height))
screen.blit(self.images[player.direction], (player.x, player.y + self.images[player.direction].get_height() / 2))
def shot(self, player):
x_velocity = 0
y_velocity = 0
if player.direction == "E":
x_velocity = 20
y_velocity = 0
elif player.direction == "W":
x_velocity = -20
y_velocity = 0
elif player.direction == "N":
x_velocity = 0
y_velocity = -20
elif player.direction == "S":
x_velocity = 0
y_velocity = 20
Bullet(player.x, player.y, self.damage, x_velocity, y_velocity, self.bullet_type)
self.sound.play() |
from setuptools import setup
setup(name='gamdist',
version='0.1',
description='Generalized Additive Models',
url='http://www.gotinder.com',
author='Bob Wilson, Tinder',
author_email='bob.wilson@gotinder.com',
license='Apache v2.0',
packages=['gamdist'],
install_requires=[
'numpy',
'scipy',
'pickle',
'multiprocessing',
'matplotlib',
'cvxpy',
'math'
],
zip_safe=False)
|
#!/usr/bin/env python3
import argparse
import numpy as np
from mapTools import *
from utilities import writeLog
from plotTools import addImagePlot
import matplotlib.pyplot as plt
import sys
'''
Description:
Author: Mikko Auvinen & Jukka-Pekka Keskinen
mikko.auvinen@fmi.fi
Finnish Meteorological Institute
'''
#==========================================================#
dscStr = '''Refine or coarsen a raster. When coarsening, the new value will be
the mean of the corresponding cells in the fine raster unless specified otherwise.
NB! Does not work properly if raster contains missing values or NaNs.
'''
parser = argparse.ArgumentParser(prog='refineTileResolution.py',\
description=dscStr)
parser.add_argument("-f", "--filename",type=str, help="Name of the .npz data file.")
parser.add_argument("-fo", "--fileout",type=str,\
help="Name of output Palm/npz topography file.")
parser.add_argument("-N","--refn", type=float,\
help="Refinement factor N in 2^N. Negative value coarsens.")
parser.add_argument("-m", "--mode", action="store_true", default=False,\
help="When coarsening, select the most common value (mode) from the finer grid.")
parser.add_argument("-i", "--integer", action="store_true", default=False,\
help="Output an integer array. Default is a float array.")
parser.add_argument("-p", "--printOn", action="store_true", default=False, \
help="Print the resulting raster data.")
parser.add_argument("-pp", "--printOnly", action="store_true", default=False, \
help="Only print the resulting data. Don't save.")
args = parser.parse_args()
writeLog( parser, args, args.printOnly )
#==========================================================#
# Renaming ... nothing else
filename = args.filename
N = args.refn
printOn = args.printOn
printOnly = args.printOnly
fileout = args.fileout
mode = args.mode
ints = args.integer
Rdict = readNumpyZTile( filename )
R1 = Rdict['R']
if( N < 0. ):
# Take precaution if coarsening and the original raster has an odd numbered dimension.
nN, nE = R1.shape
eN = None; eE = None
if( np.mod( nN, 2 ) != 0 ): eN = -1
if( np.mod( nE, 2 ) != 0 ): eE = -1
if( eN is not None or eE is not None ): R1 = R1[:eN,:eE]
R1dims = np.array(np.shape(R1))
print(' R1dims = {}'.format(R1dims))
R1Orig = Rdict['GlobOrig'].astype(float)
dPx1 = Rdict['dPx']
gridRot1 = Rdict['gridRot']
if ints:
Rtype = int
else:
Rtype = float
# Resolution ratio (rr).
rr = 2**N
# Create the index arrays. The dims are always according to the larger one.
if( N > 0. ):
dr1 = rr; fr2 = 1 # dr1 > 1
maxDims = dr1 * R1dims # Refinement, R2dims > R1dims
R2dims = maxDims.astype(int)
s2 = 1. # Scale factor. If we refine, the R1 values always fill a new zero cell, see below.
n1,e1 = np.ogrid[ 0:maxDims[0] , 0:maxDims[1] ] # northing, easting
n2,e2 = np.ogrid[ 0:maxDims[0] , 0:maxDims[1] ] # northing, easting
else:
dr1 = 1; fr2 = rr # fr2 < 1
R2dims = np.round(rr * R1dims).astype(int); print(' Coarser dims = {}'.format(R2dims))
s2 = (2**(2*N)) # Scale factor. If we coarsen, the R1 values are appended. Same value to 2^2n cells.
n1 = np.arange(R1dims[0]); e1 = np.arange(R1dims[1])
n2 = np.arange(R1dims[0]); e2 = np.arange(R1dims[1])
# Modify the integer list for refining/coarsening
n1= (n1/dr1).astype(int); e1=(e1/dr1).astype(int)
#n2 = np.round(n2*fr2, decimals=2); e2 = np.round(e2*fr2, decimals=2)
n2 = np.floor((n2+0.5)*fr2).astype(int); e2 = np.floor((e2+0.5)*fr2).astype(int)
#print(' n2 = {} '.format(n2))
#print(' n1 = {} '.format(n1))
np.savetxt('n2.dat', n2, fmt='%g')
#np.savetxt('n1.dat', n1, fmt='%g')
if( N > 0 ):
R2 = np.zeros( R2dims, Rtype ) # Create the output array.
R2[n2, e2] += R1[n1,e1]
elif np.isclose(np.around(1/s2),1/s2,0.001):
n2 = np.minimum( n2 , R2dims[0]-1)
e2 = np.minimum( e2 , R2dims[1]-1)
if mode:
R2=slowCoarsen(R1,R2dims,s2,n1,n2,e1,e2,Rtype)
else:
R2=fastCoarsen(R1,R2dims,s2,n1,n2,e1,e2,Rtype)
else:
sys.exit("ERROR: Attempting to coarsen with an incompatible refinement factor. Exiting.")
#print(' TL:{} TR:{} BL:{} BR:{} '.format( R2[0,0], R2[0,-1], R2[-1,0], R2[-1,-1]))
#print(' TL+1:{} TR+1:{} BL+1:{} BR+1:{} '.format( R2[1,0], R2[1,-1], R2[-1,1], R2[-1,-2]))
# NOTE! The global origin is the coordinate of the top left cell center.
# Therefore, it must be shifted by in accordance to the top left cc's new location.
R1 = None
Rdict['R'] = R2.astype(Rtype)
# Select the smaller delta
dPx2 = dPx1/rr
dPm = np.minimum( np.abs(dPx1), np.abs(dPx2) ) # np.abs() just in case negative dPx values sneak in.
dPm[1] = -1.*np.abs( dPm[1] ) # Set dE negative for the offset operation
# Offset the new cell-center origo
# Refine: +dN, -dE
# Coarsen: -dN, +dE
R2Orig = R1Orig.copy()
R2Orig += np.sign(N)*(2.**np.abs(N) - 1.) * (dPm/2.) # N<0 coarsens, N>0 refines
# Rotate the newly shifted global origin to the global coord. system using the R1Orig as pivot.
R2Orig = rotatePoint(R1Orig, R2Orig, gridRot1)
print(' Old Origin = {} vs.\n New Origin = {}'.format(R1Orig, R2Orig))
Rdict['GlobOrig'] = R2Orig
Rdict['dPx'] = dPx2
if( not args.printOnly ):
saveTileAsNumpyZ( fileout, Rdict )
if( args.printOn or args.printOnly ):
fig = plt.figure(num=1, figsize=(9.,9.))
fig = addImagePlot( fig, R2 , fileout )
plt.show()
|
# Compare Algorithms
from pandas import read_csv
from matplotlib import pyplot
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import LogisticRegressionCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
# load dataset
filename = 'test_data.csv'
names = ['a', 'b', 'c', 'd', 'tag']
dataframe = read_csv(filename, names=names,header=0)
array = dataframe.values
X = array[:,0:4]
Y = array[:,4]
Y = Y.astype('bool')
# prepare models
models = []
models.append(('LR', LogisticRegression()))
models.append(('LRCV', LogisticRegressionCV()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
models.append(('RFC', RandomForestClassifier(n_estimators=100, n_jobs=-1)))
models.append(('SVM', SVC()))
# evaluate each model in turn
results = []
names = []
scoring = 'accuracy'
for name, model in models:
kfold = KFold(n_splits=10, random_state=7)
cv_results = cross_val_score(model, X, Y, cv=kfold, scoring=scoring)
results.append(cv_results)
names.append(name)
msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
print(msg)
# # boxplot algorithm comparison
# fig = pyplot.figure()
# fig.suptitle('Algorithm Comparison')
# ax = fig.add_subplot(111)
# pyplot.boxplot(results)
# ax.set_xticklabels(names)
# pyplot.show() |
import giphypop
import random
class Giphy(object):
def __init__(self):
self.g = giphypop.Giphy(api_key="dc6zaTOxFJmzC")
def search(self, text):
results = [x for x in self.g.search(text)]
im = random.choice(results)
return im.media_url |
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch.autograd import Variable
from min_norm_solvers import MinNormSolver
from utils import calc_gradients, circle_points, model_from_dataset, reset_weights
from ..base import BaseMethod
def get_d_paretomtl_init(grads, losses, preference_vectors, pref_idx):
"""
calculate the gradient direction for ParetoMTL initialization
Args:
grads: flattened gradients for each task
losses: values of the losses for each task
preference_vectors: all preference vectors u
pref_idx: which index of u we are currently using
Returns:
flag: is a feasible initial solution found?
weight:
"""
flag = False
nobj = losses.shape
# check active constraints, Equation 7
current_pref = preference_vectors[pref_idx] # u_k
w = preference_vectors - current_pref # (u_j - u_k) \forall j = 1, ..., K
gx = torch.matmul(w,losses/torch.norm(losses)) # In the paper they do not normalize the loss
idx = gx > 0 # I(\theta), i.e the indexes of the active constraints
active_constraints = w[idx] # constrains which are violated, i.e. gx > 0
# calculate the descent direction
if torch.sum(idx) <= 0:
flag = True
return flag, torch.zeros(nobj)
if torch.sum(idx) == 1:
sol = torch.ones(1).cuda().float()
else:
# Equation 9
# w[idx] = set of active constraints, i.e. where the solution is closer to another preference vector than the one desired.
gx_gradient = torch.matmul(active_constraints, grads) # We need to take the derivatives of G_j which is w.dot(grads)
sol, nd = MinNormSolver.find_min_norm_element([[gx_gradient[t]] for t in range(len(gx_gradient))])
sol = torch.Tensor(sol).cuda()
# from MinNormSolver we get the weights (alpha) for each gradient. But we need the weights for the losses?
weight = torch.matmul(sol, active_constraints)
return flag, weight
def get_d_paretomtl(grads, losses, preference_vectors, pref_idx):
"""
calculate the gradient direction for ParetoMTL
Args:
grads: flattened gradients for each task
losses: values of the losses for each task
preference_vectors: all preference vectors u
pref_idx: which index of u we are currently using
"""
# check active constraints
current_weight = preference_vectors[pref_idx]
rest_weights = preference_vectors
w = rest_weights - current_weight
gx = torch.matmul(w,losses/torch.norm(losses))
idx = gx > 0
# calculate the descent direction
if torch.sum(idx) <= 0:
# here there are no active constrains in gx
sol, nd = MinNormSolver.find_min_norm_element_FW([[grads[t]] for t in range(len(grads))])
return torch.tensor(sol).cuda().float()
else:
# we have active constraints, i.e. we have move too far away from out preference vector
#print('optim idx', idx)
vec = torch.cat((grads, torch.matmul(w[idx],grads)))
sol, nd = MinNormSolver.find_min_norm_element([[vec[t]] for t in range(len(vec))])
sol = torch.Tensor(sol).cuda()
# FIX: handle more than just 2 objectives
n = preference_vectors.shape[1]
weights = []
for i in range(n):
weight_i = sol[i] + torch.sum(torch.stack([sol[j] * w[idx][j - n , i] for j in torch.arange(n, n + torch.sum(idx))]))
weights.append(weight_i)
# weight0 = sol[0] + torch.sum(torch.stack([sol[j] * w[idx][j - 2 ,0] for j in torch.arange(2, 2 + torch.sum(idx))]))
# weight1 = sol[1] + torch.sum(torch.stack([sol[j] * w[idx][j - 2 ,1] for j in torch.arange(2, 2 + torch.sum(idx))]))
# weight = torch.stack([weight0,weight1])
weight = torch.stack(weights)
return weight
class ParetoMTLMethod(BaseMethod):
def __init__(self, objectives, num_starts, **kwargs):
assert len(objectives) <= 2
self.objectives = objectives
self.num_pareto_points = num_starts
self.init_solution_found = False
self.model = model_from_dataset(method='paretoMTL', **kwargs).cuda()
self.pref_idx = -1
# the original ref_vec can be obtained by circle_points(self.num_pareto_points, min_angle=0.0, max_angle=0.5 * np.pi)
# we use the same min angle / max angle as for the other methods for comparison.
self.ref_vec = torch.Tensor(circle_points(self.num_pareto_points)).cuda().float()
def new_epoch(self, e):
if e == 0:
# we're restarting
self.pref_idx += 1
reset_weights(self.model)
self.init_solution_found = False
self.e = e
self.model.train()
def log(self):
return {"train_ray": self.ref_vec[self.pref_idx].cpu().numpy().tolist()}
def _find_initial_solution(self, batch):
grads = {}
losses_vec = []
# obtain and store the gradient value
for i in range(len(self.objectives)):
self.model.zero_grad()
batch.update(self.model(batch))
task_loss = self.objectives[i](**batch)
losses_vec.append(task_loss.data)
task_loss.backward()
grads[i] = []
# can use scalable method proposed in the MOO-MTL paper for large scale problem
# but we keep use the gradient of all parameters in this experiment
private_params = self.model.private_params() if hasattr(self.model, 'private_params') else []
for name, param in self.model.named_parameters():
if name not in private_params and param.grad is not None:
grads[i].append(Variable(param.grad.data.clone().flatten(), requires_grad=False))
grads_list = [torch.cat([g for g in grads[i]]) for i in range(len(grads))]
grads = torch.stack(grads_list)
# calculate the weights
losses_vec = torch.stack(losses_vec)
self.init_solution_found, weight_vec = get_d_paretomtl_init(grads, losses_vec, self.ref_vec, self.pref_idx)
if self.init_solution_found:
print("Initial solution found")
# optimization step
self.model.zero_grad()
for i in range(len(self.objectives)):
batch.update(self.model(batch))
task_loss = self.objectives[i](**batch)
if i == 0:
loss_total = weight_vec[i] * task_loss
else:
loss_total = loss_total + weight_vec[i] * task_loss
loss_total.backward()
return loss_total.item()
def step(self, batch):
if self.e < 2 and not self.init_solution_found:
# run at most 2 epochs to find the initial solution
# stop early once a feasible solution is found
# usually can be found with a few steps
return self._find_initial_solution(batch)
else:
# run normal update
gradients, obj_values = calc_gradients(batch, self.model, self.objectives)
grads = [torch.cat([torch.flatten(v) for k, v in sorted(grads.items())]) for grads in gradients]
grads = torch.stack(grads)
# calculate the weights
losses_vec = torch.Tensor(obj_values).cuda()
weight_vec = get_d_paretomtl(grads, losses_vec, self.ref_vec, self.pref_idx)
normalize_coeff = len(self.objectives) / torch.sum(torch.abs(weight_vec))
weight_vec = weight_vec * normalize_coeff
# optimization step
loss_total = None
for a, objective in zip(weight_vec, self.objectives):
logits = self.model(batch)
batch.update(logits)
task_loss = objective(**batch)
loss_total = a * task_loss if not loss_total else loss_total + a * task_loss
loss_total.backward()
return loss_total.item()
# private_params = self.model.private_params() if hasattr(self.model, 'private_params') else []
# for name, param in self.model.named_parameters():
# if name not in private_params:
# param.grad.data.zero_()
# param.grad = sum(weight_vec[o] * gradients[o][name] for o in range(len(self.objectives))).cuda()
def eval_step(self, batch):
self.model.eval()
return [self.model(batch)] |
from django.shortcuts import render
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.decorators import login_required
from myapp.models.schema_file import *
def solve7(time, submitted_answer, original_answer):
if time == '':
return False
if time == '0' or int(time) > 10 :
return False;
return submitted_answer == 'across, after, among, any, are, because, but, can, cannot, could, did, either, else, ever, every, from, get, got, had, his, how, into, likely, must, not, off, other, own, rather, said, say, says, she, than, the, their, then, there, this, wants, was, was, what, when, where, while, will, with, yet, you' |
from argparse import ArgumentParser
class CmdLineTool:
def __init__(self, description):
self.description = description
self._initializeOptParser()
def _initializeOptParser(self):
self.argParser = ArgumentParser(description = self.description)
def run(self):
"""
Run the tool. Call this function after all additional
arguments have been provided
"""
self._parseCommandLine()
self._runImpl()
# @Override
def _runImpl(self):
pass
def _parseCommandLine(self):
self.args = self.argParser.parse_args()
def _usage(self):
self.argParser.print_help()
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# This module implements the base CCDData class.
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from astropy.io import fits
from astropy.tests.helper import pytest
from astropy.nddata import StdDevUncertainty
from astropy import units as u
from ..ccddata import CCDData
def test_ccddata_empty():
with pytest.raises(TypeError):
CCDData() # empty initializer should fail
def test_ccddata_must_have_unit():
with pytest.raises(ValueError):
CCDData(np.zeros([100, 100]))
@pytest.mark.data_size(10)
def test_ccddata_simple(ccd_data):
assert ccd_data.shape == (10, 10)
assert ccd_data.size == 100
assert ccd_data.dtype == np.dtype(float)
def test_ccddata_init_with_string_electron_unit():
ccd = CCDData(np.zeros((10, 10)), unit="electron")
assert ccd.unit is u.electron
@pytest.mark.data_size(10)
def test_initialize_from_FITS(ccd_data, tmpdir):
hdu = fits.PrimaryHDU(ccd_data)
hdulist = fits.HDUList([hdu])
filename = tmpdir.join('afile.fits').strpath
hdulist.writeto(filename)
cd = CCDData.read(filename, unit=u.electron)
assert cd.shape == (10, 10)
assert cd.size == 100
assert np.issubdtype(cd.data.dtype, np.float)
for k, v in hdu.header.items():
assert cd.meta[k] == v
def test_initialize_from_fits_with_unit_in_header(tmpdir):
fake_img = np.random.random(size=(100, 100))
hdu = fits.PrimaryHDU(fake_img)
hdu.header['bunit'] = u.adu.to_string()
filename = tmpdir.join('afile.fits').strpath
hdu.writeto(filename)
ccd = CCDData.read(filename)
# ccd should pick up the unit adu from the fits header...did it?
assert ccd.unit is u.adu
# An explicit unit in the read overrides any unit in the FITS file
ccd2 = CCDData.read(filename, unit="photon")
assert ccd2.unit is u.photon
def test_initialize_from_FITS_bad_keyword_raises_error(ccd_data, tmpdir):
# There are two fits.open keywords that are not permitted in ccdpro:
# do_not_scale_image_data and scale_back
filename = tmpdir.join('test.fits').strpath
ccd_data.write(filename)
with pytest.raises(TypeError):
CCDData.read(filename, unit=ccd_data.unit,
do_not_scale_image_data=True)
with pytest.raises(TypeError):
CCDData.read(filename, unit=ccd_data.unit, scale_back=True)
def test_ccddata_writer(ccd_data, tmpdir):
filename = tmpdir.join('test.fits').strpath
ccd_data.write(filename)
ccd_disk = CCDData.read(filename, unit=ccd_data.unit)
np.testing.assert_array_equal(ccd_data.data, ccd_disk.data)
def test_ccddata_meta_is_case_insensitive(ccd_data):
key = 'SoMeKEY'
ccd_data.meta[key] = 10
assert key.lower() in ccd_data.meta
assert key.upper() in ccd_data.meta
def test_ccddata_meta_is_not_fits_header(ccd_data):
ccd_data.meta = {'OBSERVER': 'Edwin Hubble'}
assert not isinstance(ccd_data.meta, fits.Header)
def test_fromMEF(ccd_data, tmpdir):
hdu = fits.PrimaryHDU(ccd_data)
hdu2 = fits.PrimaryHDU(2 * ccd_data.data)
hdulist = fits.HDUList(hdu)
hdulist.append(hdu2)
filename = tmpdir.join('afile.fits').strpath
hdulist.writeto(filename)
# by default, we reading from the first extension
cd = CCDData.read(filename, unit=u.electron)
np.testing.assert_array_equal(cd.data, ccd_data.data)
# but reading from the second should work too
cd = CCDData.read(filename, hdu=1, unit=u.electron)
np.testing.assert_array_equal(cd.data, 2 * ccd_data.data)
def test_metafromheader(ccd_data):
hdr = fits.header.Header()
hdr['observer'] = 'Edwin Hubble'
hdr['exptime'] = '3600'
d1 = CCDData(np.ones((5, 5)), meta=hdr, unit=u.electron)
assert d1.meta['OBSERVER'] == 'Edwin Hubble'
assert d1.header['OBSERVER'] == 'Edwin Hubble'
def test_metafromdict():
dic = {'OBSERVER': 'Edwin Hubble', 'EXPTIME': 3600}
d1 = CCDData(np.ones((5, 5)), meta=dic, unit=u.electron)
assert d1.meta['OBSERVER'] == 'Edwin Hubble'
def test_header2meta():
hdr = fits.header.Header()
hdr['observer'] = 'Edwin Hubble'
hdr['exptime'] = '3600'
d1 = CCDData(np.ones((5, 5)), unit=u.electron)
d1.header = hdr
assert d1.meta['OBSERVER'] == 'Edwin Hubble'
assert d1.header['OBSERVER'] == 'Edwin Hubble'
def test_metafromstring_fail():
hdr = 'this is not a valid header'
with pytest.raises(TypeError):
CCDData(np.ones((5, 5)), meta=hdr)
def test_setting_bad_uncertainty_raises_error(ccd_data):
with pytest.raises(TypeError):
# Uncertainty is supposed to be an instance of NDUncertainty
ccd_data.uncertainty = 10
def test_setting_uncertainty_with_array(ccd_data):
ccd_data.uncertainty = None
fake_uncertainty = np.sqrt(np.abs(ccd_data.data))
ccd_data.uncertainty = fake_uncertainty.copy()
np.testing.assert_array_equal(ccd_data.uncertainty.array, fake_uncertainty)
def test_setting_uncertainty_wrong_shape_raises_error(ccd_data):
with pytest.raises(ValueError):
ccd_data.uncertainty = np.random.random(size=2 * ccd_data.shape)
def test_to_hdu(ccd_data):
ccd_data.meta = {'observer': 'Edwin Hubble'}
fits_hdulist = ccd_data.to_hdu()
assert isinstance(fits_hdulist, fits.HDUList)
for k, v in ccd_data.meta.items():
assert fits_hdulist[0].header[k] == v
np.testing.assert_array_equal(fits_hdulist[0].data, ccd_data.data)
def test_to_hdu_long_metadata_item(ccd_data):
# There is no attempt to try to handle the general problem of
# a long keyword (that requires HIERARCH) with a long string value
# (that requires CONTINUE).
# However, a long-ish keyword with a long value can happen because of
# auto-logging, and we are supposed to handle that.
# So, a nice long command:
from ..core import subtract_dark, _short_names
dark = CCDData(np.zeros_like(ccd_data.data), unit="adu")
result = subtract_dark(ccd_data, dark, dark_exposure=30 * u.second,
data_exposure=15 * u.second, scale=True)
assert 'subtract_dark' in result.header
hdulist = result.to_hdu()
header = hdulist[0].header
assert header['subtract_dark'] == _short_names['subtract_dark']
args_value = header[_short_names['subtract_dark']]
# Yuck -- have to hand code the ".0" to the numbers to get this to pass...
assert "dark_exposure={0} {1}".format(30.0, u.second) in args_value
assert "data_exposure={0} {1}".format(15.0, u.second) in args_value
assert "scale=True" in args_value
def test_copy(ccd_data):
ccd_copy = ccd_data.copy()
np.testing.assert_array_equal(ccd_copy.data, ccd_data.data)
assert ccd_copy.unit == ccd_data.unit
assert ccd_copy.meta == ccd_data.meta
@pytest.mark.parametrize('operation,affects_uncertainty', [
("multiply", True),
("divide", True),
])
@pytest.mark.parametrize('operand', [
2.0,
2 * u.dimensionless_unscaled,
2 * u.photon / u.adu,
])
@pytest.mark.parametrize('with_uncertainty', [
True,
False])
@pytest.mark.data_unit(u.adu)
def test_mult_div_overload(ccd_data, operand, with_uncertainty,
operation, affects_uncertainty):
if with_uncertainty:
ccd_data.uncertainty = StdDevUncertainty(np.ones_like(ccd_data))
method = ccd_data.__getattribute__(operation)
np_method = np.__getattribute__(operation)
result = method(operand)
assert result is not ccd_data
assert isinstance(result, CCDData)
assert (result.uncertainty is None or
isinstance(result.uncertainty, StdDevUncertainty))
try:
op_value = operand.value
except AttributeError:
op_value = operand
np.testing.assert_array_equal(result.data,
np_method(ccd_data.data, op_value))
if with_uncertainty:
if affects_uncertainty:
np.testing.assert_array_equal(result.uncertainty.array,
np_method(ccd_data.uncertainty.array,
op_value))
else:
np.testing.assert_array_equal(result.uncertainty.array,
ccd_data.uncertainty.array)
else:
assert result.uncertainty is None
if isinstance(operand, u.Quantity):
# Need the "1 *" below to force arguments to be Quantity to work around
# astropy/astropy#2377
expected_unit = np_method(1 * ccd_data.unit, 1 * operand.unit).unit
assert result.unit == expected_unit
else:
assert result.unit == ccd_data.unit
@pytest.mark.parametrize('operation,affects_uncertainty', [
("add", False),
("subtract", False),
])
@pytest.mark.parametrize('operand,expect_failure', [
(2.0, u.UnitsError), # fail--units don't match image
(2 * u.dimensionless_unscaled, u.UnitsError), # same
(2 * u.adu, False),
])
@pytest.mark.parametrize('with_uncertainty', [
True,
False])
@pytest.mark.data_unit(u.adu)
def test_add_sub_overload(ccd_data, operand, expect_failure, with_uncertainty,
operation, affects_uncertainty):
if with_uncertainty:
ccd_data.uncertainty = StdDevUncertainty(np.ones_like(ccd_data))
method = ccd_data.__getattribute__(operation)
np_method = np.__getattribute__(operation)
if expect_failure:
with pytest.raises(expect_failure):
result = method(operand)
return
else:
result = method(operand)
assert result is not ccd_data
assert isinstance(result, CCDData)
assert (result.uncertainty is None or
isinstance(result.uncertainty, StdDevUncertainty))
try:
op_value = operand.value
except AttributeError:
op_value = operand
np.testing.assert_array_equal(result.data,
np_method(ccd_data.data, op_value))
if with_uncertainty:
if affects_uncertainty:
np.testing.assert_array_equal(result.uncertainty.array,
np_method(ccd_data.uncertainty.array,
op_value))
else:
np.testing.assert_array_equal(result.uncertainty.array,
ccd_data.uncertainty.array)
else:
assert result.uncertainty is None
if isinstance(operand, u.Quantity):
assert (result.unit == ccd_data.unit and result.unit == operand.unit)
else:
assert result.unit == ccd_data.unit
def test_arithmetic_overload_fails(ccd_data):
with pytest.raises(TypeError):
ccd_data.multiply("five")
with pytest.raises(TypeError):
ccd_data.divide("five")
with pytest.raises(TypeError):
ccd_data.add("five")
with pytest.raises(TypeError):
ccd_data.subtract("five")
def test_arithmetic_overload_ccddata_operand(ccd_data):
ccd_data.uncertainty = StdDevUncertainty(np.ones_like(ccd_data))
operand = ccd_data.copy()
result = ccd_data.add(operand)
assert len(result.meta) == 0
np.testing.assert_array_equal(result.data,
2 * ccd_data.data)
np.testing.assert_array_equal(result.uncertainty.array,
np.sqrt(2) * ccd_data.uncertainty.array)
result = ccd_data.subtract(operand)
assert len(result.meta) == 0
np.testing.assert_array_equal(result.data,
0 * ccd_data.data)
np.testing.assert_array_equal(result.uncertainty.array,
np.sqrt(2) * ccd_data.uncertainty.array)
result = ccd_data.multiply(operand)
assert len(result.meta) == 0
np.testing.assert_array_equal(result.data,
ccd_data.data ** 2)
expected_uncertainty = (np.sqrt(2) * np.abs(ccd_data.data) *
ccd_data.uncertainty.array)
np.testing.assert_allclose(result.uncertainty.array,
expected_uncertainty)
result = ccd_data.divide(operand)
assert len(result.meta) == 0
np.testing.assert_array_equal(result.data,
np.ones_like(ccd_data.data))
expected_uncertainty = (np.sqrt(2) / np.abs(ccd_data.data) *
ccd_data.uncertainty.array)
np.testing.assert_allclose(result.uncertainty.array,
expected_uncertainty)
|
import numpy as np
from ...utils import box_utils
from ..dataset import DatasetTemplate as Dataset
def transform_annotations_to_kitti_format(annos, map_name_to_kitti=None, info_with_fakelidar=False, **kwargs):
"""
Args:
annos:
map_name_to_kitti: dict, map name to KITTI names (Car, Pedestrian, Cyclist)
info_with_fakelidar:
Returns:
"""
for anno in annos:
if 'name' not in anno:
anno['name'] = anno['gt_names']
anno.pop('gt_names')
for k in range(anno['name'].shape[0]):
if anno['name'][k] in map_name_to_kitti:
anno['name'][k] = map_name_to_kitti[anno['name'][k]]
else:
anno['name'][k] = 'Person_sitting'
if 'boxes_lidar' in anno:
gt_boxes_lidar = anno['boxes_lidar'].copy()
elif 'gt_boxes_lidar' in anno:
gt_boxes_lidar = anno['gt_boxes_lidar'].copy()
else:
gt_boxes_lidar = anno['gt_boxes'].copy()
# filter by fov
if kwargs.get('is_gt', None) and kwargs.get('GT_FILTER', None):
if kwargs.get('FOV_FILTER', None):
gt_boxes_lidar = filter_by_fov(anno, gt_boxes_lidar, kwargs)
# filter by range
if kwargs.get('GT_FILTER', None) and kwargs.get('RANGE_FILTER', None):
point_cloud_range = kwargs['RANGE_FILTER']
gt_boxes_lidar = filter_by_range(anno, gt_boxes_lidar, point_cloud_range, kwargs['is_gt'])
if kwargs.get('GT_FILTER', None):
anno['gt_boxes_lidar'] = gt_boxes_lidar
anno['bbox'] = np.zeros((len(anno['name']), 4))
anno['bbox'][:, 2:4] = 50 # [0, 0, 50, 50]
anno['truncated'] = np.zeros(len(anno['name']))
anno['occluded'] = np.zeros(len(anno['name']))
if len(gt_boxes_lidar) > 0:
if info_with_fakelidar:
gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(gt_boxes_lidar)
gt_boxes_lidar[:, 2] -= gt_boxes_lidar[:, 5] / 2
anno['location'] = np.zeros((gt_boxes_lidar.shape[0], 3))
anno['location'][:, 0] = -gt_boxes_lidar[:, 1] # x = -y_lidar
anno['location'][:, 1] = -gt_boxes_lidar[:, 2] # y = -z_lidar
anno['location'][:, 2] = gt_boxes_lidar[:, 0] # z = x_lidar
dxdydz = gt_boxes_lidar[:, 3:6]
anno['dimensions'] = dxdydz[:, [0, 2, 1]] # lwh ==> lhw
anno['rotation_y'] = -gt_boxes_lidar[:, 6] - np.pi / 2.0
anno['alpha'] = -np.arctan2(-gt_boxes_lidar[:, 1], gt_boxes_lidar[:, 0]) + anno['rotation_y']
else:
anno['location'] = anno['dimensions'] = np.zeros((0, 3))
anno['rotation_y'] = anno['alpha'] = np.zeros(0)
return annos
def filter_by_range(anno, gt_boxes_lidar, point_cloud_range, is_gt):
mask = box_utils.mask_boxes_outside_range_numpy(
gt_boxes_lidar, point_cloud_range, min_num_corners=1
)
gt_boxes_lidar = gt_boxes_lidar[mask]
anno['name'] = anno['name'][mask]
if not is_gt:
anno['score'] = anno['score'][mask]
anno['pred_labels'] = anno['pred_labels'][mask]
return gt_boxes_lidar
def filter_by_fov(anno, gt_boxes_lidar, kwargs):
fov_gt_flag = Dataset.extract_fov_gt(
gt_boxes_lidar, kwargs['FOV_DEGREE'], kwargs['FOV_ANGLE']
)
gt_boxes_lidar = gt_boxes_lidar[fov_gt_flag]
anno['name'] = anno['name'][fov_gt_flag]
return gt_boxes_lidar
|
from apiclient import errors
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from email.message import EmailMessage
import base64
import time
from lib.debugging import *
from lib.utils import *
def get_service(token_path):
store = file.Storage(token_path)
creds = store.get()
if not creds or creds.invalid:
return None
else:
return build('gmail', 'v1', http=creds.authorize(Http()))
def format_info_message_body(expected_count, actual_count):
s = config_get_message_bodies()["info"].replace("{0}", str(actual_count))
s = s.replace("{1}", str(expected_count))
return s
def format_test_message_body():
epoch = str(int(time.time()))
return config_get_message_bodies()["test"].replace("{0}", epoch)
def create_message(info=False, expected_count=None, actual_count=None):
msg = EmailMessage()
if info:
msg['To'] = config_get_receiver_info_email()
msg['Subject'] = config_get_subjects()["info"]
msg.set_content(format_info_message_body(expected_count, actual_count))
else:
msg['To'] = config_get_receiver_email()
msg['Subject'] = config_get_subjects()["test"]
msg.set_content(format_test_message_body())
msg['From'] = config_get_sender_gmail()
return {'raw': base64.urlsafe_b64encode(msg.as_string().encode()).decode()}
def send_message(service, message, type_prefix):
try:
message = (service.users().messages().send(userId='me', body=message).execute())
print_message("Sending message ID: {id}".format(id=message['id']), type_prefix, "verbose")
return message
except errors.HttpError as e:
print_message("An error occurred: {error}".format(error=e), type_prefix, "error")
print_message("Please check the email addresses entered in user_config.json", type_prefix, "error")
raise e
|
from gen import *
from dataset import *
import numpy as np
from fg import Foreground, FGTextureType
def save_to_file(npy_file_name, n_examples, dataset, use_patch_centers=False, e=16):
np_data = np.array(np.zeros(e**2))
np_targets = np.array(np.zeros(1))
if use_patch_centers:
np_patch_centers = np.array(np.zeros(64))
n_count = 0
for data in dataset:
if n_count == n_examples:
break
np_data = np.vstack((np_data, data[0]))
np_targets = np.vstack((np_targets, data[1]))
if use_patch_centers:
np_patch_centers = np.vstack((np_patch_centers, data[2]))
n_count+=1
np_data = np_data[1:]
np_data.dtype = np.float32
np_targets = np_targets[1:]
np_targets.dtype = np.uint8
if use_patch_centers:
np_patch_centers = np_patch_centers[1:]
np_patch_centers.dtype = np.int8
np_dataset = np.array([np_data, np_targets, np_patch_centers])
else:
np_dataset = np.array([np_data, np_targets])
print "Converted %s to a numpy array." % npy_file_name
np.save(npy_file_name, np_dataset)
if __name__=="__main__":
# TETROMINO
fg = Foreground(size=(16, 16), texture_type=FGTextureType.PlainBin)
texture = fg.generate_texture()
# PENTOMINO
pentomino_gen = lambda w, h: TwoGroups("pentl/pentn/pentp/pentf/penty/pentj/pentn2/pentq/pentf2/penty2",
2020, w, h,
use_patch_centers=True,
n1 = 1, n2 = 2, rot = True,
patch_size=(16, 16),
texture=texture, scale=True, task = 4)
pentomino = lambda w, h: SpritePlacer(pentomino_gen(w, h), collision_check=True, enable_perlin=False)
pentomino64x64 = pentomino(64, 64)
pentomino_dir = "/data/lisa/data/pentomino/"
pentomino64x64_raw = pentomino_dir + "pentomino64x64_300_presence.npy"
print "Started saving pentomino64x64"
no_of_examples = 300
save_to_file(pentomino64x64_raw, no_of_examples, pentomino64x64,
use_patch_centers=True, e=64)
|
# -*- coding: utf-8 -*-
###############################################################
# Author: patrice.ponchant@furgo.com (Fugro Brasil) #
# Created: 17/12/2020 #
# Python : 3.x #
###############################################################
# The future package will provide support for running your code on Python 2.6, 2.7, and 3.3+ mostly unchanged.
# http://python-future.org/quickstart.html
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
##### For the basic function #####
import datetime
import sys
import glob
import os
import math
from xml.etree.ElementTree import TreeBuilder
import pandas as pd
import json
#import numpy as np
# gaph
from jinja2 import Template
#from bokeh.io import output_file, export_png
from bokeh.plotting import *
from bokeh.models import *
from bokeh.layouts import gridplot, column, layout, row
#from bokeh.models import Button
#from bokeh.models.widgets import CheckboxButtonGroup
from bokeh.embed import components
from bokeh.resources import INLINE
#from bokeh.util.browser import view
##### CMD packages #####
from tqdm import tqdm
#from tabulate import tabulate
##### GUI packages #####
from gooey import Gooey, GooeyParser
from colored import stylize, attr, fg
##### Defined color palette #####
RelativityRed = '#C90119' #R201/G1/B25
SignalGreen = '#237f52' #R253/G127/B82
InfinityWhite = '#FFFFFF' #R255/G255/B255
QuantumBlue = '#011E41' #R1/G30/B65
QuantumBlue70 = "#0250AE" # R2/G80/B174
QuantumBlue50 = "#2385FC" # R35/G133/B252
QuantumBlue30 = "#91C1FD" # R145/G193/B253
GravityGrey = '#D9D8D6' #R217/G216/B214
GravityGrey70 = '#E4E4E2' #R228/G228/B226
GravityGrey50 = '#ECECEB' #R236/G236/B235
GravityGrey30 = '#F4F3F3' #R244/G243/B243
CosmicSand = '#D9BE89' #R217/G190/B137
CosmicSand70 = '#E4D2AC' #R228/G210/B172
CosmicSand50 = '#ECDFC4' #R236/G223/B196
CosmicSand30 = '#F4ECDC' #R244/G235/B220
PulseBlue = '#6788B1' #R103/G136/B177
PulseBlue70 = '#95ACC8' #R149/G172/B200
PulseBlue50 = '#B3C4D8' #R179/G196/B216
PulseBlue30 = '#D1DBE8' #R209/G219/B232
MotionGreen = '#8CB680' #R140/G182/B128
MotionGreen70 = '#AFCCA6' #R175/G204/B166
MotionGreen50 = '#C6DBC0' #R198/G219/B192
MotionGreen30 = '#DDE9D9' #R221/G233/B217
StrataTurquoise = '#479CAA' #R71/G156/B170
StrataTurquoise70 = '#7EBAC4' #R126/G186/B196
StrataTurquoise50 = '#A3CED5' #R163/G206/B213
StrataTurquoise30 = '#C8E1E6' #R200/G225/B230
Orange = '#e18700' #R225/G135/B0
GridGray = '#A9A9A9' #R169/G169/B169
Purple = '#800080' #R128/G0/B128
GreenViridis = '#79D151' #R121/G209/B81
YellowPlasma = '#FDE724' #R253/G231/B36
FugroColorList = [SignalGreen, PulseBlue, StrataTurquoise, CosmicSand, MotionGreen, QuantumBlue,
Orange, Purple, QuantumBlue70, GreenViridis, YellowPlasma]
# 417574686f723a205061747269636520506f6e6368616e74
##########################################################
# Main code #
##########################################################
# this needs to be *before* the @Gooey decorator!
# (this code allows to only use Gooey when no arguments are passed to the script)
if len(sys.argv) >= 2:
if not '--ignore-gooey' in sys.argv:
sys.argv.append('--ignore-gooey')
cmd = True
else:
cmd = False
# GUI Configuration
@Gooey(
program_name='CTD Interactif Report for Starfix .vel files.',
progress_regex=r"^progress: (?P<current>\d+)/(?P<total>\d+)$",
progress_expr="current / total * 100",
hide_progress_msg=True,
richtext_controls=True,
clear_before_run=True,
#richtext_controls=True,
terminal_font_family = 'Courier New', # for tabulate table nice formatation
#dump_build_config=True,
#load_build_config="gooey_config.json",
default_size=(930, 770),
timing_options={
'show_time_remaining':True,
'hide_time_remaining_on_complete':True
},
tabbed_groups=True,
navigation='Tabbed',
header_bg_color = '#95ACC8',
#body_bg_color = '#95ACC8',
menu=[{
'name': 'File',
'items': [{
'type': 'AboutDialog',
'menuTitle': 'About',
'name': 'ctdreportvel',
'description': 'CTD Interactif Report for Starfix .vel files',
'version': '0.2.0',
'copyright': '2020',
'website': 'https://github.com/Shadoward/ctdreport-vel',
'developer': 'patrice.ponchant@fugro.com',
'license': 'MIT'
}]
},{
'name': 'Help',
'items': [{
'type': 'Link',
'menuTitle': 'Documentation',
'url': ''
}]
}]
)
def main():
""" Use GooeyParser to build up the arguments we will use in our script
Save the arguments in a default json file so that we can retrieve them
every time we run the script.
"""
stored_args = {}
# get the script name without the extension & use it to build up
# the json filename
script_name = os.path.splitext(os.path.basename(__file__))[0]
args_file = "{}-args.json".format(script_name)
# Read in the prior arguments as a dictionary
if os.path.isfile(args_file):
with open(args_file) as data_file:
stored_args = json.load(data_file)
desc = "CTD Interactif Report for Starfix .vel files"
parser = GooeyParser(description=desc)
mainopt = parser.add_argument_group('CTD Options', gooey_options={'columns': 1})
metaopt = parser.add_argument_group('Metadata Options', gooey_options={'columns': 1})
# Main Arguments
mainopt.add_argument(
'-i', '--velFolder',
dest='velFolder',
metavar='.vel Folder Path',
help='Option to be use to create unique report for each .vel in the folder',
default=stored_args.get('velFolder'),
widget='DirChooser')
mainopt.add_argument(
'-n', '--numberfile',
dest='numberfile',
metavar='Number of files',
help='Number of files to be merge in one report.\n For more visibilty, please try to not pass 10 files per graph)',
type=int,
default=stored_args.get('numberfile'))
#default=1)
# mainopt.add_argument(
# '-f', '--velFilesSelect',
# dest='velFilesSelect',
# metavar='.vel Files',
# help='Option to be use to select mutiples .vel files and create a unique report',
# widget='MultiFileChooser',
# gooey_options={'wildcard': "Starfix Velocity File (*.vel)|*.vel"})
mainopt.add_argument(
'-o', '--outputFolder',
dest='outputFolder',
metavar='Output Logs Folder',
default=stored_args.get('outputFolder'),
help='Output folder to save all the report files.',
widget='DirChooser')
# Metadata Arguments
metaopt.add_argument(
'-t', '--instrument',
dest='instrument',
metavar='Instrument Name',
widget='TextField',
default=stored_args.get('instrument'),
#default='AML Oceanographic - Smart-X CTD',
help='Instrument used to collect the sound velocity data.')
metaopt.add_argument(
'-c', '--velCalc',
dest='velCalc',
metavar='Velocity Calculation',
default=stored_args.get('velCalc'),
choices=['Chen Millero', 'Del Grosso', 'Wilson'],
help='Velocity Calculation used to calculate sound velocity.')
metaopt.add_argument(
'-g', '--geodetic',
dest='geodetic',
metavar='Geodetic Parameters',
widget='TextField',
default=stored_args.get('geodetic'), #'NAD83(2011) / UTM zone 19N | EPSG Code: 6348',
help='Geodetic parameters of the cooredinates.')
# Use to create help readme.md. TO BE COMMENT WHEN DONE
# if len(sys.argv)==1:
# parser.print_help()
# sys.exit(1)
args = parser.parse_args()
# Store the values of the arguments so we have them next time we run
with open(args_file, 'w') as data_file:
# Using vars(args) returns the data as a dictionary
json.dump(vars(args), data_file, indent=1)
process(args, cmd)
def process(args, cmd):
"""
Uses this if called as __main__.
"""
velFolder = args.velFolder
#velFilesSelect = args.velFilesSelect
numberfile = int(args.numberfile)
outputFolder = args.outputFolder
instrument = args.instrument
velCalc = args.velCalc
geodetic = args.geodetic
##########################################################
# Listing the files #
##########################################################
print('', flush=True)
print('##################################################', flush=True)
print('CREATING REPORT FILES. PLEASE WAIT....', flush=True)
print('##################################################', flush=True)
#now = datetime.datetime.now() # record time of the subprocess
if args.velFolder is not None:
velListFile = []
velListemtpy = []
velListtmp = glob.glob(velFolder + "\\*.vel")
if not velListtmp:
print ('')
sys.exit(stylize('No .vel files were found, quitting', fg('red')))
for f in velListtmp:
if os.stat(f).st_size == 0:
velListemtpy.append(f)
else:
velListFile.append(f)
velsplitlist = [velListFile[i:i + numberfile] for i in range(0, len(velListFile), numberfile)]
pbar = tqdm(total=len(velsplitlist)) if cmd else print(f"Note: Output show file counting every {math.ceil(len(velsplitlist)/10)}", flush=True) # cmd vs GUI
i = 0
for el in velsplitlist:
multiplegraph(el, outputFolder, velCalc, instrument, geodetic)
progressBar(cmd, pbar, i, velsplitlist)
i += 1
if velListemtpy:
print('', flush=True)
print('The following file(s) was/were skip beacause there are empty.', flush=True)
print(velListemtpy, flush=True)
# for index, f in enumerate(velListFile):
# multiplegraph(velListFile, outputFolder, velCalc, instrument, geodetic)
# #simplegraph(f, outputFolder, velCalc, instrument, geodetic)
# progressBar(cmd, pbar, index, velListFile)
##########################################################
# Functions #
##########################################################
def lsinfo(f):
filename = os.path.splitext(os.path.basename(f))[0]
# Headers info
dfinfo = pd.read_csv(f, nrows=4, sep="99aa99", header=None, engine='python')
# Value from row 0
row0 = dfinfo[0].iloc[0].split('Time:')
row0_1 = row0[0].split('Date:')
row0_2 = row0_1[0].split('Job Number:')
Job_Number = row0_2[-1].lstrip()
s = row0_1[-1].lstrip()
Date = datetime.datetime.strptime(row0_1[-1].rstrip().lstrip(), '%B %d, %Y').strftime("%d %B %Y")
Time = row0[-1].lstrip()
# Value from row 1
Vessel = dfinfo[0].iloc[1].split('Vessel:')[-1].lstrip()
# Value from row 2
row1 = dfinfo[0].iloc[2].split('Area:')
Area = row1[-1].lstrip()
Client = row1[0].split('Client:')[-1].lstrip()
# Value from row 3
row0 = dfinfo[0].iloc[3].split('Time:')
row0_1 = row0[0].split('X:')
row0_2 = row0_1[0].split('Y:')
row0_3 = row0_2[0].split('Lon:')
Easting = row0_1[-1].lstrip()
Northing = row0_2[-1].lstrip()
Lon = row0_3[-1].lstrip()
Lat = row0_3[0].split('Lat:')[-1].lstrip()
# print('filename, Job_Number, Date, Time, Vessel, Area, Client, Easting, Northing, Lat, Lon')
# print(f'{filename}, {Job_Number}, {Date}, {Time}, {Vessel}, {Area}, {Client}, {Easting}, {Northing}, {Lat}, {Lon}')
return filename, Job_Number, Date, Time, Vessel, Area, Client, Easting, Northing, Lat, Lon
def multiplegraph(velFilesSelect, outputFolder, velCalc, instrument, geodetic):
if len(velFilesSelect) == 1:
filename = os.path.splitext(os.path.basename(velFilesSelect[0]))[0]
else:
filename = str(os.path.splitext(os.path.basename(velFilesSelect[0]))[0]) + '_to_' + str(os.path.splitext(os.path.basename(velFilesSelect[-1]))[0])
dfinfo = pd.DataFrame(columns = ['CTD Name', 'Date', 'Time', 'Latitude', 'Longitude', 'Easting [m]', 'Northing [m]',
'Max. Depth [m]', 'Average SV [m/s]', 'SV at Seabed [m/s]', 'Temperature at Seabed [degC]'])
svp = "Sound Velocity [" + velCalc + ", m/s]" if velCalc is not None else "Sound Velocity [m/s]"
htmlfile = outputFolder + '\\' + filename + '.html'
for index, f in enumerate(velFilesSelect):
# get info from file
fn, Job_Number, Date, Time, Vessel, Area, Client, Easting, Northing, Lat, Lon = lsinfo(f)
# Parameters
htmltitle = Client + " – " + Area
# get data
dfvelu = pd.read_fwf(f, skiprows=5, widths=[6,8,8], header=None)#, usecols=[3,4,6]) #[3]=depth, [4]=velocity, [6]=temperature
dfvelu[0] = dfvelu[0] * -1
temp = round(dfvelu[2].mean(),2) # Temperature at Seabed [°C]
avSV = round(dfvelu[1].mean(),2) # Average SV [m/s]
seabedvel = round(dfvelu[1].iloc[-1],2) # SV at Seabed [m/s]
depth = round(dfvelu[0].min(),2) # Max. Depth [m]
dfinfo = dfinfo.append(pd.Series([fn, Date, Time, Lat, Lon, Easting, Northing,
depth, avSV, seabedvel, temp], index=dfinfo.columns), ignore_index=True)
#colspecs = [(0, 3), (3, None)]
dfvel = pd.concat([pd.read_fwf(f, skiprows=5, widths=[6,8,8], header=None, names=['depth', 'velocity', 'temperature'])
.assign(file=os.path.basename(f)) for f in velFilesSelect])
dfvel['depth'] = dfvel['depth'] * -1
dfvel.sort_values(['file', 'depth'], ascending=[True, False], inplace=True)
################ PLOTS PARAMETERS ################
plot_options = dict(y_axis_label='Depth [Hydrostatic, m]',
background_fill_color='#F4ECDC',
width=600,
height=600,
title="",
toolbar_location=None,
#tools='crosshair,pan,wheel_zoom,box_zoom,reset,hover,save'
)
################ PLOTS ################
###### -- Figure -- ########
renderer_list = []
legend_items = []
line0 = figure(**plot_options)#, tooltips=vToolTips)
line1 = figure(y_range=line0.y_range, **plot_options)#, tooltips=tToolTips)
for (name, group), color in zip(dfvel.groupby('file'), FugroColorList):
source = ColumnDataSource(dict(Depth=group.depth,
Sound_Velocity=group.velocity,
Temperature=group.temperature))
l0 = line0.line(x="Sound_Velocity", y="Depth", color=color, source=source)
line0.xaxis.axis_label = svp
line0.x_range.bounds = 'auto'
line0.y_range.bounds = 'auto'
line0.axis.axis_label_text_font_size = "14pt"
line0.axis.axis_label_text_font_style = "bold"
line0.xaxis.axis_label_standoff = 15
line0.yaxis.axis_label_standoff = 15
l1 = line1.line(x="Temperature", y="Depth", color=color, source=source)
line1.xaxis.axis_label = "Temperature [°C]"
line1.x_range.bounds = 'auto'
line1.y_range.bounds = 'auto'
line1.axis.axis_label_text_font_size = "14pt"
line1.axis.axis_label_text_font_style = "bold"
line1.xaxis.axis_label_standoff = 15
line1.yaxis.axis_label_standoff = 15
line0.add_tools(HoverTool(renderers=[l0],
tooltips=[("CTD", name),
("Depth", "$y{0.1f} m"),
("SV", "$x{0.1f} m/s"),
("Temp.", "@Temperature{0.1f} °C")],
mode='mouse',
line_policy="interp"))
line1.add_tools(HoverTool(renderers=[l1],
tooltips=[("CTD", name),
("Depth", "$y{0.1f} m"),
("SV", "@Sound_Velocity{0.1f} m/s"),
("Temp.", "$x{0.1f} °C")],
mode='mouse',
line_policy="interp"))
renderer_list += [l0, l1]
legend_items.append(LegendItem(label=name, renderers=[l0, l1]))
# https://stackoverflow.com/questions/56825350/how-to-add-one-legend-for-that-controlls-multiple-bokeh-figures
# https://stackoverflow.com/questions/61115734/how-to-work-with-columndatasource-and-legenditem-together-in-bokeh
## Use a dummy figure for the LEGEND
dum_fig = figure(plot_width=300,plot_height=600,outline_line_alpha=0,toolbar_location=None)
# set the components of the figure invisible
for fig_component in [dum_fig.grid[0],dum_fig.ygrid[0],dum_fig.xaxis[0],dum_fig.yaxis[0]]:
fig_component.visible = False
# The glyphs referred by the legend need to be present in the figure that holds the legend, so we must add them to the figure renderers
dum_fig.renderers += renderer_list
# set the figure range outside of the range of all glyphs
dum_fig.x_range.end = 1005
dum_fig.x_range.start = 1000
# add the legend
dum_fig.add_layout(Legend(click_policy='hide',location='top_left',border_line_alpha=0,items=legend_items))
figrid = gridplot([line0, line1],ncols=2)
final = gridplot([[figrid,dum_fig]],toolbar_location=None)
################ TABLES ################
###### Data Table ######
#datatbl = gridplot(tbData, ncols=3, sizing_mode='stretch_both')
# https://gist.github.com/dennisobrien/450d7da20daaba6d39d0
source = ColumnDataSource(dict(Depth=dfvel['depth'],
Sound_Velocity=dfvel['velocity'],
Temperature=dfvel['temperature'],
CTD_Number=dfvel['file']))
original_source = ColumnDataSource(dict(Depth=dfvel['depth'],
Sound_Velocity=dfvel['velocity'],
Temperature=dfvel['temperature'],
CTD_Number=dfvel['file']))
columns = [TableColumn(field="Depth", title="Depth [m]", formatter=NumberFormatter(format="0.00"), width=250),
TableColumn(field="Sound_Velocity", title=svp, formatter=NumberFormatter(format="0.00"), width=250),
TableColumn(field="Temperature", title="Temperature [°C]", formatter=NumberFormatter(format="0.00"), width=250),
TableColumn(field="CTD_Number", title="CTD Number", width=250),
]
data_table = DataTable(source=source, columns=columns, sizing_mode="stretch_width")
# callback code to be used by all the filter widgets
# requires (source, original_source, ctd_select_obj)
combined_callback_code = """
var data = source.data;
var original_data = original_source.data;
var CTD_Number = ctd_select_obj.value;
console.log("CTD Number: " + CTD_Number);
for (var key in original_data) {
data[key] = [];
for (var i = 0; i < original_data['CTD_Number'].length; ++i) {
if (CTD_Number === "ALL" || original_data['CTD_Number'][i] === CTD_Number) {
data[key].push(original_data[key][i]);
}
}
}
source.change.emit();
target_obj.change.emit();
"""
# define the filter widgets, without callbacks for now
if len(dfvel['file'].unique()) == 1:
ctd_list = dfvel['file'].unique().tolist()
else:
ctd_list = ['ALL'] + dfvel['file'].unique().tolist()
ctd_select = Select(title="CTD Number:", value=ctd_list[0], options=ctd_list)
# now define the callback objects now that the filter widgets exist
generic_callback = CustomJS(
args=dict(source=source,
original_source=original_source,
ctd_select_obj=ctd_select,
target_obj=data_table),
code=combined_callback_code
)
# finally, connect the callbacks to the filter widgets
ctd_select.js_on_change('value', generic_callback)
# https://discourse.bokeh.org/t/extract-csv-from-button-in-bokeh-2-1-1/5980/8
button = Button(label="Download", button_type="success")
# var ordercolumns = [{
# 'CTD Number': columns.CTD_Number,
# 'Depth [m]': columns.Depth,
# 'Sound Velocity [m/s]': columns.Sound_Velocity,
# 'Temperature [°s]': columns.Temperature,
# }]
# Not very nice but this order the csv file and rename the colunms properly
javaScript="""
function table_to_csv(source) {
const columns = Object.keys(source.data)
const nrows = source.get_length()
const lines = [['CTD Number','Depth [m]','Sound Velocity [m/s]','Temperature [degC]'].join(',')]
for (let i = 0; i < nrows; i++) {
let row = [];
row.push(source.data['CTD_Number'][i].toString())
row.push(source.data['Depth'][i].toString())
row.push(source.data['Sound_Velocity'][i].toString())
row.push(source.data['Temperature'][i].toString())
lines.push(row.join(','))
}
return lines.join('\\n').concat('\\n')
}
var filetext = table_to_csv(source)
var CTD_Number = ctd_select_obj.value.replace('.vel','')
const fname = CTD_Number + '_CTD_Data.csv'
const blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' })
//addresses IE
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, fname)
} else {
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fname
link.target = '_blank'
link.style.visibility = 'hidden'
link.dispatchEvent(new MouseEvent('click'))
}
"""
button.js_on_click(CustomJS(args=dict(source=source, ctd_select_obj=ctd_select),code=javaScript))
widgets = column([ctd_select, button], height=250, width=300)
datatbl = column(row(widgets, data_table), sizing_mode="stretch_both")
###### Info Table ######
columnsInfo = [TableColumn(field=Ci, title=Ci, width=250) for Ci in dfinfo.columns] # bokeh columns
info_table = DataTable(columns=columnsInfo, source=ColumnDataSource(dfinfo), autosize_mode="fit_columns",
height=25*len(dfinfo)+25) # bokeh table
saveinfo =Button(label="Download", button_type="success", height=30, width=90)
# Not very nice but this order the csv file and rename the colunms properly
javaScript="""
function table_to_csv(source) {
const columns = Object.keys(source.data)
const nrows = source.get_length()
const lines = [['CTD Name', 'Date', 'Time', 'Latitude', 'Longitude', 'Easting [m]', 'Northing [m]',
'Max. Depth [m]', 'Average SV [m/s]', 'SV at Seabed [m/s]', 'Temperature at Seabed [degC]'].join(',')]
for (let i = 0; i < nrows; i++) {
let row = [];
row.push(source.data['CTD Name'][i].toString())
row.push(source.data['Date'][i].toString())
row.push(source.data['Time'][i].toString())
row.push(source.data['Latitude'][i].toString())
row.push(source.data['Longitude'][i].toString())
row.push(source.data['Easting [m]'][i].toString())
row.push(source.data['Northing [m]'][i].toString())
row.push(source.data['Max. Depth [m]'][i].toString())
row.push(source.data['Average SV [m/s]'][i].toString())
row.push(source.data['SV at Seabed [m/s]'][i].toString())
row.push(source.data['Temperature at Seabed [degC]'][i].toString())
lines.push(row.join(','))
}
return lines.join('\\n').concat('\\n')
}
var filetext = table_to_csv(source)
const fname = 'CTD_SummaryTable.csv'
const blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' })
//addresses IE
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, fname)
} else {
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fname
link.target = '_blank'
link.style.visibility = 'hidden'
link.dispatchEvent(new MouseEvent('click'))
}
"""
saveinfo.js_on_click(CustomJS(args=dict(source=ColumnDataSource(dfinfo)),code=javaScript))
widgets = row([saveinfo], height=33)
infotbl = layout([widgets, info_table], sizing_mode="stretch_width")
#infotbl = layout([[info_table]], sizing_mode='stretch_width')
########## RENDER PLOTS ################
###### -- Define our html template for out plots -- ########
template = Template('''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>'CTD {{filename}}'</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
{{ js_resources }}
{{ css_resources }}
<style>
h1 {font-family: 'segoe ui', sans-serif;
display: block;
font-size: 160%;
margin-block-start: 0em;
margin-block-end: 0em;
margin-inline-start: 0px;
margin-inline-end: 0px;
font-weight: bold;
padding-top: 7px;
}
h2 {font-family: 'segoe ui', sans-serif;
color: #ffffff;
margin: 60px 0px 0px 0px;
padding: 0px 0px 6px 150px;
font-size: 35px;
line-height: 48px;
letter-spacing: -2px;
font-weight: bold;
background-color: #011E41;
}
h3 {font-family: 'segoe ui', sans-serif;
color: #011E41;
margin: 20px 0px 0px 15px;
padding: 0px 0px 6px 0px;
font-size: 28px;
line-height: 44px;
letter-spacing: -2px;
#font-weight: bold;
}
h4 {font-family: 'segoe ui', sans-serif;
color: #011E41;
margin: 0px 0px 10px 15px;
padding: 0px 0px -5px 0px;
font-size: 24px;
line-height: 44px;
letter-spacing: -2px;
font-style: italic;
border-bottom-style: solid;
border-width: 2px;
border-color: #011E41;
}
p {font-family: 'segoe ui', sans-serif;
font-size: 16px;
line-height: 24px;
margin: 0 0 24px 15px;
text-align: left;
///text-justify: inter-word;
}
p.noteSmall {font-size:8.0pt;
line-height:12pt;
color:#808080;
}
p.noteNormal {font-size:10.0pt;
color:#808080;
}
ul {font-family: 'segoe ui', sans-serif;
font-size: 16px;
line-height: 24px;
margin: 0 0 24px;
text-align: left;
///text-justify: inter-word;
}
p.TableText, li.TableText, div.TableText
{margin-top:3.0pt;
margin-right:5.65pt;
margin-bottom:3.0pt;
margin-left:5.65pt;
font-size:9.0pt;
font-family:"Segoe UI",sans-serif;
}
p.TableNote, li.TableNote, div.TableNote
{margin-top:3.0pt;
margin-right:5.65pt;
margin-bottom:3.0pt;
margin-left:5.65pt;
line-height:12pt;
font-size:8.0pt;
font-family:"Segoe UI",sans-serif;
color:#808080;
}
.TableText.Centre
{text-align:center;
}
p.TableHeading, li.TableHeading, div.TableHeading
{margin-top:3.0pt;
margin-right:5.65pt;
margin-bottom:3.0pt;
margin-left:5.65pt;
font-size:9.0pt;
font-family:"Segoe UI Semibold",sans-serif;
}
.TableHeading.Centre
{text-align:center;
}
td.TableHeadingGridTable
{border:solid #6788B1 1.0pt;
border-right:solid white 1.0pt;
background:#6788B1;
vertical-align: top;
padding:0cm 0cm 0cm 0cm;
}
td.TableTextGridTable
{border-top:none;
border-left:none;
border-bottom:solid #6788B1 1.0pt;
border-right:solid #6788B1 1.0pt;
vertical-align: top;
padding:0cm 0cm 0cm 0cm;
}
td.TableHeadingLinedTable
{border:none;
border-bottom:solid #6788B1 1.0pt;
background:white;
vertical-align: bottom;
padding:0cm 0cm 0cm 0cm;
}
td.TableTextLinedTable
{border:none;
border-bottom:solid #7F7F7F 1.0pt;
vertical-align: top;
padding:0cm 0cm 0cm 0cm;
}
.app_header {
height:80px;
width: 100%;
background-color:#011E41;
color:#eee;
margin-left: auto;
margin-right: auto;
}
@media screen and (min-width : 1024px) {
.app_header {
width: 100%;
}
}
.app_header a {
color: #900;
}
.app_header_icon {
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAABDCAYAAABX2cG8AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAALiMAAC4jAXilP3YAAASVSURBVHhe7ZxdiFVVFMfnq0LSJsI0CpKwhzJ6iXwYLQiiCAYCn4QeRJLoqbRUjKC0t6EPwd4iKiMsSsge+kA0kiIjQQoSpMwIYYixtI9RCZM7/dY+y+s995572feMZz72/H/wZ++19jr77LPX3fuec7xjjxBCCCGEEEIIIYQQQghRMb1eVkatVnuQ4g10Q3B0z7G+vr5lXhcziYmJiX4SPEZZGo7/0bsTJejzsioW9Pb2LvK6mAYq3aJZgNdS/JlZeWgbpfg+szoyyhb9uNfFTMISbNtsEWy9qz1MVEjVW3Qn/vNSVEjXWzSLbyGKPW6Q7+BjXs9BH49SfJJZnWGLPulVuyu/jmIgsy7Bec6gc24GPLY/s6I4x7nOej1AH6XvIWw8Ni4369j82TxSjZ5/+jmNLrhZHVzwGQY31dR3Gs5/2H058K/3EJvAQewvspZ4OOY8et67CWDXvLlrOPQC+pDqoHdn/S1FR7OIeDhmFA15N9FM5xZ9uZnw0hK8kU/7fW5GwzFXoBeYyDvdNSnoqx+tYjzPuMt4Ed9tXo+GY26keD2z4ul6i+bi3+FkV7nZES5swC7QzRy0fUvbCTfNvgX7bjebsYmqWYXzH6Z+V/A2wPHr2V5ftToxbxGzNjQ0QdwPFMfREDGLg7MJYobp61Or01eNuJZ5IuZ9in2Z1WPb7bOEXZOZeYh9j/4esTrdHSJueWhogBj7gO5BY2g1Mfb1koOQcfopPMe0wIDm28CL4ELDBV8Ee503FRGzRT/pISHB7m7mAArJImYx+hodLFB9K6ReuEXj3uAhAeyt3tQCbe96mMUdcnczOz3EYh5wXw78/3hINElu0e1gjn5iZYQ4VsIYWolWFOibcEB3nPeyFIztO68aR72cNCklOBomcxur4ecOGvbQTiyzONca7NyKbqLwZc9UMKdW8EVI8EJW8tJ2ImR+Ftke4h5DH7veRoWPU5zrOG2vuBlLuN+4HMzJFcyEv8zED6E/3NU1HNvxRQ3tI+geznU7+sXdU86sSDATdauXV1LcbPWShFXGhP+KjlC92uySvMR47G68Hes4xyiKfWPXuAPc5OWkmS0r+AO+555gQvcwYfZIUkTMtvYw/byGNtDXXvqa5/4y/I6G6edUZuah7+tp+4hzxX6IniJ+hPjN1Hdlrhaiv4amBAbczWPSCm8qS/3Fhk2S+0rB8fV/CKHe8TGJ8l70r7tboG03Rf05mvrO0FAC+vrSu4lmxqxgHk0Ocg0bkf1AwF6Hxuok2sKKOeBd2erZge9N9JfHNOs0eg7tavDVRReN73xb2j0mbL2M+yuKtfjGm2NMtD1E+bTFOpuwP0OF8W1k493Pddnd+syBQUWvYFENc/Iuei6hBCeOEpw4SnDiKMGJowQnjhKcOEpw4ijBiaMEJ44SnDhKcOIowYmjBCeOEpw4SnDiKMGJU3WC7df+f2fVFuxHa2K2U8t+wZgD3+feLGY75HOAhB7JUhuSa3+De4c3ixQgofd7fi3B290tUoLE7ka/keP6X7uLhCC5S5D+Zx0hhBBCCCGEEEIIIYQQIil6ev4H0L1DGlhlR+UAAAAASUVORK5CYII=')
no-repeat;
/* margin:-29px; */
margin-top: 5px;
margin-left:5px;
margin-right: 70px;
float:left;
width: 120px;
height: 67px;
}
.app_header_search {
float:right;
padding:15px;
}
.slick-header-column {
background-color: #6788B1 !important;
background-image: none !important;
color: white !important;
font-size:9.0pt;
font-family:"Segoe UI Semibold",sans-serif;
}
.slick-row {
background-color: white !important;
background-image: none !important;
color:black !important;
font-size:9.0pt;
font-family:"Segoe UI",sans-serif;
}
.bk-cell-index {
background-color: white !important;
background-image: none !important;
color:black !important;
font-size:9.0pt;
font-family:"Segoe UI",sans-serif;
}
</style>
</head>
<body>
<div id="app_header" class="app_header">
<span class="app_header_icon"></span>
<h1>{{ title }}</h1>
</div>
<h3>Executive Summary</h3>
<h4></h4>
<p>The CTD was collected on the {{ date }} using a {{ instrument }}.</p>
<p>The recommended United Nations Educational, Scientific and Cultural Organisation (UNESCO) formulae was used to process the data and can be found in the <a href="http://unesdoc.unesco.org/images/0005/000598/059832eb.pdf">UNESCO technical papers in marine science 44</a>.
<br>{{velCalc}} formula was use to determided sound velocity from the CTD data.
</p>
<div style="margin-left: 15px;">
{{ plot_div.tblInfo }}
<hr>
</div>
<p class=noteSmall>Note:
<br>Geodetic Parameters = {{ geodetic }}
<br>Sound Velocity Calculation = {{ velCalc }}</p>
<p></p>
<h3>Interactive Plots</h3>
<h4></h4>
<p class=noteNormal>The graphs are interactive with the option of zoom in and out, move, save a image and have o hover tooltips.
<br>The legend is interative too and by clicking on a item the data in the graph will be hidden.</p>
<div style="margin-left: 15px;">
{{ plot_div.p }}
</div>
<h3>Interactive Table</h3>
<h4></h4>
<div style="margin-left: 15px;">
{{ savebt }}
{{ plot_div.tblData }}
</div>
{{ plot_script }}
</body>
</html>
''')
resources = INLINE
js_resources = resources.render_js()
css_resources = resources.render_css()
script, div = components({'p': final, 'tblData': datatbl, 'tblInfo': infotbl})
html = template.render(js_resources=js_resources,css_resources=css_resources,plot_script=script,plot_div=div,velCalc=velCalc,
title=htmltitle,filename=filename,location=Area, instrument=instrument,geodetic=geodetic)
###### -- end -- ########
###### -- save the document in a HTML -- ########
with open(htmlfile, 'w', encoding="utf-8") as f:
f.write(html)
###### -- end -- ########
reset_output()
# Others function
# https://stackoverflow.com/questions/42915638/bokeh-datatables-overlapping-in-both-row-and-gridplot#
def multi_table(d,sv,t,svp):
source = ColumnDataSource(data=dict())
source.data = {'Depth': d, 'SoundVelocity': sv, 'Temperature': t}
columns = [TableColumn(field="Depth", title="Depth [m]", formatter=NumberFormatter(format="0.00"), width=250),
TableColumn(field="SoundVelocity", title=svp, formatter=NumberFormatter(format="0.00"), width=250),
TableColumn(field="Temperature", title="Temperature [°C]", formatter=NumberFormatter(format="0.00"), width=250),
]
data_table = DataTable(source=source, columns=columns, autosize_mode="fit_columns")
return data_table
# from https://www.pakstech.com/blog/python-gooey/
def print_progress(index, total):
print(f"progress: {index+1}/{total}", flush=True)
# Progrees bar GUI and CMD
def progressBar(cmd, pbar, index, ls):
if cmd:
pbar.update(1)
else:
print_progress(index, len(ls)) # to have a nice progress bar in the GUI
if index % math.ceil(len(ls)/10) == 0 and index != (len(ls) - 1): # decimate print
print(f"Files Process: {index+1}/{len(ls)}", flush=True)
if index == (len(ls) - 1):
print(f"Files Process: {index+1}/{len(ls)}", flush=True)
if __name__ == "__main__":
now = datetime.datetime.now() # time the process
main()
print('', flush=True)
print("Process Duration: ", (datetime.datetime.now() - now), flush=True) # print the processing time. It is handy to keep an eye on processing performance. |
from tests.utils import econf_compile, econf_foreach_cluster, module_and_mapping_manifests, SUPPORTED_ENVOY_VERSIONS
import os
import pytest
# Tests if `setting` exists within the cluster config and has `expected` as the value for that setting
# Use `exists` to test if you expect a setting to not exist
def _test_cluster_setting(yaml, setting, expected, exists=True, envoy_version="V2"):
econf = econf_compile(yaml, envoy_version=envoy_version)
def check(cluster):
if exists:
assert setting in cluster
assert cluster[setting] == expected
else:
assert setting not in cluster
econf_foreach_cluster(econf, check)
# Tests a setting in a cluster that has it's own fields. Example: common_http_protocol_options has multiple subfields
def _test_cluster_subfields(yaml, setting, expectations={}, exists=True, envoy_version="V2"):
econf = econf_compile(yaml, envoy_version=envoy_version)
def check(cluster):
if exists:
assert setting in cluster
else:
assert setting not in cluster
for key, expected in expectations.items():
print("Checking key: {} for the {} setting in Envoy cluster".format(key, setting))
assert key in cluster[setting]
assert cluster[setting][key] == expected
econf_foreach_cluster(econf, check)
# Test dns_type setting in Mapping
@pytest.mark.compilertest
def test_logical_dns_type():
yaml = module_and_mapping_manifests(None, ["dns_type: logical_dns"])
for v in SUPPORTED_ENVOY_VERSIONS:
# The dns type is listed as just "type"
_test_cluster_setting(yaml, setting="type",
expected="LOGICAL_DNS", exists=True, envoy_version=v)
@pytest.mark.compilertest
def test_strict_dns_type():
# Make sure we can configure strict dns as well even though it's the default
yaml = module_and_mapping_manifests(None, ["dns_type: strict_dns"])
for v in SUPPORTED_ENVOY_VERSIONS:
# The dns type is listed as just "type"
_test_cluster_setting(yaml, setting="type",
expected="STRICT_DNS", exists=True, envoy_version=v)
@pytest.mark.compilertest
def test_dns_type_wrong():
# Ensure we fallback to strict_dns as the setting when an invalid string is passed
# This is preferable to invalid config and an error is logged
yaml = module_and_mapping_manifests(None, ["dns_type: something_new"])
for v in SUPPORTED_ENVOY_VERSIONS:
# The dns type is listed as just "type"
_test_cluster_setting(yaml, setting="type",
expected="STRICT_DNS", exists=True, envoy_version=v)
@pytest.mark.compilertest
def test_logical_dns_type_endpoints():
# Ensure we use endpoint discovery instead of this value when using the endpoint resolver.
# This test only makes sense in non-legacy mode.
if os.environ.get('AMBASSADOR_LEGACY_MODE', 'false').lower() == 'true':
pytest.xfail("Not supported in legacy mode")
return
yaml = module_and_mapping_manifests(None, ["dns_type: logical_dns", "resolver: endpoint"])
for v in SUPPORTED_ENVOY_VERSIONS:
# The dns type is listed as just "type"
_test_cluster_setting(yaml, setting="type",
expected="EDS", exists=True, envoy_version=v)
@pytest.mark.compilertest
def test_dns_ttl():
# Test configuring the respect_dns_ttl generates an Envoy config
yaml = module_and_mapping_manifests(None, ["respect_dns_ttl: true"])
for v in SUPPORTED_ENVOY_VERSIONS:
# The dns type is listed as just "type"
_test_cluster_setting(yaml, setting="respect_dns_ttl",
expected="true", exists=True, envoy_version=v)
@pytest.mark.compilertest
def test_dns_ttl():
# Test dns_ttl is not configured when not applied in the Mapping
yaml = module_and_mapping_manifests(None, None)
for v in SUPPORTED_ENVOY_VERSIONS:
# The dns type is listed as just "type"
_test_cluster_setting(yaml, setting="respect_dns_ttl",
expected="false", exists=False, envoy_version=v)
|
from openstack.bssintl import bss_intl_service
from openstack import resource2 as resource
class Version(resource.Resource):
resource_key = 'version'
resources_key = 'versions'
base_path = '/'
service = bss_intl_service.BssIntlService(
version=bss_intl_service.BssIntlService.UNVERSIONED
)
# capabilities
allow_list = True
# Properties
links = resource.Body('links')
status = resource.Body('status')
|
##################################################################
## (c) Copyright 2018- by Jaron T. Krogel ##
##################################################################
#====================================================================#
# quantum_package_analyzer.py #
# Supports data analysis for Quantum Package output. Currently #
# just a placeholder for further development. #
# #
# Content summary: #
# QuantumPackageAnalyzer #
# SimulationAnalyzer class for Quantum Package. #
# #
#====================================================================#
from simulation import NullSimulationAnalyzer
class QuantumPackageAnalyzer(NullSimulationAnalyzer):
None
#end class QuantumPackageAnalyzer
|
# -*- coding: utf-8 -*-
"""Tests for the wgs_sv_calling workflow module code"""
import textwrap
import pytest
import ruamel.yaml as yaml
from snakemake.io import Wildcards
from snappy_pipeline.workflows.wgs_sv_calling import WgsSvCallingWorkflow
from .common import get_expected_output_bcf_files_dict, get_expected_output_vcf_files_dict
from .conftest import patch_module_fs
__author__ = "Manuel Holtgrewe <manuel.holtgrewe@bihealth.de>"
@pytest.fixture(scope="module") # otherwise: performance issues
def minimal_config():
"""Return YAML parsing result for (somatic) configuration"""
return yaml.round_trip_load(
textwrap.dedent(
r"""
static_data_config:
reference:
path: /path/to/ref.fa
dbsnp:
path: /path/to/dbsnp.vcf.gz
step_config:
ngs_mapping:
tools:
dna: ['bwa']
compute_coverage_bed: true
path_target_regions: /path/to/regions.bed
bwa:
path_index: /path/to/bwa/index.fa
wgs_sv_calling:
tools:
dna:
- manta
- delly2
long_dna:
- pb_honey_spots
data_sets:
first_batch:
file: sheet.tsv
search_patterns:
- {'left': '*/*/*_R1.fastq.gz', 'right': '*/*/*_R2.fastq.gz'}
search_paths: ['/path']
type: germline_variants
naming_scheme: only_secondary_id
"""
).lstrip()
)
@pytest.fixture
def wgs_sv_calling_workflow(
dummy_workflow,
minimal_config,
dummy_cluster_config,
config_lookup_paths,
work_dir,
config_paths,
germline_sheet_fake_fs,
mocker,
):
"""Return WgsSvCallingWorkflow object pre-configured with germline sheet"""
# Patch out file-system related things in abstract (the crawling link in step is defined there)
patch_module_fs("snappy_pipeline.workflows.abstract", germline_sheet_fake_fs, mocker)
# Update the "globals" attribute of the mock workflow (snakemake.workflow.Workflow) so we
# can obtain paths from the function as if we really a NGSMappingPipelineStep here
dummy_workflow.globals = {"ngs_mapping": lambda x: "NGS_MAPPING/" + x}
# Construct the workflow object
return WgsSvCallingWorkflow(
dummy_workflow,
minimal_config,
dummy_cluster_config,
config_lookup_paths,
config_paths,
work_dir,
)
# Tests for Delly2StepPart (call) -----------------------------------------------------------------
def test_delly2_step_part_call_get_input_files(wgs_sv_calling_workflow):
wildcards = Wildcards(fromdict={"mapper": "bwa", "library_name": "P001-N1-DNA1-WGS1"})
actual = wgs_sv_calling_workflow.get_input_files("delly2", "call")(wildcards)
expected = {
"bai": "NGS_MAPPING/output/bwa.P001-N1-DNA1-WGS1/out/bwa.P001-N1-DNA1-WGS1.bam.bai",
"bam": "NGS_MAPPING/output/bwa.P001-N1-DNA1-WGS1/out/bwa.P001-N1-DNA1-WGS1.bam",
}
assert actual == expected
def test_delly2_step_part_call_get_output_files(wgs_sv_calling_workflow):
# Define expected
base_name_out = (
r"work/{mapper,[^\.]+}.delly2.call.{library_name,[^\.]+}/out/"
r"{mapper}.delly2.call.{library_name}"
)
expected = get_expected_output_bcf_files_dict(base_out=base_name_out)
# Get actual
actual = wgs_sv_calling_workflow.get_output_files("delly2", "call")
assert actual == expected
def test_delly_step_part_call_get_log_file(wgs_sv_calling_workflow):
expected = "work/{mapper}.delly2.call.{library_name}/log/snakemake.log"
assert wgs_sv_calling_workflow.get_log_file("delly2", "call") == expected
def test_delly_step_part_call_update_cluster_config(wgs_sv_calling_workflow, dummy_cluster_config):
actual = set(dummy_cluster_config["wgs_sv_calling_delly2_call"].keys())
expected = {"mem", "time", "ntasks"}
assert actual == expected
# Tests for Delly2StepPart (merge_calls) ----------------------------------------------------------
def test_delly2_step_part_merge_calls_get_input_files(wgs_sv_calling_workflow):
wildcards = Wildcards(fromdict={"mapper": "bwa", "index_ngs_library": "P001-N1-DNA1-WGS1"})
actual = wgs_sv_calling_workflow.get_input_files("delly2", "merge_calls")(wildcards)
expected = [
"work/bwa.delly2.call.P001-N1-DNA1-WGS1/out/bwa.delly2.call.P001-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.call.P002-N1-DNA1-WGS1/out/bwa.delly2.call.P002-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.call.P003-N1-DNA1-WGS1/out/bwa.delly2.call.P003-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.call.P004-N1-DNA1-WGS1/out/bwa.delly2.call.P004-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.call.P005-N1-DNA1-WGS1/out/bwa.delly2.call.P005-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.call.P006-N1-DNA1-WGS1/out/bwa.delly2.call.P006-N1-DNA1-WGS1.bcf",
]
assert actual == expected
def test_delly2_step_part_merge_calls_get_output_files(wgs_sv_calling_workflow):
# Define expected
base_name_out = r"work/{mapper,[^\.]+}.delly2.merge_calls/out/{mapper}.delly2.merge_calls"
expected = get_expected_output_bcf_files_dict(base_out=base_name_out)
# Get actual
actual = wgs_sv_calling_workflow.get_output_files("delly2", "merge_calls")
assert actual == expected
def test_delly_step_part_merge_calls_get_log_file(wgs_sv_calling_workflow):
expected = "work/{mapper}.delly2.merge_calls/log/snakemake.log"
assert wgs_sv_calling_workflow.get_log_file("delly2", "merge_calls") == expected
def test_delly_step_part_merge_calls_update_cluster_config(
wgs_sv_calling_workflow, dummy_cluster_config
):
actual = set(dummy_cluster_config["wgs_sv_calling_delly2_merge_calls"].keys())
expected = {"mem", "time", "ntasks"}
assert actual == expected
# Tests for Delly2StepPart (genotype) -------------------------------------------------------------
def test_delly2_step_part_genotype_get_input_files(wgs_sv_calling_workflow):
wildcards = Wildcards(fromdict={"mapper": "bwa", "library_name": "P001-N1-DNA1-WGS1"})
actual = wgs_sv_calling_workflow.get_input_files("delly2", "genotype")(wildcards)
expected = {
"bai": "NGS_MAPPING/output/bwa.P001-N1-DNA1-WGS1/out/bwa.P001-N1-DNA1-WGS1.bam.bai",
"bam": "NGS_MAPPING/output/bwa.P001-N1-DNA1-WGS1/out/bwa.P001-N1-DNA1-WGS1.bam",
"bcf": "work/bwa.delly2.merge_calls/out/bwa.delly2.merge_calls.bcf",
}
assert actual == expected
def test_delly2_step_part_genotype_get_output_files(wgs_sv_calling_workflow):
# Define expected
base_name_out = (
r"work/{mapper,[^\.]+}.delly2.genotype.{library_name,[^\.]+}/out/"
r"{mapper}.delly2.genotype.{library_name}"
)
expected = get_expected_output_bcf_files_dict(base_out=base_name_out)
# Get actual
actual = wgs_sv_calling_workflow.get_output_files("delly2", "genotype")
assert actual == expected
def test_delly_step_part_genotype_get_log_file(wgs_sv_calling_workflow):
expected = "work/{mapper}.delly2.genotype.{library_name}/log/snakemake.log"
assert wgs_sv_calling_workflow.get_log_file("delly2", "genotype") == expected
def test_delly_step_part_genotype_update_cluster_config(
wgs_sv_calling_workflow, dummy_cluster_config
):
actual = set(dummy_cluster_config["wgs_sv_calling_delly2_genotype"].keys())
expected = {"mem", "time", "ntasks"}
assert actual == expected
# Tests for Delly2StepPart (merge_genotypes) ------------------------------------------------------
def test_delly2_step_part_merge_genotypes_get_input_files(wgs_sv_calling_workflow):
wildcards = Wildcards(fromdict={"mapper": "bwa", "index_ngs_library": "P001-N1-DNA1-WGS1"})
actual = wgs_sv_calling_workflow.get_input_files("delly2", "merge_genotypes")(wildcards)
expected = [
"work/bwa.delly2.genotype.P001-N1-DNA1-WGS1/out/bwa.delly2.genotype.P001-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.genotype.P002-N1-DNA1-WGS1/out/bwa.delly2.genotype.P002-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.genotype.P003-N1-DNA1-WGS1/out/bwa.delly2.genotype.P003-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.genotype.P004-N1-DNA1-WGS1/out/bwa.delly2.genotype.P004-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.genotype.P005-N1-DNA1-WGS1/out/bwa.delly2.genotype.P005-N1-DNA1-WGS1.bcf",
"work/bwa.delly2.genotype.P006-N1-DNA1-WGS1/out/bwa.delly2.genotype.P006-N1-DNA1-WGS1.bcf",
]
assert actual == expected
def test_delly2_step_part_merge_genotypes_get_output_files(wgs_sv_calling_workflow):
# Define expected
base_name_out = (
r"work/{mapper,[^\.]+}.delly2.merge_genotypes/out/{mapper}.delly2.merge_genotypes"
)
expected = get_expected_output_bcf_files_dict(base_out=base_name_out)
# Get actual
actual = wgs_sv_calling_workflow.get_output_files("delly2", "merge_genotypes")
assert actual == expected
def test_delly_step_part_merge_genotypes_get_log_file(wgs_sv_calling_workflow):
expected = "work/{mapper}.delly2.merge_genotypes/log/snakemake.log"
assert wgs_sv_calling_workflow.get_log_file("delly2", "merge_genotypes") == expected
def test_delly_step_part_merge_genotypes_update_cluster_config(
wgs_sv_calling_workflow, dummy_cluster_config
):
actual = set(dummy_cluster_config["wgs_sv_calling_delly2_merge_genotypes"].keys())
expected = {"mem", "time", "ntasks"}
assert actual == expected
# Tests for Delly2StepPart (reorder_vcf) ----------------------------------------------------------
def test_delly2_step_part_reorder_vcf_get_input_files(wgs_sv_calling_workflow):
wildcards = Wildcards(fromdict={"mapper": "bwa", "index_ngs_library": "P001-N1-DNA1-WGS1"})
actual = wgs_sv_calling_workflow.get_input_files("delly2", "reorder_vcf")(wildcards)
expected = {"bcf": "work/bwa.delly2.merge_genotypes/out/bwa.delly2.merge_genotypes.bcf"}
assert actual == expected
def test_delly2_step_part_reorder_vcf_get_output_files(wgs_sv_calling_workflow):
# Define expected
base_name_out = (
r"work/{mapper,[^\.]+}.delly2.{index_ngs_library,[^\.]+}/out/"
r"{mapper}.delly2.{index_ngs_library}"
)
expected = get_expected_output_vcf_files_dict(base_out=base_name_out)
# Get actual
actual = wgs_sv_calling_workflow.get_output_files("delly2", "reorder_vcf")
assert actual == expected
def test_delly_step_part_reorder_vcf_get_log_file(wgs_sv_calling_workflow):
expected = "work/{mapper}.delly2.{index_ngs_library}/log/snakemake.log"
assert wgs_sv_calling_workflow.get_log_file("delly2", "reorder_vcf") == expected
def test_delly_step_part_reorder_vcf_update_cluster_config(
wgs_sv_calling_workflow, dummy_cluster_config
):
actual = set(dummy_cluster_config["wgs_sv_calling_delly2_reorder_vcf"].keys())
expected = {"mem", "time", "ntasks"}
assert actual == expected
# Tests for MantaStepPart -------------------------------------------------------------------------
def test_manta_step_part_get_input_files(wgs_sv_calling_workflow):
wildcards = Wildcards(fromdict={"mapper": "bwa", "index_ngs_library": "P001-N1-DNA1-WGS1"})
actual = wgs_sv_calling_workflow.get_input_files("manta", "run")(wildcards)
expected = [
"NGS_MAPPING/output/bwa.P001-N1-DNA1-WGS1/out/bwa.P001-N1-DNA1-WGS1.bam",
"NGS_MAPPING/output/bwa.P001-N1-DNA1-WGS1/out/bwa.P001-N1-DNA1-WGS1.bam.bai",
"NGS_MAPPING/output/bwa.P002-N1-DNA1-WGS1/out/bwa.P002-N1-DNA1-WGS1.bam",
"NGS_MAPPING/output/bwa.P002-N1-DNA1-WGS1/out/bwa.P002-N1-DNA1-WGS1.bam.bai",
"NGS_MAPPING/output/bwa.P003-N1-DNA1-WGS1/out/bwa.P003-N1-DNA1-WGS1.bam",
"NGS_MAPPING/output/bwa.P003-N1-DNA1-WGS1/out/bwa.P003-N1-DNA1-WGS1.bam.bai",
]
assert actual == expected
def test_manta_step_part_get_output_files(wgs_sv_calling_workflow):
# Define expected
base_name_out = "work/{mapper}.manta.{index_ngs_library}/out/{mapper}.manta.{index_ngs_library}"
expected = get_expected_output_vcf_files_dict(base_out=base_name_out)
# Get actual
actual = wgs_sv_calling_workflow.get_output_files("manta", "run")
assert actual == expected
def test_manta_step_part_get_log_file(wgs_sv_calling_workflow):
expected = "work/{mapper}.manta.{index_ngs_library}/log/snakemake.log"
assert wgs_sv_calling_workflow.get_log_file("manta", "run") == expected
def test_manta_step_part_update_cluster_config(wgs_sv_calling_workflow, dummy_cluster_config):
actual = set(dummy_cluster_config["wgs_sv_calling_manta_run"].keys())
expected = {"mem", "time", "ntasks"}
assert actual == expected
# Tests for WgsSvCallingWorkflow -----------------------------------------------------------
def test_wgs_sv_calling_workflow(wgs_sv_calling_workflow):
"""Tests simple functionality of the workflow."""
# Check created sub steps
expected = ["delly2", "link_out", "manta", "pb_honey_spots", "popdel", "sniffles", "svtk"]
actual = list(sorted(wgs_sv_calling_workflow.sub_steps.keys()))
assert actual == expected
# Check result file construction
tpl = (
"output/{mapper}.{sv_caller}.P00{i}-N1-DNA1-WGS1/out/"
"{mapper}.{sv_caller}.P00{i}-N1-DNA1-WGS1.{ext}"
)
expected = [
tpl.format(mapper=mapper, sv_caller=sv_caller, i=i, ext=ext)
for mapper in ("bwa",)
for sv_caller in ("delly2", "manta")
for i in [1, 4] # only indices
for ext in ("vcf.gz", "vcf.gz.md5", "vcf.gz.tbi", "vcf.gz.tbi.md5")
]
expected = list(sorted(expected))
actual = list(sorted(wgs_sv_calling_workflow.get_result_files()))
assert actual == expected
|
import os
from functools import lru_cache
import typer
from changelog import dump_to_file, load_from_file
from changelog.exceptions import ChangelogParseError, ChangelogValidationError
from changelog.model import Changelog
@lru_cache(maxsize=None)
def global_options():
return {"path": os.getenv("CHANGELOG_PATH", "CHANGELOG.md")}
def get_changelog() -> Changelog:
path = global_options()["path"]
try:
changelog = load_from_file(path=path)
except (ChangelogParseError, ChangelogValidationError) as exc:
typer.secho(
f"""
ERROR: Could not parse changelog: {str(exc)}""",
fg="red",
)
raise typer.Exit(1)
return changelog
def save_changelog(changelog: Changelog):
path = global_options()["path"]
dump_to_file(changelog, path=path)
|
# -*- coding: utf-8 -*-
##
# \file init_fdtd_geospr.py
# \title Definition of the numerical parameters for the FDTD method.
# The updated scheme that gives the pressure
# at each time iteration is defined in the upd_fdtd.py files.
# It is applied for the grid convergence studies geometrical divergence.
# \author Pierre Chobeau
# \version 0.1
# \license BSD 3-Clause License
# \inst UMRAE (Ifsttar Nantes), LAUM (Le Mans Université)
# \date 2017, 30 Aug.
##
import numpy as np
import os
import site
import progressbar
base_path = reduce(lambda l, r: l + os.path.sep + r,
os.path.dirname(os.path.realpath(__file__)).split(os.path.sep))
fdtd_core_path = os.path.join(base_path, 'fdtd_core')
site.addsitedir(fdtd_core_path)
from upd_fdtd import upd_p_fdtd_srl, upd_vel_pbc_fdtd
tools_path = os.path.join(base_path.rsplit(os.sep, 2)[0], 'tools')
site.addsitedir(tools_path)
import source_signals as src
data_plotting_path = os.path.join(base_path.rsplit(os.sep, 2)[0], 'data_plotting')
site.addsitedir(data_plotting_path)
from display_wavefronts import instatenous_pressure
def fdtd_srl_init_conv(dl, h_num, dt, d_sr, T, f_max, rho, c, case, disp_inst_p):
"""
Setting the 2D geometries and running the FDTD update for case 1: geometrical spreading.
Main script that contains all the parameters to run the FDTD update in 2D.
:param dl: spatial step (m).
:type dl: float
:param h_num: spatial step index.
:type h_num: int
:param dt: time step (s).
:type dt: float
:param d_sr: horizontal distances between the source and the receivers, list of floats (m).
:type d_sr: list of floats
:param T: simulation duration (s).
:type T: float
:param f_max: approximated maximale frequency of the source signal (Hz).
:type f_max: float
:param rho: air density (kg.m-3).
:type rho: float
:param c: sound speed (m.s-1).
:type c: float
:param case: integer that sorts of the saved folders in the results directory.
:type case: int
:param disp_inst_p: display the instantaneous pressure.
:type disp_inst_p: bool
:param Lx: continuous length of the domain (in meter) following the x-direction.
:param Ly: continuous length of the domain (in meter) following the y-direction.
:param Nx: discrete length of the domain (number of node) following the x-direction.
:param Ny: discrete length of the domain (number of node) following the y-direction.
:param x: discrete length sequence of a domain side, scalar (m).
:param dx: spatial step after discretization, scalar (m).
:param Nt: number of iteration time, scalar.
:param t: discretized time sequence, 1d array (s).
:param It: discretized time sequence, 1d array.
:param Ts: time step after dicretization, scalar (s).
:param Cn: Courant number, scalar.
:param p: updated pressure (n+1), numpy array (dimension of the scene).
:param p1: current pressure (n), numpy array (dimension of the scene).
:param p2: past pressure (n-1), numpy array (dimension of the scene).
:param fsrc: soft source (n+1), numpy array (dimension of the scene).
:param fsrc1: soft source (n), numpy array (dimension of the scene).
:param p_axial: pressure saved on the axial axis, 2d array (number of recievers * n).
:param p_diag: pressure saved on the diagonal axis, 2d array (number of recievers * n).
:param A: inertance of the boundary, scalar.
:param B: stiffness of the boundary, scalar.
:param C: resistivity of the boundary, scalar.
:param Nb: boundary of the domain (1 if BC, 0 else) for the compact
pressure update, numpy array (dimension of the scene).
:param x_src: discrete x coordinate of the source, scalar (number of node).
:param y_src: discrete y coordinate of the source, scalar (number of node).
:param x_rcv: discrete x coordinate of the receiver, scalar (number of node).
:param y_rcv: discrete y coordinate of the receiver, scalar (number of node).
:param n: discrete iteration inside the for loop, scalar.
:return: the acoustic pressure at the pre-defined receivers' locations as a function of time.
:rtype: (1+1)D array of floats 64
"""
# ==============================================================================
# Source
# ==============================================================================
src_typ = "gauss_1"
src_frq = f_max
# ==============================================================================
# Parameters
# ==============================================================================
dl_max = 0.075 * c * np.sqrt(2) / src_frq # 2% accuracy kowalczyk_ieee2011 ~ lambda/9.43
dt = dl / (np.sqrt(2.) * c)
# print 'dt_lim = %.3e' %dt_lim
Lx = 24.0
Ly = Lx # compulsory for the right diagonal coordinates
Nx = np.int(np.round(Lx / dl))
Ny = np.int(np.round(Ly / dl))
x = np.linspace(0, Lx, Nx + 1)
dx = np.float64(x[1] - x[0])
dx = round(dx, 5)
Nt = int(round(T / float(dt)))
t = np.linspace(0, Nt * dt, Nt + 1)
It = range(0, t.shape[0])
Ts = np.float64(t[1] - t[0])
Cn = np.float64(c * Ts / dx)
nNt = 1
# print '--------------------- Courant Number --------------------------'
# while Cn >= (1 / np.sqrt(2)):
# print 'COURANT NUMBER CORRECTION!!!'
# nNt = 1 + nNt
# t = np.linspace(0, Nt * dt, Nt + (nNt)) # time discretization
# It = range(0, t.shape[0] - 1) # time iterations range
# Ts = np.float64(t[1] - t[0]) # sampling period for staggered grid
# Cn = np.float64(c * Ts / dx)
# print 'Additional iterations for stab: %i' % (nNt)
# Nt = Nt + nNt # add the additional time steps to the main time sequence
# print 'Ratio Cn/Cn_th=%g < 1.0' % (Cn * np.sqrt(2))
src_dly = int(round(1/50./Ts))
print ' FDTD geometrical spreading '
print '-------------------------- Time -------------------------------'
print 'TIME-STEP: Ts=%0.2g s' % (Ts)
print 'NUMBER OF It: Nt=%i' % (Nt)
print 'DURATION: T=%.3f s,' % (T)
print 'SAMP. FREQ.: Fs=%.3f Hz,' % (1 / Ts)
print 'BANDWIDTH: FMAX=%.3f Hz,' % (0.196 / Ts)
print '2PERCENT ACCURACY: %.3f Hz,' % (0.075 / Ts)
print 'COURANT NUMBER: Cn = %.3f' % Cn
print 'Nodes/lambda = %.3f' % (c / src_frq / dx)
print '-------------------------- Space ------------------------------'
print 'SPATIAL-STEP: dx=%g m, dl_max=%g m.' % (dx, dl_max)
print 'DIMENSIONS: Nx=%i cells; Ny=%i cells; Lx=%g m; Ly=%g m.' \
% (Nx, Ny, Lx, Ly)
print '---------------------- Source Signal --------------------------'
print 'SOURCE TYPE: %s,' % src_typ
print 'SOURCE FREQ: f=%g Hz.' % src_frq
print 'SOURCE DELAY: i=%g Iter.' % src_dly
print '---------------------------------------------------------------'
# ==============================================================================
# Variables
# ==============================================================================
p = np.zeros((Nx + 1, Ny + 1), dtype=np.complex128)
p1 = np.zeros((Nx + 1, Ny + 1), dtype=np.complex128)
p2 = np.zeros((Nx + 1, Ny + 1), dtype=np.complex128)
fsrc = np.zeros((Nx + 1, Ny + 1), dtype=np.complex128)
fsrc1 = np.zeros((Nx + 1, Ny + 1), dtype=np.complex128)
fsrc2 = np.zeros((Nx + 1, Ny + 1), dtype=np.complex128)
p_axial = np.zeros((len(d_sr), Nt + 1), dtype=np.complex128)
p_diag = np.zeros((len(d_sr), Nt + 1), dtype=np.complex128)
# ==============================================================================
# Boundaries of the domain, where the BC is calculated
# ==============================================================================
A = 0.;
B = 1;
C = 0.
Nb = np.zeros((Nx + 1, Ny + 1))
i = 1;
Nb[i, 1:-1] = 1.
i = p.shape[0] - 2;
Nb[i, 1:-1] = 1.
j = Ny - 1;
Nb[1:-1, j] = 1.
j = p.shape[1] - 2;
Nb[1:-1, j] = 1.
# ==============================================================================
# Location of the source and receiver(s)
# ==============================================================================
x_src = int(round(Lx / 2. / dx))
y_src = int(round(Ly / 2. / dx))
x_axial = [int(round((Lx / 2. + ii) / dx )) for ii in d_sr]
y_axial = y_src
x_diag = [int(round( (Lx / 2. + ii*np.cos(np.pi/4)) / dx )) for ii in d_sr]
y_diag = x_diag
# # ==============================================================================
# # Remove the old figures of wavefronts
# # ==============================================================================
# if disp_inst_p:
# import os
# import glob
# res_path = os.path.join(base_path.rsplit(os.sep, 1)[0], 'results', 'case%i' % case, 'figures')
# for name in glob.glob(os.path.join(res_path, 'wave_front_*')):
# os.remove(name) # clean up previous plot files
# ==============================================================================
# Calculation of the pressure
# ==============================================================================
depth = 1
bar = progressbar.ProgressBar(maxval=It[-1],
widgets={'(', progressbar.Timer(), ') ', progressbar.Bar('x'), ' (', progressbar.ETA(), ') ', })
bar.start()
for n in It:
# print("Iteration rate %i/%i" % (n, max(It)))
# p1[x_src, y_src] = 1. * src.src_select(src_typ, t, n, src_frq, src_dly) # hard source impl.
fsrc[x_src, y_src] = 1. * src.src_select(src_typ, t, n, src_frq, src_dly) # soft source impl.
p = upd_p_fdtd_srl(p, p1, p2, fsrc, fsrc1, fsrc2,
Nb, c, rho, Ts, dx, Cn, A, B, C, depth)
if disp_inst_p:
instatenous_pressure(n, Nt, p, dx, Ts, Lx, Ly, case, True)
for d in range(len(d_sr)):
p_axial[d, n] = p[x_axial[d], y_axial]
p_diag[d, n] = p[x_diag[d], y_diag[d]]
fsrc1[:, :], fsrc2[:, :] = fsrc.copy(), fsrc1.copy()
p1[:, :], p2[:, :] = p.copy(), p1.copy()
bar.update(n)
bar.finish()
import os
res_path = os.path.join(base_path.rsplit(os.sep, 2)[0], 'results', 'case%i' % case, 'fdtd')
if not os.path.exists(res_path): os.makedirs(res_path)
np.save(os.path.join(res_path, 't_%i.npy' % (h_num)), t)
np.save(os.path.join(res_path, 'Ts_%i.npy' % (h_num)), Ts)
np.save(os.path.join(res_path, 'p_%s_%i.npy' % ('axial', h_num)), p_axial)
np.save(os.path.join(res_path, 'p_%s_%i.npy' % ('diag', h_num)), p_diag)
|
# prenese strani (približno 170 strani seznama, vsaka stran navede 50 iger) in podatke shrani v igre.csv (konzole ohranjajo prvotna imena)
import os, sys, inspect
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from pomozno.obdelovanje_html import obdelava_html_seznam
from pomozno import prenos_strani
from pomozno import vrni_link_do_strani
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
import delo_s_csvji
def preberi_strani_in_izpiši_csv():
vse_igre = []
for i in range(172):
print(i)
link = vrni_link_do_strani.link(i)
html = prenos_strani.prenesi_eno_stran(link)
igre = obdelava_html_seznam.vrni_slovar_podatkov_iger_iz_niza(html)
vse_igre += igre
delo_s_csvji.zapisi_csv(vse_igre, ["id_igre", "ime", "konzola", "konzola_kratica", "ocena", "tezavnost", "dolzina", "povezava"], "igre.csv") |
from app.cache import get_from_cache, set_into_cache, delete_from_cache
import logging as _logging
import hashlib, json
logging = _logging.getLogger("matrufsc2_decorators_cacheable")
logging.setLevel(_logging.DEBUG)
__author__ = 'fernando'
CACHE_CACHEABLE_KEY = "cache/functions/%s/%s"
def cacheable(consider_only=None):
def decorator(fn):
def dec(filters, **kwargs):
if consider_only is not None and filters:
filters = {k: filters[k] for k in filters.iterkeys() if k in consider_only}
filters_hash = hashlib.sha1(json.dumps(filters, sort_keys=True)).hexdigest()
cache_key = CACHE_CACHEABLE_KEY % (
fn.__name__,
filters_hash
)
persistent = kwargs.get("persistent", True)
if kwargs.get("overwrite"):
update_with = kwargs.get("update_with")
if update_with:
result = get_from_cache(cache_key, persistent=persistent).get_result()
if not result:
result = update_with
if type(result) == type(update_with):
logging.debug("Updating cache with passed in value")
set_into_cache(cache_key, update_with, persistent=persistent).get_result()
else:
raise Exception("Types differents: %s != %s" % (str(type(result)), str(type(update_with))))
elif kwargs.get("exclude"):
return delete_from_cache(cache_key, persistent=persistent).get_result()
else:
result = None
else:
result = get_from_cache(cache_key, persistent=persistent).get_result()
if not result:
result = fn(filters)
set_into_cache(cache_key, result, persistent=persistent).get_result()
return result
dec.__name__ = fn.__name__
dec.__doc__ = fn.__doc__
return dec
return decorator |
from flask import Flask, request, jsonify
import utils
app = Flask(__name__)
def extract_req_data(data):
if isinstance(data, str):
return data.split("|")
elif isinstance(data, list):
return data
else:
raise Exception("Invalid Request format !!")
@app.route("/info")
def get_disque_info():
return jsonify(utils.info())
@app.route("/qsize")
def get_queue_size():
payload = request.json
queue = payload["queue_name"]
queue_names=[]
if isinstance(queue, str):
queue_names.append(queue.split("|"))
elif isinstance(queue, list):
queue_names = queue
return jsonify(utils.get_queue_size(queue_names))
@app.route("/show_job")
def show_job():
payload = request.json
job_id = payload["job_id"]
job_ids = []
if isinstance(job_id, str):
job_ids = job_id.split("|")
elif isinstance(job_id, list):
job_ids = job_id
return jsonify(utils.show_job(job_ids))
@app.route("/qstats")
def queue_stats():
payload = request.json
queue_name = payload["queue_name"]
queue_name = extract_req_data(queue_name)
resp = utils.get_queue_stats(queue_name)
return jsonify(resp)
@app.route("/qpeek")
def queue_peek():
payload = request.json
queue_name = payload["queue_name"]
count = payload.get("count")
queue_name = extract_req_data(queue_name)
resp = utils.queue_peek(queue_name)
return jsonify(resp)
|
# MIT licensed
# Copyright (c) 2020 lilydjwg <lilydjwg@gmail.com>, et al.
# Copyright (c) 2017 Felix Yan <felixonmars@archlinux.org>, et al.
import pytest
pytestmark = [pytest.mark.asyncio, pytest.mark.needs_net]
async def test_anitya(get_version):
assert await get_version("shutter", {
"source": "anitya",
"anitya": "fedora/shutter",
}) == "0.97"
|
import requests
def giveme(names: [str], system: str='macOS', target: str='./.gitignore'):
"""
Parameters
----------
names: a list of names. if more than one, concat ignore files
"""
url = 'https://raw.githubusercontent.com/github/gitignore/master/{}.gitignore'
content = b''
for name in names:
_content = requests.get(url.format(name))
content += _content.content
if system:
_content = requests.get('https://raw.githubusercontent.com/github/gitignore/master/Global/{}.gitignore'.format(system))
content += b'\n'
content += _content.content
with open(target, 'wb') as f:
f.write(content)
if __name__ == '__main__':
giveme(['OCaml']) |
# Python Implementation: MPI weather forecasting benchmark
# -*- coding: utf-8 -*-
##
# @file mpiWeatherConv.py
#
# @version 1.0.0
#
# @par Purpose
# Run a MPI Jena weather classification task using keras.
#
# @par Comments
# This is another experiment from Chollet's book featuring a
# temperature prediction task using a 1-D convolution and Gated
# Recurrent Unit (GRU) input layer.
#
# This is Python 3 code!
# Known Bugs: none
#
# @author Ekkehard Blanz <Ekkehard.Blanz@gmail.com> (C) 2019
#
# @copyright See COPYING file that comes with this distribution
#
# File history:
#
# Date | Author | Modification
# -----------------+----------------+------------------------------------------
# Wed Jul 17 2019 | Ekkehard Blanz | converted from Chollet's book
# | |
import os
import time
import numpy as np
from keras import models
from keras import layers
import os
import time
import numpy as np
from keras import models
from keras import layers
def prepData( originalDatasetDir, trainSize ):
fname = os.path.join( originalDatasetDir, 'mpi_roof_2009_2016.csv' )
f = open(fname)
data = f.read()
f.close()
lines = data.split('\n')
header = lines[0].split(',')
if lines[-1]:
lines = lines[1:]
else:
lines = lines[1:-1]
float_data = np.zeros((len(lines), len(header) - 1))
for i, line in enumerate(lines):
values = [float(x) for x in line.split(',')[1:]]
float_data[i, :] = values
mean = float_data[:trainSize].mean(axis=0)
float_data -= mean
std = float_data[:trainSize].std(axis=0)
float_data /= std
return float_data
def generator( data, lookback, delay, min_index, max_index,
shuffle=False, batch_size=128, step=6 ):
"""!
@param data The original array of floating-point data, which you
normalized above
@param lookback How many timesteps back the input data should go
@param delay How many timesteps in the future the target should be
@param min_index and max_index Indices in the data array that delimit which
timesteps to draw from. This is useful for keeping a segment of the
data for validation and another for testing
@param shuffle Whether to shuffle the samples or draw them in chronological
order
@param batch_size The number of samples per batch
@param step—The period, in timesteps, at which you sample data. You’ll set
it to 6 in order to draw one data point every hour
"""
if max_index is None:
max_index = len(data) - delay - 1
i = min_index + lookback
while 1:
if shuffle:
rows = np.random.randint(
min_index + lookback, max_index, size=batch_size)
else:
if i + batch_size >= max_index:
i = min_index + lookback
rows = np.arange(i, min(i + batch_size, max_index))
i += len(rows)
samples = np.zeros((len(rows),
lookback // step,
data.shape[-1]))
targets = np.zeros((len(rows),))
for j, row in enumerate(rows):
indices = range(rows[j] - lookback, rows[j], step)
samples[j] = data[indices]
targets[j] = data[rows[j] + delay][1]
yield samples, targets
def testRun( dtype ):
lookback = 1440 # ten days
step = 6 # one hour
delay = 144 # one day - which element to predict
batch_size = 128
epochs = 10
trainSize = 200000
validationSize = 100000
float_data = prepData( "../../Data/mpiJenaClimate", trainSize )
testSize = len( float_data ) - (trainSize + validationSize + delay) - 1
# customizations
#trainSize = 0
validationSize = 0
#testSize = lookback + batch_size + 1
#testSize = 0
last = 0
if trainSize:
first = 0
last = trainSize
train_gen = generator( float_data,
lookback=lookback,
delay=delay,
min_index=first,
max_index=last,
shuffle=True,
step=step,
batch_size=batch_size )
if validationSize:
first = last
last = first + validationSize
val_gen = generator( float_data,
lookback=lookback,
delay=delay,
min_index=first,
max_index=last,
step=step,
batch_size=batch_size)
if testSize:
first = last
last = first + testSize
test_gen = generator( float_data,
lookback=lookback,
delay=delay,
min_index=first,
max_index=last,
step=step,
batch_size=batch_size )
if validationSize:
val_steps = validationSize- lookback
else:
val_steps = 0
if testSize:
test_steps = testSize - lookback
else:
test_steps = 0
network = models.Sequential()
network.add( layers.Conv1D( 32, 5, activation="relu",
input_shape=(None, float_data.shape[-1]) ) )
network.add( layers.MaxPooling1D( 3 ) )
network.add( layers.Conv1D( 32, 5, activation="relu" ) )
network.add( layers.GRU( 32, dropout=0.1, recurrent_dropout=0.5 ) )
network.add( layers.Dense( 1 ) )
network.compile( optimizer="rmsprop", loss="mae" )
if trainSize:
start = time.time()
if val_steps:
history = network.fit_generator( train_gen,
steps_per_epoch=500,
epochs=epochs,
validation_data=val_gen,
validation_steps=val_steps )
# do whatever analysis with history
else:
network.fit_generator( train_gen,
steps_per_epoch=500,
epochs=epochs )
trainingTime = time.time() - start
else:
trainingTime = 0
if testSize:
start = time.time()
testLoss = network.evaluate_generator( test_gen,
steps=(test_steps // batch_size),
verbose=1 )
testAccuracy = None # not a classification task
testTime = time.time() - start
else:
testTime = 0
testAccuracy = None
return (trainSize, testSize,
trainingTime, testTime, testAccuracy, network)
|
# Copyright (c) 2018-2019 Alexander L. Hayes (@hayesall)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from bs4 import BeautifulSoup as bs
import sys
import unittest
# This set of tests is interested in ffscraper.fanfic.review
sys.path.append('./')
from ffscraper.fanfic import review
class ReviewsTest(unittest.TestCase):
# ffscraper.fanfic.review
def test_reviews_1(self):
soup = bs("""<tbody><tr >
<td style='padding-top:10px;padding-bottom:10px'>
<span style='float:right'>
<a href='https://www.fanfiction.net/' style='color:#333333;
border-bottom:0px;' title='Reply to Review'></span>
<a href='/u/123/persona'>persona</a>
<small style='color:gray'>chapter 10 .
<span data-xutime='11111'>5/3</span>
</small><div style='margin-top:5px'>Most recent.</div>
</td></tr>
<tr ><td style='padding-top:10px;padding-bottom:10px'>
<span style='float:right'>
<a href='https://www.fanfiction.net/' style='color:#333333;
border-bottom:0px;' title='Reply to Review'></span>
<a href='/u/123/persona'>persona</a>
<small style='color:gray'>chapter 10 .
<span data-xutime='11110'>5/3</span>
</small><div style='margin-top:5px'>Same person.</div>
</td></tr>
<tr ><td style='padding-top:10px;padding-bottom:10px'>
<img class='round36' style='clear:left;float:left;
margin-right:3px;padding:2px;border:1px solid #ccc;
-moz-border-radius:2px;-webkit-border-radius:2px;'
src='/static/images/d_60_90.jpg' width=50 height=50> Guest
<small style='color:gray'>chapter 2 .
<span data-xutime='22222'>5/8/1985</span>
</small><div style='margin-top:5px'>Anonymous third.</div>
</td></tr></tbody>""", 'html.parser')
reviews = review._reviews_in_table(soup)
reality = [r for r in reviews]
self.assertEqual(reality[0][0], '123')
self.assertEqual(reality[0][1], '10')
self.assertEqual(reality[0][2], '11111')
self.assertEqual(reality[0][3], 'Most recent.')
self.assertEqual(reality[1][0], '123')
self.assertEqual(reality[1][1], '10')
self.assertEqual(reality[1][2], '11110')
self.assertEqual(reality[1][3], 'Same person.')
self.assertEqual(reality[2][0], 'Guest')
self.assertEqual(reality[2][1], '2')
self.assertEqual(reality[2][2], '22222')
self.assertEqual(reality[2][3], 'Anonymous third.')
|
"""Common Wrapper/Interface around various video reading/writing tools to make video reading stable,
consistent and super easy around different systems and OS.
Backends
- OpenCV (in-development)
# How to Read Video
```python
from vidsz import Reader
# open reader
reader = Reader("static/countdown.mp4")
# print info: width, height, fps etc.
print(reader)
# access specific things
print(reader.width, reader.height, reader.fps)
# access number-of-frames/seconds/minutes that have been read
print(reader.frame_count, reader.seconds, reader.minutes)
# read frames with while loop
while reader.is_open():
# returns ndarry-frame or None if nothing left to read
frame = reader.read()
# read frame with for loop
for frame in reader:
# use frame however you like
pass
# release
reader.release()
# or read with a with block
with Reader("static/countdown.mp4") as reader:
frame = reader.read()
frames = reader.read_all() # list of frames returned
```
# How to Write Video
```python
from vidsz import Reader, Writer
video_fname = "static/countdown.mp4"
# open reader
reader = Reader(video_fname)
# start writer with the Reader object
# by default it'll append _out in the name of the output video
writer = Writer(reader)
# start writer with your settings;
# you can also give any combinations of
# following settings with Reader object to
# overwrite default settings
writer = Writer("out.mp4", width=680, height=340, fps=30, ext="avi")
# print writer info
print(writer)
# write single frame
frame = reader.read()
writer.write(frame)
# write list of frames
# or directly write everything from reader object
writer.write_all(reader)
# close off
writer.release()
# using "with" block, write "static/countdown_out.mp4" (clone of input)
with Reader(video_fname) as reader:
with Writer(reader) as writer:
writer.write_all(reader)
```
"""
__version__ = "0.1.1"
|
#! /usr/bin/env python
"""
Copyright 2010-2019 University Of Southern California
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import division, print_function
# Import Python modules
import os
import unittest
# Import Broadband modules
import cmp_bbp
import seqnum
import bband_utils
from install_cfg import InstallCfg
from wcc_siteamp_cfg import WccSiteampCfg
from wcc_siteamp import WccSiteamp
class TestWccSiteamp(unittest.TestCase):
"""
Acceptance Test for wcc_siteamp.py
"""
def setUp(self):
self.install = InstallCfg()
self.wcc_siteamp_cfg = WccSiteampCfg("LABasin500", "GP")
os.chdir(self.install.A_INSTALL_ROOT)
self.stations = "test_stat.txt"
self.sim_id = int(seqnum.get_seq_num())
self.freqs = ['lf', 'hf']
refdir = os.path.join(self.install.A_TEST_REF_DIR, "gp")
indir = os.path.join(self.install.A_IN_DATA_DIR, str(self.sim_id))
tmpdir = os.path.join(self.install.A_TMP_DATA_DIR, str(self.sim_id))
outdir = os.path.join(self.install.A_OUT_DATA_DIR, str(self.sim_id))
logdir = os.path.join(self.install.A_OUT_LOG_DIR, str(self.sim_id))
# Create all directories
bband_utils.mkdirs([indir, tmpdir, outdir, logdir], print_cmd=False)
# Copy station list
cmd = "cp %s %s" % (os.path.join(refdir, self.stations), indir)
bband_utils.runprog(cmd)
# Copy LF and HF seismograms
for i in range(1, 6):
for freq in self.freqs:
cmd = "cp %s %s" % (os.path.join(refdir,
"s%02d-%s.bbp" %
(i, freq)),
os.path.join(tmpdir,
"%d.s%02d-%s.bbp" %
(self.sim_id, i, freq)))
bband_utils.runprog(cmd)
def test_wcc_siteamp(self):
"""
Test GP site response module
"""
wcc_obj = WccSiteamp(self.stations, "GP",
"LABasin500", sim_id=self.sim_id)
wcc_obj.run()
freqs = ['lf', 'hf']
for i in range(1, 6):
for freq in freqs:
ref_file = os.path.join(self.install.A_TEST_REF_DIR,
"gp",
"s%02d-%s-site.bbp" %
(i, freq))
bbpfile = os.path.join(self.install.A_TMP_DATA_DIR,
str(self.sim_id),
"%d.s%02d-%s.acc.bbp" %
(self.sim_id, i, freq))
self.failIf(cmp_bbp.cmp_bbp(ref_file, bbpfile) != 0,
"output %s BBP file %s does not match reference %s bbp file %s " %
(freq, bbpfile, freq, ref_file))
if __name__ == '__main__':
SUITE = unittest.TestLoader().loadTestsFromTestCase(TestWccSiteamp)
unittest.TextTestRunner(verbosity=2).run(SUITE)
|
import urllib
import json
import os
from flask import Blueprint, flash, redirect, render_template, url_for, request
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename
from app import app, db
from .models import Blog, Comment
main = Blueprint('main', __name__)
# helper functions to get random quotes
def get_random_quote():
quote_url = 'http://quotes.stormconsultancy.co.uk/random.json'
with urllib.request.urlopen(quote_url) as url:
quote_data = url.read()
quote = json.loads(quote_data)
return quote
@main.route('/')
def index():
from sqlalchemy import desc
# sorted_blogs = Blog.query.order_by(desc(Blog.date_posted)).all()
blogs = Blog.query.all()
quote = get_random_quote()
return render_template('index.html', blogs=blogs, quote=quote,)
@main.route('/profile')
def profile():
blogs = Blog.query.filter_by(author=current_user.id).all()
quote = get_random_quote()
page = 'profile'
return render_template('profile.html', blogs=blogs, quote=quote, page=page)
@main.route('/create_blog', methods=['GET', 'POST'])
@login_required
def create_blog():
quote = get_random_quote()
if request.method == 'POST':
title = request.form.get('title')
content = request.form.get('content')
category = request.form.get('category')
author = current_user.id
blog = Blog(title=title, content=content,
category=category, author=author)
db.session.add(blog)
db.session.commit()
return redirect(url_for("main.index"))
return render_template('create_blog.html', quote=quote)
@main.route('/update_blog/<blog_id>', methods=['GET', 'POST'])
@login_required
def update_blog(blog_id):
quote = get_random_quote()
blog = Blog.query.filter_by(id=blog_id).first()
if not blog:
flash('Blog does not exist')
return redirect(url_for('main.index'))
# if changes are made, update the blog
if request.method == 'POST':
blog.title = request.form.get('title')
blog.content = request.form.get('content')
blog.category = request.form.get('category')
db.session.commit()
return redirect(url_for('main.index'))
# Auto fill the blog details
return render_template('update_blog.html', blog=blog, current_user=current_user, quote=quote)
@main.route('/delete_blog/<blog_id>', methods=['GET', 'POST'])
@login_required
def delete_blog(blog_id):
blog = Blog.query.filter_by(id=blog_id).first()
if not blog:
flash('Blog does not exist')
return redirect(url_for('main.index'))
db.session.delete(blog)
db.session.commit()
return redirect(url_for('main.index'))
@main.route('/blog/<blog_id>')
def blog(blog_id):
blog = Blog.query.filter_by(id=blog_id).first()
quote = get_random_quote()
if not blog:
flash('Blog does not exist')
return redirect(url_for('main.index'))
return render_template('blog.html', blog=blog, quote=quote)
@main.route('/create-comment/<blog_id>', methods=['GET', 'POST'])
def create_comment(blog_id):
blog = Blog.query.filter_by(id=blog_id).first()
if not blog:
flash('Blog does not exist')
return redirect(url_for('main.index'))
if request.method == 'POST':
username = request.form.get('name')
comment = request.form.get('comment')
comment = Comment(name=username, content=comment, blog_id=blog.id)
db.session.add(comment)
db.session.commit()
return redirect(url_for('main.blog', blog_id=blog.id))
@main.route('/delete-comment/<comment_id>', methods=['GET', 'POST'])
@login_required
def delete_comment(comment_id):
comment = Comment.query.filter_by(id=comment_id).first()
if not comment:
flash('Comment does not exist')
return redirect(url_for('main.index'))
db.session.delete(comment)
db.session.commit()
return redirect(url_for('main.blog', blog_id=comment.blog_id))
ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'gif', 'svg'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@main.route('/upload_profile_pic', methods=['GET', 'POST'])
@login_required
def upload_profile_pic():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# update the profile picture
current_user.profile_pic = filename
db.session.commit()
return redirect(url_for('main.profile'))
return render_template('upload_profile_pic.html')
@main.route('/category/<category>')
def category(category):
quote = get_random_quote()
blogs = Blog.query.filter_by(category=category).all()
return render_template('category.html', blogs=blogs, category=category, quote=quote)
# def sidebar():
# categories = Blog.category.query.all()
# print('*********************************************************')
# print(categories)
# return render_template('sidebar.html', categories=categories)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.