max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
email_service.py
t04glovern/UGATIT
28
6613651
from os import environ from os.path import join, dirname from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import re import boto3 import urllib.parse class EmailService(object): EMAIL_REGEX = re.compile( r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") def __init__(self): self.ses = boto3.client('ses') def is_email(self, candidate): is_email = False if self.EMAIL_REGEX.match(candidate): is_email = True return is_email def send_email(self, email_addr, image_url): email = self.build_email(email_addr, image_url) self.ses.send_raw_email( RawMessage={'Data': email.as_string()}, Source=email['From'], Destinations=[email['To']] ) def build_email(self, email_addr, image_url): email = MIMEMultipart() email['Subject'] = 'Your Anime Selfie is ready!' email['From'] = environ.get('SENDER_EMAIL') email['To'] = email_addr email.preamble = 'Multipart message.\n' email_body = self.build_email_body(image_url) part = MIMEText(email_body, 'html') email.attach(part) return email @staticmethod def build_email_body(image_url): image_url_escaped = urllib.parse.quote(image_url) html_file = join(dirname(__file__), 'templates', 'template.html') html_file = open(html_file, 'r') email = html_file.read() email = email.replace('{{image_url}}', image_url) email = email.replace('{{image_url_escaped}}', image_url_escaped) return email
from os import environ from os.path import join, dirname from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import re import boto3 import urllib.parse class EmailService(object): EMAIL_REGEX = re.compile( r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") def __init__(self): self.ses = boto3.client('ses') def is_email(self, candidate): is_email = False if self.EMAIL_REGEX.match(candidate): is_email = True return is_email def send_email(self, email_addr, image_url): email = self.build_email(email_addr, image_url) self.ses.send_raw_email( RawMessage={'Data': email.as_string()}, Source=email['From'], Destinations=[email['To']] ) def build_email(self, email_addr, image_url): email = MIMEMultipart() email['Subject'] = 'Your Anime Selfie is ready!' email['From'] = environ.get('SENDER_EMAIL') email['To'] = email_addr email.preamble = 'Multipart message.\n' email_body = self.build_email_body(image_url) part = MIMEText(email_body, 'html') email.attach(part) return email @staticmethod def build_email_body(image_url): image_url_escaped = urllib.parse.quote(image_url) html_file = join(dirname(__file__), 'templates', 'template.html') html_file = open(html_file, 'r') email = html_file.read() email = email.replace('{{image_url}}', image_url) email = email.replace('{{image_url_escaped}}', image_url_escaped) return email
none
1
2.294703
2
lukcid2.py
omdahshaabi/LuckCid
1
6613652
import random import string import tkMessageBox from Tkinter import * # Returns a combination of letter & digits def gen(): return random.choice(list('abcdef' + string.digits)) # prints the first digits until %, and starts printing random generation from the gen function and converts to upper case # and then opens up a file and appends every click as a new line. def printme(): combo1 = '00000001008%s111%s1%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s' % (gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper()) with open("cid_file1.txt", 'a') as outfile: outfile.write(combo1 + '\n') entryText.set(combo1) def printme2(): combo2 = '00000001008%s000%s1%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s' % (gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper()) with open("cid_file2.txt", 'a') as outfile: outfile.write(combo2 + '\n') entryText2.set(combo2) # Main Window window = Tk() # Size of the window window.geometry("500x300") # Tittle window.title("Lukcid v2") # Disable resizing window.resizable(width=FALSE, height=FALSE) # *** Status Bar *** status = Label(window, text="Twitter: 0Katz Youtube: Simple Dev ", bd=1, relief=SUNKEN, anchor=W) status.pack(side=BOTTOM) # Variable holding the image photo = PhotoImage(file="pirate.png") # Invoke the image and displays it on the main window label = Label(window, image=photo) label.pack() # Prints an info warning before program loads and whishes you good luck :) tkMessageBox.showinfo("Made by 0Katz", 'May the force be with you!') # Entry Text entryText = StringVar(window) entryText2 = StringVar(window) # Text Box Button which generates the console ids with 1's textbox = Entry(window, textvariable=entryText).place(x=260, y=100, width=227) botton = Button(window, text="Generate", command=printme).place(x=356, y=126) # Text Box and Button which generates console ids with 0's textbox2 = Entry(window, textvariable=entryText2).place(x=260, y=160, width=227) botton = Button(window, text="Generate", command=printme2).place(x=356, y=186) # Doesn't work yet, just there for an idea until # We can figure a way to use .Net framework with python tmApi = Radiobutton(window, text="TMAPI", value=1).place(x=17, y=140) ccApi = Radiobutton(window, text="CCAPI", value=1).place(x=85, y=140) apiButton = Button(window, text="Stablish Connection").place(x=26, y=180) ipPs3 = Entry(window).place(x=20, y=100) ipLabel = Label(window, text="IP ADDRESS").place(x=37, y=70) genLabel = Label(window, text="CONSOLE ID").place(x=350, y=70) window.mainloop()
import random import string import tkMessageBox from Tkinter import * # Returns a combination of letter & digits def gen(): return random.choice(list('abcdef' + string.digits)) # prints the first digits until %, and starts printing random generation from the gen function and converts to upper case # and then opens up a file and appends every click as a new line. def printme(): combo1 = '00000001008%s111%s1%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s' % (gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper()) with open("cid_file1.txt", 'a') as outfile: outfile.write(combo1 + '\n') entryText.set(combo1) def printme2(): combo2 = '00000001008%s000%s1%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s' % (gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper(), gen().upper()) with open("cid_file2.txt", 'a') as outfile: outfile.write(combo2 + '\n') entryText2.set(combo2) # Main Window window = Tk() # Size of the window window.geometry("500x300") # Tittle window.title("Lukcid v2") # Disable resizing window.resizable(width=FALSE, height=FALSE) # *** Status Bar *** status = Label(window, text="Twitter: 0Katz Youtube: Simple Dev ", bd=1, relief=SUNKEN, anchor=W) status.pack(side=BOTTOM) # Variable holding the image photo = PhotoImage(file="pirate.png") # Invoke the image and displays it on the main window label = Label(window, image=photo) label.pack() # Prints an info warning before program loads and whishes you good luck :) tkMessageBox.showinfo("Made by 0Katz", 'May the force be with you!') # Entry Text entryText = StringVar(window) entryText2 = StringVar(window) # Text Box Button which generates the console ids with 1's textbox = Entry(window, textvariable=entryText).place(x=260, y=100, width=227) botton = Button(window, text="Generate", command=printme).place(x=356, y=126) # Text Box and Button which generates console ids with 0's textbox2 = Entry(window, textvariable=entryText2).place(x=260, y=160, width=227) botton = Button(window, text="Generate", command=printme2).place(x=356, y=186) # Doesn't work yet, just there for an idea until # We can figure a way to use .Net framework with python tmApi = Radiobutton(window, text="TMAPI", value=1).place(x=17, y=140) ccApi = Radiobutton(window, text="CCAPI", value=1).place(x=85, y=140) apiButton = Button(window, text="Stablish Connection").place(x=26, y=180) ipPs3 = Entry(window).place(x=20, y=100) ipLabel = Label(window, text="IP ADDRESS").place(x=37, y=70) genLabel = Label(window, text="CONSOLE ID").place(x=350, y=70) window.mainloop()
en
0.845537
# Returns a combination of letter & digits # prints the first digits until %, and starts printing random generation from the gen function and converts to upper case # and then opens up a file and appends every click as a new line. # Main Window # Size of the window # Tittle # Disable resizing # *** Status Bar *** # Variable holding the image # Invoke the image and displays it on the main window # Prints an info warning before program loads and whishes you good luck :) # Entry Text # Text Box Button which generates the console ids with 1's # Text Box and Button which generates console ids with 0's # Doesn't work yet, just there for an idea until # We can figure a way to use .Net framework with python
3.646261
4
Scripts/lab4b/aSurname4b.py
PepperBurst/DSP
1
6613653
<reponame>PepperBurst/DSP<filename>Scripts/lab4b/aSurname4b.py def coeff422(): b = [] a = [] b.append([0.16, -0.48, 0.48, -0.16]) b.append([0.634, 0, -0.634]) b.append([0.634, 0, 0.634]) b.append([1, -5, 10]) a.append([1, 0.13, 0.52, 0.3]) a.append([1, 0, -0.268]) a.append([1, 0, 0.268]) a.append([10, -5, 1]) return b, a
def coeff422(): b = [] a = [] b.append([0.16, -0.48, 0.48, -0.16]) b.append([0.634, 0, -0.634]) b.append([0.634, 0, 0.634]) b.append([1, -5, 10]) a.append([1, 0.13, 0.52, 0.3]) a.append([1, 0, -0.268]) a.append([1, 0, 0.268]) a.append([10, -5, 1]) return b, a
none
1
2.708161
3
export_model.py
isamu-isozaki/toxic-joke-generator
0
6613654
#!/usr/bin/env python3 import fire import json import os import numpy as np import tensorflow as tf import model, sample, encoder from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import signature_def_utils from tensorflow.python.saved_model import tag_constants from tensorflow.python.saved_model import utils from tensorflow.python.util import compat def export_model( model_name='117M', seed=None, nsamples=0, batch_size=1, length=None, top_k=0, version=1, folder_id=None, ): """ Run the sample_model :model_name=117M : String, which model to use :seed=None : Integer seed for random number generators, fix seed to reproduce results :nsamples=0 : Number of samples to return, if 0, continues to generate samples indefinately. :batch_size=1 : Number of batches (only affects speed/memory). :length=None : Number of tokens in generated text, if None (default), is determined by model hyperparameters :top_k=0 : Integer value controlling diversity. 1 means only 1 word is considered for each step (token), resulting in deterministic completions, while 40 means 40 words are considered at each step. 0 (default) is a special setting meaning no restrictions. 40 generally is a good value. :version=1 : Integer value giving the version the model is exported as. :folder_id=None : If the google drive is being used, specify the folder to upload here. Otherwise, keep as None : """ enc = encoder.get_encoder(model_name) hparams = model.default_hparams() with open(os.path.join('models', model_name, 'hparams.json')) as f: hparams.override_from_dict(json.load(f)) if length is None: length = hparams.n_ctx elif length > hparams.n_ctx: raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx) with tf.Session(graph=tf.Graph()) as sess: np.random.seed(seed) tf.set_random_seed(seed) temperature = tf.placeholder("float", [1]) output_tensor = sample.sample_sequence( hparams=hparams, length=length, start_token=enc.encoder['<|endoftext|>'], batch_size=batch_size, temperature=temperature, top_k=top_k )[:, 1:] saver = tf.train.Saver() ckpt = tf.train.latest_checkpoint(os.path.join('models', model_name)) saver.restore(sess, ckpt) def export_model(path):#Thanks Siraj! Couldn't have done it without you! #Link is https://github.com/llSourcell/How-to-Deploy-a-Tensorflow-Model-in-Production/blob/master/custom_model.py print("Exporting trained model to ", path) builder = saved_model_builder.SavedModelBuilder(path) input_temperature = utils.build_tensor_info(temperature) output = utils.build_tensor_info(output_tensor) prediction_signature = signature_def_utils.build_signature_def( inputs={'temperature': input_temperature}, outputs={'output': output}, method_name=signature_constants.PREDICT_METHOD_NAME) builder.add_meta_graph_and_variables( sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ 'predict': prediction_signature }, main_op=tf.tables_initializer()) builder.save() base_directory = "./export_model" export_path = f"./export_model/{version}" export_model(export_path) if(folder_id != None): from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # 1. Authenticate and create the PyDrive client. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) for content in os.listdir(export_path): f = drive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": folder_id}]}) f.SetContentFile(f"{export_path}"+"/"+content) f.Upload() if __name__ == '__main__': fire.Fire(export_model)
#!/usr/bin/env python3 import fire import json import os import numpy as np import tensorflow as tf import model, sample, encoder from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import signature_def_utils from tensorflow.python.saved_model import tag_constants from tensorflow.python.saved_model import utils from tensorflow.python.util import compat def export_model( model_name='117M', seed=None, nsamples=0, batch_size=1, length=None, top_k=0, version=1, folder_id=None, ): """ Run the sample_model :model_name=117M : String, which model to use :seed=None : Integer seed for random number generators, fix seed to reproduce results :nsamples=0 : Number of samples to return, if 0, continues to generate samples indefinately. :batch_size=1 : Number of batches (only affects speed/memory). :length=None : Number of tokens in generated text, if None (default), is determined by model hyperparameters :top_k=0 : Integer value controlling diversity. 1 means only 1 word is considered for each step (token), resulting in deterministic completions, while 40 means 40 words are considered at each step. 0 (default) is a special setting meaning no restrictions. 40 generally is a good value. :version=1 : Integer value giving the version the model is exported as. :folder_id=None : If the google drive is being used, specify the folder to upload here. Otherwise, keep as None : """ enc = encoder.get_encoder(model_name) hparams = model.default_hparams() with open(os.path.join('models', model_name, 'hparams.json')) as f: hparams.override_from_dict(json.load(f)) if length is None: length = hparams.n_ctx elif length > hparams.n_ctx: raise ValueError("Can't get samples longer than window size: %s" % hparams.n_ctx) with tf.Session(graph=tf.Graph()) as sess: np.random.seed(seed) tf.set_random_seed(seed) temperature = tf.placeholder("float", [1]) output_tensor = sample.sample_sequence( hparams=hparams, length=length, start_token=enc.encoder['<|endoftext|>'], batch_size=batch_size, temperature=temperature, top_k=top_k )[:, 1:] saver = tf.train.Saver() ckpt = tf.train.latest_checkpoint(os.path.join('models', model_name)) saver.restore(sess, ckpt) def export_model(path):#Thanks Siraj! Couldn't have done it without you! #Link is https://github.com/llSourcell/How-to-Deploy-a-Tensorflow-Model-in-Production/blob/master/custom_model.py print("Exporting trained model to ", path) builder = saved_model_builder.SavedModelBuilder(path) input_temperature = utils.build_tensor_info(temperature) output = utils.build_tensor_info(output_tensor) prediction_signature = signature_def_utils.build_signature_def( inputs={'temperature': input_temperature}, outputs={'output': output}, method_name=signature_constants.PREDICT_METHOD_NAME) builder.add_meta_graph_and_variables( sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ 'predict': prediction_signature }, main_op=tf.tables_initializer()) builder.save() base_directory = "./export_model" export_path = f"./export_model/{version}" export_model(export_path) if(folder_id != None): from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials # 1. Authenticate and create the PyDrive client. auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) for content in os.listdir(export_path): f = drive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": folder_id}]}) f.SetContentFile(f"{export_path}"+"/"+content) f.Upload() if __name__ == '__main__': fire.Fire(export_model)
en
0.78722
#!/usr/bin/env python3 Run the sample_model :model_name=117M : String, which model to use :seed=None : Integer seed for random number generators, fix seed to reproduce results :nsamples=0 : Number of samples to return, if 0, continues to generate samples indefinately. :batch_size=1 : Number of batches (only affects speed/memory). :length=None : Number of tokens in generated text, if None (default), is determined by model hyperparameters :top_k=0 : Integer value controlling diversity. 1 means only 1 word is considered for each step (token), resulting in deterministic completions, while 40 means 40 words are considered at each step. 0 (default) is a special setting meaning no restrictions. 40 generally is a good value. :version=1 : Integer value giving the version the model is exported as. :folder_id=None : If the google drive is being used, specify the folder to upload here. Otherwise, keep as None : #Thanks Siraj! Couldn't have done it without you! #Link is https://github.com/llSourcell/How-to-Deploy-a-Tensorflow-Model-in-Production/blob/master/custom_model.py # 1. Authenticate and create the PyDrive client. #fileLink", "id": folder_id}]})
2.323997
2
plot_vlc_compare_runs.py
serl/hls-bba-testbed
3
6613655
<gh_stars>1-10 import sys, os from pylibs.log import Session from pylibs.plot import plotCompareVLCRuns from pylibs.parallelize import Parallelize if __name__ == "__main__": filenames = sys.argv[1:] assert len(filenames) export = len(filenames) > 1 if filenames[0] == 'export': export = True filenames = sys.argv[2:] for filename in filenames: filename = filename.rstrip(os.sep) sessions = [] run = 1 funcs = [] while True: runpath = os.path.join(filename, str(run)) if not os.path.isdir(runpath): runpath += '.tar.gz' if not os.path.isfile(runpath): break print "Reading {0} run {1}...".format(filename, run) funcs.append({'args': (runpath,)}) run += 1 p = Parallelize(funcs, fn=Session.read) p.run() sessions = p.results if len(sessions) == 0: print "No runs in {0}".format(filename) continue print "Plotting {0}...".format(filename) plotCompareVLCRuns(sessions, os.path.join('tests', sessions[0].collection, 'compare_runs_' + sessions[0].name + '.png') if export else False, thickness_factor=2, size=(12,9)) #plotCompareVLCRuns(sessions, sessions[0].collection + '_compare_runs_' + sessions[0].name + '_paper.svg' if export else False, thickness_factor=2, size=(9,12))
import sys, os from pylibs.log import Session from pylibs.plot import plotCompareVLCRuns from pylibs.parallelize import Parallelize if __name__ == "__main__": filenames = sys.argv[1:] assert len(filenames) export = len(filenames) > 1 if filenames[0] == 'export': export = True filenames = sys.argv[2:] for filename in filenames: filename = filename.rstrip(os.sep) sessions = [] run = 1 funcs = [] while True: runpath = os.path.join(filename, str(run)) if not os.path.isdir(runpath): runpath += '.tar.gz' if not os.path.isfile(runpath): break print "Reading {0} run {1}...".format(filename, run) funcs.append({'args': (runpath,)}) run += 1 p = Parallelize(funcs, fn=Session.read) p.run() sessions = p.results if len(sessions) == 0: print "No runs in {0}".format(filename) continue print "Plotting {0}...".format(filename) plotCompareVLCRuns(sessions, os.path.join('tests', sessions[0].collection, 'compare_runs_' + sessions[0].name + '.png') if export else False, thickness_factor=2, size=(12,9)) #plotCompareVLCRuns(sessions, sessions[0].collection + '_compare_runs_' + sessions[0].name + '_paper.svg' if export else False, thickness_factor=2, size=(9,12))
en
0.20316
#plotCompareVLCRuns(sessions, sessions[0].collection + '_compare_runs_' + sessions[0].name + '_paper.svg' if export else False, thickness_factor=2, size=(9,12))
2.140019
2
project/service/serve.py
hnliu-git/decepticon
0
6613656
<reponame>hnliu-git/decepticon<gh_stars>0 import os from flask import Flask from flask import render_template, request from t5_inf import RaceInfModule # Flask App app = Flask(__name__) app.config["TEMPLATES_AUTO_RELOAD"] = True app.config["APPLICATION_ROOT"] = os.environ.get("APP_ROOT","/service") # Model q_model = RaceInfModule.load_from_checkpoint(app.config["APPLICATION_ROOT"]+"/ckpts/t5_que.ckpt") q_model.eval() d_model = RaceInfModule.load_from_checkpoint(app.config["APPLICATION_ROOT"]+"/ckpts/t5_dis.ckpt") d_model.eval() @app.route("/") def index(): return render_template("index.html",app_root=app.config["APPLICATION_ROOT"]) @app.route("/predict",methods=["POST"]) def predict(): global q_model, d_model article=request.json["article"] answer = request.json["answer"] print("Start generating..") question = q_model.generate_sentence(article, answer) print("Question generated!") distractor = d_model.generate_sentence(article, answer, question) print("Distractor generated!") generation = {'question': question, 'distractor': distractor} generation_html=render_template("result.html",generation=generation) return {"generation_html":generation_html} @app.route("/predict_json",methods=["POST"]) def predict_json(): global q_model, d_model article = request.json["article"] answer = request.json["answer"] question = q_model.generate_sentence(article, answer) distractor = d_model.generate_sentence(article, answer, question) generation = {'question': question, 'distractor': distractor} return {"generation":generation}
import os from flask import Flask from flask import render_template, request from t5_inf import RaceInfModule # Flask App app = Flask(__name__) app.config["TEMPLATES_AUTO_RELOAD"] = True app.config["APPLICATION_ROOT"] = os.environ.get("APP_ROOT","/service") # Model q_model = RaceInfModule.load_from_checkpoint(app.config["APPLICATION_ROOT"]+"/ckpts/t5_que.ckpt") q_model.eval() d_model = RaceInfModule.load_from_checkpoint(app.config["APPLICATION_ROOT"]+"/ckpts/t5_dis.ckpt") d_model.eval() @app.route("/") def index(): return render_template("index.html",app_root=app.config["APPLICATION_ROOT"]) @app.route("/predict",methods=["POST"]) def predict(): global q_model, d_model article=request.json["article"] answer = request.json["answer"] print("Start generating..") question = q_model.generate_sentence(article, answer) print("Question generated!") distractor = d_model.generate_sentence(article, answer, question) print("Distractor generated!") generation = {'question': question, 'distractor': distractor} generation_html=render_template("result.html",generation=generation) return {"generation_html":generation_html} @app.route("/predict_json",methods=["POST"]) def predict_json(): global q_model, d_model article = request.json["article"] answer = request.json["answer"] question = q_model.generate_sentence(article, answer) distractor = d_model.generate_sentence(article, answer, question) generation = {'question': question, 'distractor': distractor} return {"generation":generation}
en
0.647125
# Flask App # Model
2.281823
2
_unittests/ut_pycode/test_pip_helper.py
Pandinosaurus/pyquickhelper
18
6613657
""" @brief test tree node (time=2s) """ import unittest import pandas from pyquickhelper.pycode import ExtTestCase from pyquickhelper.pycode.pip_helper import ( get_packages_list, package2dict, get_package_info, PQPipError) class TestPipHelper(ExtTestCase): def test_exc(self): exc = PQPipError('cmd', 'out', 'err') msg = str(exc) self.assertEqual([msg.replace('\n', '')], [ 'CMD:cmdOUT:out[piperror]err']) def test_pip_list(self): li = get_packages_list() dt = package2dict(li[0]) avoid = {'py_version'} empty = [] for k, v in dt.items(): if k not in avoid: if k is None: empty.append(k) self.assertEmpty(empty) self.assertNotEmpty(li) def test_pip_show(self): info = get_package_info("pandas") if "version" not in str(info): raise AssertionError(str(info)) info = get_package_info("sphinx") if "version" not in str(info): raise Exception(str(info)) def test_pip_show_all(self): info = get_package_info(start=0, end=2) df = pandas.DataFrame(info) self.assertNotEmpty(info) if __name__ == "__main__": info = get_package_info() df = pandas.DataFrame(info) df.to_excel("out_packages.xlsx") if __name__ == "__main__": unittest.main()
""" @brief test tree node (time=2s) """ import unittest import pandas from pyquickhelper.pycode import ExtTestCase from pyquickhelper.pycode.pip_helper import ( get_packages_list, package2dict, get_package_info, PQPipError) class TestPipHelper(ExtTestCase): def test_exc(self): exc = PQPipError('cmd', 'out', 'err') msg = str(exc) self.assertEqual([msg.replace('\n', '')], [ 'CMD:cmdOUT:out[piperror]err']) def test_pip_list(self): li = get_packages_list() dt = package2dict(li[0]) avoid = {'py_version'} empty = [] for k, v in dt.items(): if k not in avoid: if k is None: empty.append(k) self.assertEmpty(empty) self.assertNotEmpty(li) def test_pip_show(self): info = get_package_info("pandas") if "version" not in str(info): raise AssertionError(str(info)) info = get_package_info("sphinx") if "version" not in str(info): raise Exception(str(info)) def test_pip_show_all(self): info = get_package_info(start=0, end=2) df = pandas.DataFrame(info) self.assertNotEmpty(info) if __name__ == "__main__": info = get_package_info() df = pandas.DataFrame(info) df.to_excel("out_packages.xlsx") if __name__ == "__main__": unittest.main()
en
0.402504
@brief test tree node (time=2s)
2.640693
3
CSES/Introductory_Problems/Permutations.py
kancharlaraju21/Competitive_Programming
0
6613658
n=int(input()) if n==2 or n==3: print("NO SOLUTION") else: if n % 2==0: for i in range(n-1,0,-2): print(i,end=' ') print(n,end=' ') for i in range(2,n,2): print(i,end=' ') else: for i in range(n-1,0,-2): print(i,end=' ') print(n,end=' ') for i in range(n-2,0,-2): print(i,end=' ')
n=int(input()) if n==2 or n==3: print("NO SOLUTION") else: if n % 2==0: for i in range(n-1,0,-2): print(i,end=' ') print(n,end=' ') for i in range(2,n,2): print(i,end=' ') else: for i in range(n-1,0,-2): print(i,end=' ') print(n,end=' ') for i in range(n-2,0,-2): print(i,end=' ')
none
1
3.984146
4
opticalFlow/deepvel/testing/imax/analyze_output.py
aasensio/DeepLearning
0
6613659
<gh_stars>0 import numpy as np import matplotlib.pyplot as pl import h5py import platform import os from ipdb import set_trace as stop from astropy.io import fits import scipy.io as io import time import matplotlib.animation as manimation os.environ["KERAS_BACKEND"] = "tensorflow" if (platform.node() != 'vena'): os.environ["CUDA_VISIBLE_DEVICES"] = "0" from keras.layers import Input, Convolution2D, merge, Activation, Lambda, BatchNormalization from keras.callbacks import ModelCheckpoint, Callback from keras.models import Model, model_from_json import tensorflow as tf import keras.backend.tensorflow_backend as ktf def running_mean(x, N): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N]) / N class trainDNNFull(object): def __init__(self, root, observations, output, name_of_variable): # Only allocate needed memory config = tf.ConfigProto() config.gpu_options.allow_growth=True session = tf.Session(config=config) ktf.set_session(session) self.root = root self.nx = 800 self.ny = 800 self.n_times = 2 self.n_filters = 64 self.batch_size = 1 self.n_conv_layers = 20 self.stride = 1 self.skip_frequency = 2 self.n_frames = 1 self.observations = observations self.output = output self.name_of_variable = name_of_variable def residual(self, inputs): x = Convolution2D(self.n_filters, 3, 3, border_mode='same', init='he_normal')(inputs) x = BatchNormalization()(x) x = Activation('relu')(x) x = Convolution2D(self.n_filters, 3, 3, border_mode='same', init='he_normal')(x) x = BatchNormalization()(x) x = merge([x, inputs], 'sum') return x def defineNetwork(self): print("Setting up network...") inputs = Input(shape=(self.nx, self.ny, self.n_times)) conv = Convolution2D(self.n_filters, 3, 3, activation='relu', border_mode='same', init='he_normal')(inputs) x = self.residual(conv) for i in range(self.n_conv_layers): x = self.residual(x) x = Convolution2D(self.n_filters, 3, 3, border_mode='same', init='he_normal')(x) x = BatchNormalization()(x) x = merge([x, conv], 'sum') final = Convolution2D(6, 1, 1, activation='linear', border_mode='same', init='he_normal')(x) self.model = Model(input=inputs, output=final) print("Loading weights...") self.model.load_weights("{0}_weights.hdf5".format(self.root)) def validation_generator(self): f = io.readsav(self.observations) out = f[self.name_of_variable] self.median_i = np.median(out[:,100:-100,100:-100]) input_validation = np.zeros((self.batch_size,self.nx,self.ny,2), dtype='float32') while 1: for i in range(self.n_frames): print('{0}/{1}'.format(i,self.n_frames)) input_validation[:,:,:,0] = out[i*self.batch_size:(i+1)*self.batch_size,100:100+self.nx,100:100+self.ny] / self.median_i input_validation[:,:,:,1] = out[i*self.batch_size+1:(i+1)*self.batch_size+1,100:100+self.nx,100:100+self.ny] / self.median_i yield input_validation f.close() def predict_validation(self): print("Predicting validation data...") tmp = np.load('/net/duna/scratch1/aasensio/deepLearning/opticalFlow/database/normalization.npz') min_i, max_i, min_v, max_v = tmp['arr_0'], tmp['arr_1'], tmp['arr_2'], tmp['arr_3'] f = io.readsav(self.observations) out = f[self.name_of_variable] self.median_i = np.median(out[:,100:-100,100:-100]) input_validation = np.zeros((1,self.nx,self.ny,2), dtype='float32') input_validation[0,:,:,0] = out[0:1,100:100+self.nx,100:100+self.ny] / self.median_i input_validation[0,:,:,1] = out[1:2,100:100+self.nx,100:100+self.ny] / self.median_i # ff = io.readsav(self.observations) # im = ff['cont'] # x = np.arange(self.nx) # y = np.arange(self.ny) start = time.time() out = self.model.predict_generator(self.validation_generator(), self.n_frames, max_q_size=1) end = time.time() print("Prediction took {0} seconds...".format(end-start)) fun = ktf.function([self.model.layers[0].input],[self.model.layers[1].output]) output = np.squeeze(fun([input_validation])[0][0,200:300,200:300,:]).reshape((100,100,8,8)) f, ax = pl.subplots(nrows=2, ncols=2, figsize=(12,12)) ax[0,0].imshow(output[:,:,0,0] / np.median(output[:,:,0,0])) ax[0,1].imshow(output[:,:,4,0] / np.median(output[:,:,4,0])) ax[1,0].imshow(output[:,:,3,4] / np.median(output[:,:,3,4])) ax[1,1].imshow(output[:,:,2,2] / np.median(output[:,:,2,2])) pl.show() # stop() if (__name__ == '__main__'): # out = trainDNNFull('../training/cnns/resnet', 'cont.idl', 'imax_velocity.h5', 'cont') out = trainDNNFull('../../training/cnns/resnet2', '/net/vena/scratch1/deepLearning/opticalFlow/database/sf_Icon_307-364.sav', 'imax_velocity_noPmodes.h5', 'mov') out.defineNetwork() out.predict_validation()
import numpy as np import matplotlib.pyplot as pl import h5py import platform import os from ipdb import set_trace as stop from astropy.io import fits import scipy.io as io import time import matplotlib.animation as manimation os.environ["KERAS_BACKEND"] = "tensorflow" if (platform.node() != 'vena'): os.environ["CUDA_VISIBLE_DEVICES"] = "0" from keras.layers import Input, Convolution2D, merge, Activation, Lambda, BatchNormalization from keras.callbacks import ModelCheckpoint, Callback from keras.models import Model, model_from_json import tensorflow as tf import keras.backend.tensorflow_backend as ktf def running_mean(x, N): cumsum = np.cumsum(np.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N]) / N class trainDNNFull(object): def __init__(self, root, observations, output, name_of_variable): # Only allocate needed memory config = tf.ConfigProto() config.gpu_options.allow_growth=True session = tf.Session(config=config) ktf.set_session(session) self.root = root self.nx = 800 self.ny = 800 self.n_times = 2 self.n_filters = 64 self.batch_size = 1 self.n_conv_layers = 20 self.stride = 1 self.skip_frequency = 2 self.n_frames = 1 self.observations = observations self.output = output self.name_of_variable = name_of_variable def residual(self, inputs): x = Convolution2D(self.n_filters, 3, 3, border_mode='same', init='he_normal')(inputs) x = BatchNormalization()(x) x = Activation('relu')(x) x = Convolution2D(self.n_filters, 3, 3, border_mode='same', init='he_normal')(x) x = BatchNormalization()(x) x = merge([x, inputs], 'sum') return x def defineNetwork(self): print("Setting up network...") inputs = Input(shape=(self.nx, self.ny, self.n_times)) conv = Convolution2D(self.n_filters, 3, 3, activation='relu', border_mode='same', init='he_normal')(inputs) x = self.residual(conv) for i in range(self.n_conv_layers): x = self.residual(x) x = Convolution2D(self.n_filters, 3, 3, border_mode='same', init='he_normal')(x) x = BatchNormalization()(x) x = merge([x, conv], 'sum') final = Convolution2D(6, 1, 1, activation='linear', border_mode='same', init='he_normal')(x) self.model = Model(input=inputs, output=final) print("Loading weights...") self.model.load_weights("{0}_weights.hdf5".format(self.root)) def validation_generator(self): f = io.readsav(self.observations) out = f[self.name_of_variable] self.median_i = np.median(out[:,100:-100,100:-100]) input_validation = np.zeros((self.batch_size,self.nx,self.ny,2), dtype='float32') while 1: for i in range(self.n_frames): print('{0}/{1}'.format(i,self.n_frames)) input_validation[:,:,:,0] = out[i*self.batch_size:(i+1)*self.batch_size,100:100+self.nx,100:100+self.ny] / self.median_i input_validation[:,:,:,1] = out[i*self.batch_size+1:(i+1)*self.batch_size+1,100:100+self.nx,100:100+self.ny] / self.median_i yield input_validation f.close() def predict_validation(self): print("Predicting validation data...") tmp = np.load('/net/duna/scratch1/aasensio/deepLearning/opticalFlow/database/normalization.npz') min_i, max_i, min_v, max_v = tmp['arr_0'], tmp['arr_1'], tmp['arr_2'], tmp['arr_3'] f = io.readsav(self.observations) out = f[self.name_of_variable] self.median_i = np.median(out[:,100:-100,100:-100]) input_validation = np.zeros((1,self.nx,self.ny,2), dtype='float32') input_validation[0,:,:,0] = out[0:1,100:100+self.nx,100:100+self.ny] / self.median_i input_validation[0,:,:,1] = out[1:2,100:100+self.nx,100:100+self.ny] / self.median_i # ff = io.readsav(self.observations) # im = ff['cont'] # x = np.arange(self.nx) # y = np.arange(self.ny) start = time.time() out = self.model.predict_generator(self.validation_generator(), self.n_frames, max_q_size=1) end = time.time() print("Prediction took {0} seconds...".format(end-start)) fun = ktf.function([self.model.layers[0].input],[self.model.layers[1].output]) output = np.squeeze(fun([input_validation])[0][0,200:300,200:300,:]).reshape((100,100,8,8)) f, ax = pl.subplots(nrows=2, ncols=2, figsize=(12,12)) ax[0,0].imshow(output[:,:,0,0] / np.median(output[:,:,0,0])) ax[0,1].imshow(output[:,:,4,0] / np.median(output[:,:,4,0])) ax[1,0].imshow(output[:,:,3,4] / np.median(output[:,:,3,4])) ax[1,1].imshow(output[:,:,2,2] / np.median(output[:,:,2,2])) pl.show() # stop() if (__name__ == '__main__'): # out = trainDNNFull('../training/cnns/resnet', 'cont.idl', 'imax_velocity.h5', 'cont') out = trainDNNFull('../../training/cnns/resnet2', '/net/vena/scratch1/deepLearning/opticalFlow/database/sf_Icon_307-364.sav', 'imax_velocity_noPmodes.h5', 'mov') out.defineNetwork() out.predict_validation()
en
0.269709
# Only allocate needed memory # ff = io.readsav(self.observations) # im = ff['cont'] # x = np.arange(self.nx) # y = np.arange(self.ny) # # out = trainDNNFull('../training/cnns/resnet', 'cont.idl', 'imax_velocity.h5', 'cont')
2.226343
2
tests/helpers.py
seba-ban/env-var
0
6613660
import os from typing import Any, Optional, Sequence from unittest import TestCase from env_var.env import _env from env_var.errors import EnvVarNotDefinedError, EnvVarValidationError VAR_NAME = "TEST_VAR" def set_var(val: Optional[str] = None): if val is None: if VAR_NAME in os.environ: del os.environ[VAR_NAME] return os.environ[VAR_NAME] = val def check_validators( test_case: TestCase, _env_instance: _env, valid_values: Sequence[Any], invalid_values: Sequence[Any], ): for valid in valid_values: if isinstance(valid, tuple): var_value, parsed = valid else: var_value = parsed = valid set_var(var_value) test_case.assertEqual(_env_instance.required(), parsed) for invalid in invalid_values: with test_case.assertRaises(EnvVarValidationError): set_var(invalid) _env_instance.required() with test_case.assertRaises(EnvVarValidationError): set_var(invalid) _env_instance.optional() set_var() for valid in valid_values: with test_case.assertRaises(EnvVarNotDefinedError): _env_instance.required() for invalid in invalid_values: test_case.assertIsNone(_env_instance.optional()) for valid in valid_values: if isinstance(valid, tuple): _, parsed = valid else: parsed = valid test_case.assertEqual(_env_instance.default(parsed).required(), parsed)
import os from typing import Any, Optional, Sequence from unittest import TestCase from env_var.env import _env from env_var.errors import EnvVarNotDefinedError, EnvVarValidationError VAR_NAME = "TEST_VAR" def set_var(val: Optional[str] = None): if val is None: if VAR_NAME in os.environ: del os.environ[VAR_NAME] return os.environ[VAR_NAME] = val def check_validators( test_case: TestCase, _env_instance: _env, valid_values: Sequence[Any], invalid_values: Sequence[Any], ): for valid in valid_values: if isinstance(valid, tuple): var_value, parsed = valid else: var_value = parsed = valid set_var(var_value) test_case.assertEqual(_env_instance.required(), parsed) for invalid in invalid_values: with test_case.assertRaises(EnvVarValidationError): set_var(invalid) _env_instance.required() with test_case.assertRaises(EnvVarValidationError): set_var(invalid) _env_instance.optional() set_var() for valid in valid_values: with test_case.assertRaises(EnvVarNotDefinedError): _env_instance.required() for invalid in invalid_values: test_case.assertIsNone(_env_instance.optional()) for valid in valid_values: if isinstance(valid, tuple): _, parsed = valid else: parsed = valid test_case.assertEqual(_env_instance.default(parsed).required(), parsed)
none
1
2.995804
3
Funky Sentence Gen/Funky Sentence Generator.py
Software-Cat/Python-Mini-Projects
0
6613661
<filename>Funky Sentence Gen/Funky Sentence Generator.py import random adjectives = ["abandoned", "baffled", "cringy", "dazzling", "eccentric", "fancy", "generous", "happy", "ill", "jocose", "kind", "lazy", "magical", "naked", "obstinate", "patriotic", "queasy", "raging", "savage", "talented", "unlucky", "vegetarian", "white", "xenophobic", "yawning", "zippy"] executerNouns = ["apple", "banana", "cat", "dog", "elephatnt", "flamingo", "giraffe", "hippo", "iguana", "jellyfish", "kangaroo", "ladybug", "mammoth", "numbat", "octopus", "panda", "quail", "rabbit", "snake", "teacher", "umpire", "vocalist", "whale", "xylophone", "yoga instructor", "zoologist"] adverbs = ["accidentally", "beneficially", "chaotically", "doubtfully", "efficiently", "fearfullly", "gently", "hypocritically", "impulsively", "jealously", "keenly", "loudly", "mysteriously", "naively", "obediently", "passionately", "quietly", "rationally", "sadly", "telepathically", "uncontrollably", "viciously", "wildly", "xenophobically", "youthfully", "zealously"] verbs = ["ate", "bent", "cleaned", "danced", "educated", "fabricated", "grew", "hacked", "immobilized", "jumbled", "kicked"] genders = ["his", "hers"] subjectNouns = ["aquarium", "bandana", "cabbage"] prepositions = ["with", "without", "in front of", "behind", "next to", "under", "over"] objects = ["aeroplane", "broom"] print("The " + random.choice(adjectives) + " " + random.choice(executerNouns) + " " + random.choice(adverbs) + " " + random.choice(verbs) + " " + random.choice(genders) + " " + random.choice(subjectNouns) + " " + random.choice(prepositions) + " a/an " + random.choice(objects) + ".")
<filename>Funky Sentence Gen/Funky Sentence Generator.py import random adjectives = ["abandoned", "baffled", "cringy", "dazzling", "eccentric", "fancy", "generous", "happy", "ill", "jocose", "kind", "lazy", "magical", "naked", "obstinate", "patriotic", "queasy", "raging", "savage", "talented", "unlucky", "vegetarian", "white", "xenophobic", "yawning", "zippy"] executerNouns = ["apple", "banana", "cat", "dog", "elephatnt", "flamingo", "giraffe", "hippo", "iguana", "jellyfish", "kangaroo", "ladybug", "mammoth", "numbat", "octopus", "panda", "quail", "rabbit", "snake", "teacher", "umpire", "vocalist", "whale", "xylophone", "yoga instructor", "zoologist"] adverbs = ["accidentally", "beneficially", "chaotically", "doubtfully", "efficiently", "fearfullly", "gently", "hypocritically", "impulsively", "jealously", "keenly", "loudly", "mysteriously", "naively", "obediently", "passionately", "quietly", "rationally", "sadly", "telepathically", "uncontrollably", "viciously", "wildly", "xenophobically", "youthfully", "zealously"] verbs = ["ate", "bent", "cleaned", "danced", "educated", "fabricated", "grew", "hacked", "immobilized", "jumbled", "kicked"] genders = ["his", "hers"] subjectNouns = ["aquarium", "bandana", "cabbage"] prepositions = ["with", "without", "in front of", "behind", "next to", "under", "over"] objects = ["aeroplane", "broom"] print("The " + random.choice(adjectives) + " " + random.choice(executerNouns) + " " + random.choice(adverbs) + " " + random.choice(verbs) + " " + random.choice(genders) + " " + random.choice(subjectNouns) + " " + random.choice(prepositions) + " a/an " + random.choice(objects) + ".")
none
1
2.655477
3
policy_driven_attack/models/victim/mnist/lr.py
machanic/TangentAttack
4
6613662
import torch.nn as nn __all__ = ['lr'] class LR(nn.Module): def __init__(self, num_classes=10): super(LR, self).__init__() self.fc = nn.Linear(784, num_classes) def forward(self, x): x = x.view(x.shape[0], -1) x = self.fc(x) return x def lr(**kwargs): return LR(**kwargs)
import torch.nn as nn __all__ = ['lr'] class LR(nn.Module): def __init__(self, num_classes=10): super(LR, self).__init__() self.fc = nn.Linear(784, num_classes) def forward(self, x): x = x.view(x.shape[0], -1) x = self.fc(x) return x def lr(**kwargs): return LR(**kwargs)
none
1
2.953532
3
train_region.py
mguludag/birthplace_region_predict_python_webapp
2
6613663
from keras.optimizers import SGD # import h5py import cv2 from face_network import create_face_network import numpy as np from keras.utils.np_utils import to_categorical from keras.callbacks import ModelCheckpoint import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' train_split = 0.7 # Folder path PATH = "D:\\Users\\mguludag\\Desktop\\staj_proj\\bolgeler" FILE_FORMAT = (".png", ".jpg") # Get first three digits def getImageId(name): return name images = [] imagesResized = [] region = [] for subdir, dirs, files in os.walk(PATH): for file in files: if file.endswith(FILE_FORMAT): name = os.path.join(subdir, file) im = cv2.imread(name, cv2.IMREAD_COLOR) im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB) # im.show() images.append(np.array(im)) im = cv2.resize(im, (224, 224)) imagesResized.append(np.array(im)) imageId = getImageId(os.path.basename(subdir)) if(imageId=="akdeniz"): region.append(0) if(imageId=="ege"): region.append(1) if(imageId=="ic_anadolu"): region.append(2) if(imageId=="karadeniz"): region.append(3) # cv2.imshow("sfsf",im) # cv2.waitKey(0) # Concatenate # images = np.float64(np.stack(images)) # print(images.shape) imagesResized = np.float64(np.stack(imagesResized)) region = np.stack(region) # Normalize data # images /= 255.0 imagesResized /= 255.0 # f = h5py.File('images.h5', 'r') X_data = imagesResized y_data = region #One-hot y_data = to_categorical(y_data, 4) # Split into training and validation sets num_images = len(y_data) p = np.random.permutation(num_images) X_data = X_data[p] y_data = y_data[p] X_train = X_data[0:int(round(train_split*num_images))] y_train = y_data[0:int(round(train_split*num_images))] X_test = X_data[int(round(train_split*num_images))+1:-1] y_test = y_data[int(round(train_split*num_images))+1:-1] # Zero center means = np.mean(X_train, axis = 0) X_train -= means X_test -= means # Save means (for testing) np.save('means_region.npy',means) opt = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True) checkpoint = ModelCheckpoint('weights_region.hdf5', monitor='val_acc', verbose=1, save_best_only=False, save_weights_only=True, mode='max') model = create_face_network(nb_class=4, hidden_dim=256, shape=(224, 224, 3)) model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=1, callbacks=[checkpoint], validation_data=(X_test, y_test), shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0)
from keras.optimizers import SGD # import h5py import cv2 from face_network import create_face_network import numpy as np from keras.utils.np_utils import to_categorical from keras.callbacks import ModelCheckpoint import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' train_split = 0.7 # Folder path PATH = "D:\\Users\\mguludag\\Desktop\\staj_proj\\bolgeler" FILE_FORMAT = (".png", ".jpg") # Get first three digits def getImageId(name): return name images = [] imagesResized = [] region = [] for subdir, dirs, files in os.walk(PATH): for file in files: if file.endswith(FILE_FORMAT): name = os.path.join(subdir, file) im = cv2.imread(name, cv2.IMREAD_COLOR) im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB) # im.show() images.append(np.array(im)) im = cv2.resize(im, (224, 224)) imagesResized.append(np.array(im)) imageId = getImageId(os.path.basename(subdir)) if(imageId=="akdeniz"): region.append(0) if(imageId=="ege"): region.append(1) if(imageId=="ic_anadolu"): region.append(2) if(imageId=="karadeniz"): region.append(3) # cv2.imshow("sfsf",im) # cv2.waitKey(0) # Concatenate # images = np.float64(np.stack(images)) # print(images.shape) imagesResized = np.float64(np.stack(imagesResized)) region = np.stack(region) # Normalize data # images /= 255.0 imagesResized /= 255.0 # f = h5py.File('images.h5', 'r') X_data = imagesResized y_data = region #One-hot y_data = to_categorical(y_data, 4) # Split into training and validation sets num_images = len(y_data) p = np.random.permutation(num_images) X_data = X_data[p] y_data = y_data[p] X_train = X_data[0:int(round(train_split*num_images))] y_train = y_data[0:int(round(train_split*num_images))] X_test = X_data[int(round(train_split*num_images))+1:-1] y_test = y_data[int(round(train_split*num_images))+1:-1] # Zero center means = np.mean(X_train, axis = 0) X_train -= means X_test -= means # Save means (for testing) np.save('means_region.npy',means) opt = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True) checkpoint = ModelCheckpoint('weights_region.hdf5', monitor='val_acc', verbose=1, save_best_only=False, save_weights_only=True, mode='max') model = create_face_network(nb_class=4, hidden_dim=256, shape=(224, 224, 3)) model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy']) model.fit(X_train, y_train, batch_size=32, epochs=10, verbose=1, callbacks=[checkpoint], validation_data=(X_test, y_test), shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0)
en
0.433206
# import h5py # Folder path # Get first three digits # im.show() # cv2.imshow("sfsf",im) # cv2.waitKey(0) # Concatenate # images = np.float64(np.stack(images)) # print(images.shape) # Normalize data # images /= 255.0 # f = h5py.File('images.h5', 'r') #One-hot # Split into training and validation sets # Zero center # Save means (for testing)
2.301176
2
src/foreign_if/python/examples/dt_demo.py
XpressAI/frovedis
63
6613664
<filename>src/foreign_if/python/examples/dt_demo.py #!/usr/bin/env python import sys import numpy as np np.set_printoptions(threshold=5) #from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from frovedis.mllib.tree import DecisionTreeClassifier, DecisionTreeRegressor # initializing the Frovedis server argvs = sys.argv argc = len(argvs) if (argc < 2): print ('Please give frovedis_server calling command as the first argument \n(e.g. "mpirun -np 2 /opt/nec/frovedis/ve/bin/frovedis_server")') quit() from frovedis.exrpc.server import FrovedisServer FrovedisServer.initialize(argvs[1]) # classification data from sklearn.datasets import load_breast_cancer mat, lbl = load_breast_cancer(return_X_y=True) # fitting input matrix and label on DecisionTree Classifier object dtc = DecisionTreeClassifier(criterion='gini', max_depth=5) dtc.fit(mat,lbl) #dtc.debug_print() # predicting on train model print("predicting on DecisionTree classifier model: ") print(dtc.predict(mat)) print("predicting probability on DecisionTree classifier model: ") print (dtc.predict_proba(mat)) print("prediction accuracy: %.4f" % (dtc.score(mat, lbl))) # regression data from sklearn.datasets import load_boston mat, lbl = load_boston(return_X_y=True) # fitting input matrix and label on DecisionTree Regressor object dtr = DecisionTreeRegressor(criterion='mse', max_depth=5) dtr.fit(mat, lbl) #dtr.debug_print() # predicting on train model print("predicting on DecisionTree Regressor model: ") print(dtr.predict(mat)) print("prediction score: %.4f" % (dtr.score(mat, lbl))) #clean-up #dtc.release() #dtr.release() FrovedisServer.shut_down()
<filename>src/foreign_if/python/examples/dt_demo.py #!/usr/bin/env python import sys import numpy as np np.set_printoptions(threshold=5) #from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from frovedis.mllib.tree import DecisionTreeClassifier, DecisionTreeRegressor # initializing the Frovedis server argvs = sys.argv argc = len(argvs) if (argc < 2): print ('Please give frovedis_server calling command as the first argument \n(e.g. "mpirun -np 2 /opt/nec/frovedis/ve/bin/frovedis_server")') quit() from frovedis.exrpc.server import FrovedisServer FrovedisServer.initialize(argvs[1]) # classification data from sklearn.datasets import load_breast_cancer mat, lbl = load_breast_cancer(return_X_y=True) # fitting input matrix and label on DecisionTree Classifier object dtc = DecisionTreeClassifier(criterion='gini', max_depth=5) dtc.fit(mat,lbl) #dtc.debug_print() # predicting on train model print("predicting on DecisionTree classifier model: ") print(dtc.predict(mat)) print("predicting probability on DecisionTree classifier model: ") print (dtc.predict_proba(mat)) print("prediction accuracy: %.4f" % (dtc.score(mat, lbl))) # regression data from sklearn.datasets import load_boston mat, lbl = load_boston(return_X_y=True) # fitting input matrix and label on DecisionTree Regressor object dtr = DecisionTreeRegressor(criterion='mse', max_depth=5) dtr.fit(mat, lbl) #dtr.debug_print() # predicting on train model print("predicting on DecisionTree Regressor model: ") print(dtr.predict(mat)) print("prediction score: %.4f" % (dtr.score(mat, lbl))) #clean-up #dtc.release() #dtr.release() FrovedisServer.shut_down()
en
0.480906
#!/usr/bin/env python #from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor # initializing the Frovedis server # classification data # fitting input matrix and label on DecisionTree Classifier object #dtc.debug_print() # predicting on train model # regression data # fitting input matrix and label on DecisionTree Regressor object #dtr.debug_print() # predicting on train model #clean-up #dtc.release() #dtr.release()
2.711921
3
setting.py
midoks/vms
1
6613665
# -- coding:utf-8 -- import time import sys import os chdir = os.getcwd() sys.path.append(chdir + '/class/core') sys.path.append(chdir + '/class/ctr') sys.path.append("/usr/local/lib/python2.7/site-packages") import common import system_api cpu_info = system_api.system_api().getCpuInfo() workers = cpu_info[1] if not os.path.exists(os.getcwd() + '/logs'): os.mkdir(os.getcwd() + '/logs') if not os.path.exists('data/port.pl'): common.writeFile('data/port.pl', '8000') app_port = common.readFile('data/port.pl') bind = [] if os.path.exists('data/ipv6.pl'): bind.append('[0:0:0:0:0:0:0:0]:%s' % app_port) else: bind.append('0.0.0.0:%s' % app_port) if workers > 2: workers = 2 threads = workers * 1 backlog = 512 reload = True daemon = True worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker' timeout = 7200 keepalive = 60 preload_app = True capture_output = True access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' loglevel = 'info' errorlog = chdir + '/logs/error.log' accesslog = chdir + '/logs/access.log' pidfile = chdir + '/logs/vms.pid'
# -- coding:utf-8 -- import time import sys import os chdir = os.getcwd() sys.path.append(chdir + '/class/core') sys.path.append(chdir + '/class/ctr') sys.path.append("/usr/local/lib/python2.7/site-packages") import common import system_api cpu_info = system_api.system_api().getCpuInfo() workers = cpu_info[1] if not os.path.exists(os.getcwd() + '/logs'): os.mkdir(os.getcwd() + '/logs') if not os.path.exists('data/port.pl'): common.writeFile('data/port.pl', '8000') app_port = common.readFile('data/port.pl') bind = [] if os.path.exists('data/ipv6.pl'): bind.append('[0:0:0:0:0:0:0:0]:%s' % app_port) else: bind.append('0.0.0.0:%s' % app_port) if workers > 2: workers = 2 threads = workers * 1 backlog = 512 reload = True daemon = True worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker' timeout = 7200 keepalive = 60 preload_app = True capture_output = True access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' loglevel = 'info' errorlog = chdir + '/logs/error.log' accesslog = chdir + '/logs/access.log' pidfile = chdir + '/logs/vms.pid'
en
0.304031
# -- coding:utf-8 --
2.073094
2
src/sprites/ball.py
LeonGeorgi/ballsurf
0
6613666
<gh_stars>0 import uuid from abc import abstractmethod, ABC import pygame.gfxdraw from const import Const from context import Context from gamerect import GameRect from image import CachedImage from sprite import Sprite, Sprites, Type class Ball(Sprite, ABC): def __init__(self, x=None): if x is None: self.x = 2 * Const.game_height else: self.x = x self.image = CachedImage(self.filename()) self.diameter = self.image.get_width() * Const.pixel_size self.y = Const.game_height - self.diameter self.__vspeed = 0 self.bounced = False self.hit_bottom = False self.id = uuid.uuid4() def update(self, context: Context, sprites: Sprites): self.x -= context.x_delta if self.bounced: self.move_by_gravity(context) def render(self, surface: pygame.Surface, size_factor: float): rect = self.box.to_pygame(size_factor, False) if rect.width <= 0 or rect.height <= 0: return img = self.image.scale(rect.width, rect.height) surface.blit(img, (rect.left, rect.top)) def bounce(self, velocity: float): self.bounced = True self.__vspeed = -velocity / 2 def move_by_gravity(self, context: Context): # time in s t = context.time_factor / Const.fps # gravity in m/(s**2) a = context.gravity self.y = 1 / 2 * a * (t ** 2) + \ self.__vspeed * t + \ self.y self.__vspeed = a * t + self.__vspeed if self.y + self.diameter >= Const.game_height + self.diameter * 0.3 and not self.hit_bottom: self.__vspeed = -self.__vspeed * self.bounciness() self.hit_bottom = True elif self.y + self.diameter < Const.game_height + self.diameter * 0.3 and self.hit_bottom: self.hit_bottom = False @property def box(self) -> GameRect: offset = max(0, (self.y + self.diameter) - Const.game_height) y_delta = 0 if offset > self.diameter * 0.3: y_delta = offset - self.diameter * 0.3 offset = self.diameter * 0.3 return GameRect(self.x, self.y - y_delta, self.diameter, self.diameter - offset) def type(self) -> Type: return Type.BALL def can_delete(self) -> bool: return self.x <= -1 @abstractmethod def filename(self) -> str: pass @abstractmethod def bounciness(self) -> float: """ :return: by how much the velocity of the player is multiplied when he hits the ball """ pass @abstractmethod def immediate_speed_increase(self) -> float: pass @abstractmethod def desired_speed_increase(self) -> float: pass
import uuid from abc import abstractmethod, ABC import pygame.gfxdraw from const import Const from context import Context from gamerect import GameRect from image import CachedImage from sprite import Sprite, Sprites, Type class Ball(Sprite, ABC): def __init__(self, x=None): if x is None: self.x = 2 * Const.game_height else: self.x = x self.image = CachedImage(self.filename()) self.diameter = self.image.get_width() * Const.pixel_size self.y = Const.game_height - self.diameter self.__vspeed = 0 self.bounced = False self.hit_bottom = False self.id = uuid.uuid4() def update(self, context: Context, sprites: Sprites): self.x -= context.x_delta if self.bounced: self.move_by_gravity(context) def render(self, surface: pygame.Surface, size_factor: float): rect = self.box.to_pygame(size_factor, False) if rect.width <= 0 or rect.height <= 0: return img = self.image.scale(rect.width, rect.height) surface.blit(img, (rect.left, rect.top)) def bounce(self, velocity: float): self.bounced = True self.__vspeed = -velocity / 2 def move_by_gravity(self, context: Context): # time in s t = context.time_factor / Const.fps # gravity in m/(s**2) a = context.gravity self.y = 1 / 2 * a * (t ** 2) + \ self.__vspeed * t + \ self.y self.__vspeed = a * t + self.__vspeed if self.y + self.diameter >= Const.game_height + self.diameter * 0.3 and not self.hit_bottom: self.__vspeed = -self.__vspeed * self.bounciness() self.hit_bottom = True elif self.y + self.diameter < Const.game_height + self.diameter * 0.3 and self.hit_bottom: self.hit_bottom = False @property def box(self) -> GameRect: offset = max(0, (self.y + self.diameter) - Const.game_height) y_delta = 0 if offset > self.diameter * 0.3: y_delta = offset - self.diameter * 0.3 offset = self.diameter * 0.3 return GameRect(self.x, self.y - y_delta, self.diameter, self.diameter - offset) def type(self) -> Type: return Type.BALL def can_delete(self) -> bool: return self.x <= -1 @abstractmethod def filename(self) -> str: pass @abstractmethod def bounciness(self) -> float: """ :return: by how much the velocity of the player is multiplied when he hits the ball """ pass @abstractmethod def immediate_speed_increase(self) -> float: pass @abstractmethod def desired_speed_increase(self) -> float: pass
en
0.944909
# time in s # gravity in m/(s**2) :return: by how much the velocity of the player is multiplied when he hits the ball
2.889262
3
Test/FunctionalTests/CommonTestScripts/LevelEditorUtil.py
jethac/ATF
821
6613667
<filename>Test/FunctionalTests/CommonTestScripts/LevelEditorUtil.py #Copyright (c) 2014 Sony Computer Entertainment America LLC. See License.txt. import System import Test import Sce.Atf.Dom import LevelEditorSample from System import Environment from System.IO import Path from System.IO import File def SetSchema(schema): global Schema Schema = schema return def AddObjectAndVerify(editingContext, domNodeType, vector): domNode = Sce.Atf.Dom.DomNode(domNodeType) gameObject = editingContext.Insert(domNode, vector[0], vector[1], vector[2]) Test.Equal(gameObject.DomNode.Type.Name, domNodeType.Name, "Verify the correct type was added") Test.Equal(System.Decimal(vector[0]), System.Decimal(gameObject.Translation[0]), "Verify new object X pos") Test.Equal(System.Decimal(vector[1]), System.Decimal(gameObject.Translation[1]), "Verify new object Y pos") Test.Equal(System.Decimal(vector[2]), System.Decimal(gameObject.Translation[2]), "Verify new object Z pos") #More generic (and cluttered) way if domNode is returned from insertion #Test.Equal(domNode.GetAttribute(domNode.Type.GetAttributeInfo("name")), name, "Verify new object name") #Test.EqualSystem.(Decimal(domNode.GetAttribute(domNode.Type.GetAttributeInfo("translate"))[0]), System.Decimal(x), "Verify new object X pos") #... return gameObject def AddObjectSetPropertiesAndVerify(editingContext, domNodeType, vTranslation, vScale, vRotation, vRotatePivot): domNode = Sce.Atf.Dom.DomNode(domNodeType) gameObject = editingContext.Insert(domNode, vTranslation[0], vTranslation[1], vTranslation[2]) editingContext.SetProperty(gameObject.DomNode, Schema.gameObjectType.scaleAttribute, Test.ConstructArray([vScale[0], vScale[1], vScale[2]])) editingContext.SetProperty(gameObject.DomNode, Schema.gameObjectType.rotatePivotAttribute, Test.ConstructArray([vRotatePivot[0], vRotatePivot[1], vRotatePivot[2]])) editingContext.SetProperty(gameObject.DomNode, Schema.gameObjectType.rotateAttribute, Test.ConstructArray([vRotation[0], vRotation[1], vRotation[2]])) Test.Equal(gameObject.DomNode.Type.Name, domNodeType.Name, "Verify the correct type was added") Test.Equal(System.Decimal(vTranslation[0]), System.Decimal(gameObject.Translation[0]), "Verify new object X pos") Test.Equal(System.Decimal(vTranslation[1]), System.Decimal(gameObject.Translation[1]), "Verify new object Y pos") Test.Equal(System.Decimal(vTranslation[2]), System.Decimal(gameObject.Translation[2]), "Verify new object Z pos") Test.Equal(System.Decimal(vScale[0]), System.Decimal(gameObject.Scale[0]), "Verify new object X scale") Test.Equal(System.Decimal(vScale[1]), System.Decimal(gameObject.Scale[1]), "Verify new object Y scale") Test.Equal(System.Decimal(vScale[2]), System.Decimal(gameObject.Scale[2]), "Verify new object Z scale") VerifyAttributeAngle(gameObject.DomNode, Schema.gameObjectType.rotateAttribute, vRotation) Test.Equal(System.Decimal(vRotatePivot[0]), System.Decimal(gameObject.RotatePivot[0]), "Verify new object X rotate pivot") Test.Equal(System.Decimal(vRotatePivot[1]), System.Decimal(gameObject.RotatePivot[1]), "Verify new object Y rotate pivot") Test.Equal(System.Decimal(vRotatePivot[2]), System.Decimal(gameObject.RotatePivot[2]), "Verify new object Z rotate pivot") return gameObject def VerifyAttribute(domNode, attr, expected): Test.Equal(expected, domNode.GetAttribute(attr), "Verify attribute") return def VerifyAttributeVector(domNode, attr, vector): Test.Equal(System.Decimal(vector[0]), System.Decimal(domNode.GetAttribute(attr)[0]), "Verify X axis") Test.Equal(System.Decimal(vector[1]), System.Decimal(domNode.GetAttribute(attr)[1]), "Verify Y axis") Test.Equal(System.Decimal(vector[2]), System.Decimal(domNode.GetAttribute(attr)[2]), "Verify Z axis") return #internally, angles are stored as radians, but the api/ui displays degrees #need to convert the internal radian to degrees, and use a fuzzy compare #to account for floating point precision differences def VerifyAttributeAngle(domNode, attr, vector): Test.FuzzyCompare(System.Decimal(vector[0]), System.Decimal(domNode.GetAttribute(attr)[0]), "Verify X angle") Test.FuzzyCompare(System.Decimal(vector[1]), System.Decimal(domNode.GetAttribute(attr)[1]), "Verify Y angle") Test.FuzzyCompare(System.Decimal(vector[2]), System.Decimal(domNode.GetAttribute(attr)[2]), "Verify Z angle") return #This function constructs the full path to a resource under the Data folder. def GetResourceFilePath(relativeFilePath): #current directory is something like: #LevelEditor\bin\Debug.vs2010 #Data directory is: #LevelEditor\Data #so the relative path to the data directory is: dataDir = Path.Combine(Environment.CurrentDirectory, "../../Data") resourcePath = Path.Combine(dataDir, relativeFilePath) resourcePath = Path.GetFullPath(resourcePath) return resourcePath #Helper to convert an array of domNodes, sets each name based on its type, and returns a c# array of objects def ConstructDomNodeArray(domNodes): ret = System.Array.CreateInstance(System.Object, domNodes.Count) for i in range(domNodes.Count): name = domNodes[i].Type.Name.Replace("gap:", "") domNodes[i].SetAttribute(LevelEditorSample.Schema.gameObjectType.nameAttribute, name) ret[i] = domNodes[i] return ret
<filename>Test/FunctionalTests/CommonTestScripts/LevelEditorUtil.py #Copyright (c) 2014 Sony Computer Entertainment America LLC. See License.txt. import System import Test import Sce.Atf.Dom import LevelEditorSample from System import Environment from System.IO import Path from System.IO import File def SetSchema(schema): global Schema Schema = schema return def AddObjectAndVerify(editingContext, domNodeType, vector): domNode = Sce.Atf.Dom.DomNode(domNodeType) gameObject = editingContext.Insert(domNode, vector[0], vector[1], vector[2]) Test.Equal(gameObject.DomNode.Type.Name, domNodeType.Name, "Verify the correct type was added") Test.Equal(System.Decimal(vector[0]), System.Decimal(gameObject.Translation[0]), "Verify new object X pos") Test.Equal(System.Decimal(vector[1]), System.Decimal(gameObject.Translation[1]), "Verify new object Y pos") Test.Equal(System.Decimal(vector[2]), System.Decimal(gameObject.Translation[2]), "Verify new object Z pos") #More generic (and cluttered) way if domNode is returned from insertion #Test.Equal(domNode.GetAttribute(domNode.Type.GetAttributeInfo("name")), name, "Verify new object name") #Test.EqualSystem.(Decimal(domNode.GetAttribute(domNode.Type.GetAttributeInfo("translate"))[0]), System.Decimal(x), "Verify new object X pos") #... return gameObject def AddObjectSetPropertiesAndVerify(editingContext, domNodeType, vTranslation, vScale, vRotation, vRotatePivot): domNode = Sce.Atf.Dom.DomNode(domNodeType) gameObject = editingContext.Insert(domNode, vTranslation[0], vTranslation[1], vTranslation[2]) editingContext.SetProperty(gameObject.DomNode, Schema.gameObjectType.scaleAttribute, Test.ConstructArray([vScale[0], vScale[1], vScale[2]])) editingContext.SetProperty(gameObject.DomNode, Schema.gameObjectType.rotatePivotAttribute, Test.ConstructArray([vRotatePivot[0], vRotatePivot[1], vRotatePivot[2]])) editingContext.SetProperty(gameObject.DomNode, Schema.gameObjectType.rotateAttribute, Test.ConstructArray([vRotation[0], vRotation[1], vRotation[2]])) Test.Equal(gameObject.DomNode.Type.Name, domNodeType.Name, "Verify the correct type was added") Test.Equal(System.Decimal(vTranslation[0]), System.Decimal(gameObject.Translation[0]), "Verify new object X pos") Test.Equal(System.Decimal(vTranslation[1]), System.Decimal(gameObject.Translation[1]), "Verify new object Y pos") Test.Equal(System.Decimal(vTranslation[2]), System.Decimal(gameObject.Translation[2]), "Verify new object Z pos") Test.Equal(System.Decimal(vScale[0]), System.Decimal(gameObject.Scale[0]), "Verify new object X scale") Test.Equal(System.Decimal(vScale[1]), System.Decimal(gameObject.Scale[1]), "Verify new object Y scale") Test.Equal(System.Decimal(vScale[2]), System.Decimal(gameObject.Scale[2]), "Verify new object Z scale") VerifyAttributeAngle(gameObject.DomNode, Schema.gameObjectType.rotateAttribute, vRotation) Test.Equal(System.Decimal(vRotatePivot[0]), System.Decimal(gameObject.RotatePivot[0]), "Verify new object X rotate pivot") Test.Equal(System.Decimal(vRotatePivot[1]), System.Decimal(gameObject.RotatePivot[1]), "Verify new object Y rotate pivot") Test.Equal(System.Decimal(vRotatePivot[2]), System.Decimal(gameObject.RotatePivot[2]), "Verify new object Z rotate pivot") return gameObject def VerifyAttribute(domNode, attr, expected): Test.Equal(expected, domNode.GetAttribute(attr), "Verify attribute") return def VerifyAttributeVector(domNode, attr, vector): Test.Equal(System.Decimal(vector[0]), System.Decimal(domNode.GetAttribute(attr)[0]), "Verify X axis") Test.Equal(System.Decimal(vector[1]), System.Decimal(domNode.GetAttribute(attr)[1]), "Verify Y axis") Test.Equal(System.Decimal(vector[2]), System.Decimal(domNode.GetAttribute(attr)[2]), "Verify Z axis") return #internally, angles are stored as radians, but the api/ui displays degrees #need to convert the internal radian to degrees, and use a fuzzy compare #to account for floating point precision differences def VerifyAttributeAngle(domNode, attr, vector): Test.FuzzyCompare(System.Decimal(vector[0]), System.Decimal(domNode.GetAttribute(attr)[0]), "Verify X angle") Test.FuzzyCompare(System.Decimal(vector[1]), System.Decimal(domNode.GetAttribute(attr)[1]), "Verify Y angle") Test.FuzzyCompare(System.Decimal(vector[2]), System.Decimal(domNode.GetAttribute(attr)[2]), "Verify Z angle") return #This function constructs the full path to a resource under the Data folder. def GetResourceFilePath(relativeFilePath): #current directory is something like: #LevelEditor\bin\Debug.vs2010 #Data directory is: #LevelEditor\Data #so the relative path to the data directory is: dataDir = Path.Combine(Environment.CurrentDirectory, "../../Data") resourcePath = Path.Combine(dataDir, relativeFilePath) resourcePath = Path.GetFullPath(resourcePath) return resourcePath #Helper to convert an array of domNodes, sets each name based on its type, and returns a c# array of objects def ConstructDomNodeArray(domNodes): ret = System.Array.CreateInstance(System.Object, domNodes.Count) for i in range(domNodes.Count): name = domNodes[i].Type.Name.Replace("gap:", "") domNodes[i].SetAttribute(LevelEditorSample.Schema.gameObjectType.nameAttribute, name) ret[i] = domNodes[i] return ret
en
0.584891
#Copyright (c) 2014 Sony Computer Entertainment America LLC. See License.txt. #More generic (and cluttered) way if domNode is returned from insertion #Test.Equal(domNode.GetAttribute(domNode.Type.GetAttributeInfo("name")), name, "Verify new object name") #Test.EqualSystem.(Decimal(domNode.GetAttribute(domNode.Type.GetAttributeInfo("translate"))[0]), System.Decimal(x), "Verify new object X pos") #... #internally, angles are stored as radians, but the api/ui displays degrees #need to convert the internal radian to degrees, and use a fuzzy compare #to account for floating point precision differences #This function constructs the full path to a resource under the Data folder. #current directory is something like: #LevelEditor\bin\Debug.vs2010 #Data directory is: #LevelEditor\Data #so the relative path to the data directory is: #Helper to convert an array of domNodes, sets each name based on its type, and returns a c# array of objects
2.186706
2
lib/annotation/prodigy_resources/recipe.py
jvasilakes-umn/idisk
4
6613668
import prodigy from prodigy.components.loaders import JSONL """ Prodigy recipe for annotating pairs of iDISK concepts. """ @prodigy.recipe("compare", dataset=prodigy.recipe_args['dataset'], input_file=("File containing input data.", "positional", None, str), html_file=("File containing HTML template", "positional", None, str)) def compare(dataset, input_file, html_file): """ Prodigy recipe for annotating pairs of iDISK concepts. """ stream = JSONL(input_file) html_template = open(html_file, 'r').read() stream = add_to_stream(stream, html_template) return { "dataset": dataset, "stream": stream, "view_id": "choice", "exclude": [dataset], "config": {"html_template": html_template} } def set_hashes(task, i): """ For some reason Prodigy was assigning the same hashes to every example in the data, which meant that when it looked at the saved annotations in the dataset to figure out which to exclude, it excluded all of them. Setting the _input_hash to the index of the candidate connection also makes lookup easier when we filter the candidates according to their annotation. """ task["_input_hash"] = i task["_task_hash"] = -(i+1) return task def add_to_stream(stream, html): for (i, task) in enumerate(stream): task["html"] = html task = set_hashes(task, i) task["options"] = [{"id": 1, "text": "Equal"}, {"id": 2, "text": "Not Equal"}, {"id": 3, "text": "Parent-Child"}, {"id": 4, "text": "Child-Parent"}] yield task
import prodigy from prodigy.components.loaders import JSONL """ Prodigy recipe for annotating pairs of iDISK concepts. """ @prodigy.recipe("compare", dataset=prodigy.recipe_args['dataset'], input_file=("File containing input data.", "positional", None, str), html_file=("File containing HTML template", "positional", None, str)) def compare(dataset, input_file, html_file): """ Prodigy recipe for annotating pairs of iDISK concepts. """ stream = JSONL(input_file) html_template = open(html_file, 'r').read() stream = add_to_stream(stream, html_template) return { "dataset": dataset, "stream": stream, "view_id": "choice", "exclude": [dataset], "config": {"html_template": html_template} } def set_hashes(task, i): """ For some reason Prodigy was assigning the same hashes to every example in the data, which meant that when it looked at the saved annotations in the dataset to figure out which to exclude, it excluded all of them. Setting the _input_hash to the index of the candidate connection also makes lookup easier when we filter the candidates according to their annotation. """ task["_input_hash"] = i task["_task_hash"] = -(i+1) return task def add_to_stream(stream, html): for (i, task) in enumerate(stream): task["html"] = html task = set_hashes(task, i) task["options"] = [{"id": 1, "text": "Equal"}, {"id": 2, "text": "Not Equal"}, {"id": 3, "text": "Parent-Child"}, {"id": 4, "text": "Child-Parent"}] yield task
en
0.929535
Prodigy recipe for annotating pairs of iDISK concepts. Prodigy recipe for annotating pairs of iDISK concepts. For some reason Prodigy was assigning the same hashes to every example in the data, which meant that when it looked at the saved annotations in the dataset to figure out which to exclude, it excluded all of them. Setting the _input_hash to the index of the candidate connection also makes lookup easier when we filter the candidates according to their annotation.
2.282801
2
test_idun.py
ArneRustad/Master-thesis-cf
0
6613669
<gh_stars>0 import time print("Starting script on Idun") # for i in range(10): # print("Waiting 10 seconds") # time.sleep(10) import torch print("Finished script on Idun")
import time print("Starting script on Idun") # for i in range(10): # print("Waiting 10 seconds") # time.sleep(10) import torch print("Finished script on Idun")
en
0.470658
# for i in range(10): # print("Waiting 10 seconds") # time.sleep(10)
2.652009
3
misc/untitled.py
nishishailesh/moving_average_clin_lab
0
6613670
all record: { b'1297254': { b'Date': b'time: 18-11-2021 11:46:59', b'': '', b'Patient ID : 1297254': '', b'Name :': '', b'Gender :': '', b'Age :': '', b'Department :': '', b'Hospital Name :': '', b'----------------------': '', b'FiO2 : 0.21': '', b'Pat. Temp : 37.0': '', b'TRef : 26.250': '', b'BLOOD GAS': '', b'pCO2': b'24.86 mmHg', b'pO2': b'56.84 mmHg', b'HEMATOCRIT': '', b'Hct': b'29.67 %', b'SO2': b'92.84 %', b'Hb': b'9.89 g/dL', b'ELECTROLYTES': '', b'Na': b'146.8 mmol/L', b'K': b'3.26 mmol/L', b'iCa': b'0.93 mmol/L', b'Cl': b'115.6 mmol/L', b'Li': b'NA NA', b'nCa': b'1.00 mmol/L', b'TCa': b'1.99 mmol/L', b'METABOLITES': '', b'GLU': b'104.9 mg/dL', b'LAC': b'1.60 mmol/L', b'CALCULATED PARAMETERS': '', b'HCO3': b'20.99 mmol/L', b'TCO2': b'21.74 mmol/L', b'SBC': b'24.33 mmol/L', b'O2Ct': b'12.94 Vol%', b'pO2%': b'7.48 %', b'BE': b'-1.36 mmol/L', b'BE-B': b'-0.13 mmol/L', b'BE-ECF': b'-1.89 mmol/L', b'Anion Gap': '', b'AG-Na': b'10.24 mmol/L', b'AG-K': b'13.50 mmol/L', b'Alveolar oxygen': '', b'A': b'119.9 mmHg', b'AaDO2': b'63.12 mmHg', b'a/A': b'47.38 %', b'\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0': ''}} {b'1297254': { b'Date': b'time: 18-11-2021 11:46:59', b'': '', b'Patient ID : 1297254': '', b'Name :': '', b'Gender :': '', b'Age :': '', b'Department :': '', b'Hospital Name :': '', b'----------------------': '', b'FiO2 : 0.21': '', b'Pat. Temp : 37.0': '', b'TRef : 26.250': '', b'BLOOD GAS': '', b'pH': b'7.531', b'pCO2': b'24.86 mmHg', b'pO2': b'56.84 mmHg', b'HEMATOCRIT': '', b'Hct': b'29.67 %', b'SO2': b'92.84 %', b'Hb': b'9.89 g/dL', b'ELECTROLYTES': '', b'Na': b'146.8 mmol/L', b'K': b'3.26 mmol/L', b'iCa': b'0.93 mmol/L', b'Cl': b'115.6 mmol/L', b'Li': b'NA NA', b'nCa': b'1.00 mmol/L', b'TCa': b'1.99 mmol/L', b'METABOLITES': '', b'GLU': b'104.9 mg/dL', b'LAC': b'1.60 mmol/L', b'CALCULATED PARAMETERS': '', b'HCO3': b'20.99 mmol/L', b'TCO2': b'21.74 mmol/L', b'SBC': b'24.33 mmol/L', b'O2Ct': b'12.94 Vol%', b'pO2%': b'7.48 %', b'BE': b'-1.36 mmol/L', b'BE-B': b'-0.13 mmol/L', b'BE-ECF': b'-1.89 mmol/L', b'Anion Gap': '', b'AG-Na': b'10.24 mmol/L', b'AG-K': b'13.50 mmol/L', b'Alveolar oxygen': '', b'A': b'119.9 mmHg', b'AaDO2': b'63.12 mmHg', b'a/A': b'47.38 %', b'\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0': ''}} 021-11-19 18:03:05,825 data: { b'Date': b'time: 19-11-2021 17:39:09', b'': '', b'Patient ID : 1298280': '', b'Name :': '', b'Gender :': '', b'Age :': '', b'Department :': '', b'Hospital Name :': '', b'----------------------': '', b'FiO2 : 0.21': '', b'Pat. Temp : 37.0': '', b'TRef : 26.375': '', b'BLOOD GAS': '', b'pH': b'7.594', b'pCO2': b'24.65 mmHg', b'pO2': b'214.3 mmHg', b'HEMATOCRIT': '', b'Hct': b'29.06 %', b'SO2': b'99.88 %', b'Hb': b'9.69 g/dL', b'ELECTROLYTES': '', b'Na': b'147.8 mmol/L', b'K': b'2.00 mmol/L', b'iCa': b'0.80 mmol/L', b'Cl': b'124.1 mmol/L', b'Li': b'NA NA', b'nCa': b'0.89 mmol/L', b'TCa': b'1.78 mmol/L', b'METABOLITES': '', b'GLU': b'66.91 mg/dL', b'LAC': b'2.17 mmol/L', b'CALCULATED PARAMETERS': '', b'HCO3': b'24.09 mmol/L', b'TCO2': b'24.83 mmol/L', b'SBC': b'27.72 mmol/L', b'O2Ct': b'14.11 Vol%', b'pO2%': b'28.21 %', b'BE': b'2.39 mmol/L', b'BE-B': b'3.69 mmol/L', b'BE-ECF': b'2.23 mmol/L', b'Anion Gap': '', b'AG-Na': b'-0.29 mmol/L', b'AG-K': b'1.71 mmol/L', b'Alveolar oxygen': '', b'A': b'120.2 mmHg', b'AaDO2': b'-94.1 mmHg', b'a/A': b'178.3 %', b'\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0': ''} 2021-11-19 18:03:05,825 pH: b'7.594' 2021-11-19 18:03:05,825 pCO2: b'24.65 mmHg' 2021-11-19 18:03:05,825 Na: b'147.8 mmol/L' 2021-11-19 18:03:05,825 K: b'2.00 mmol/L' 2021-11-19 18:03:05,825 iCa: b'0.80 mmol/L' 2021-11-19 18:03:05,825 Cl: b'124.1 mmol/L'
all record: { b'1297254': { b'Date': b'time: 18-11-2021 11:46:59', b'': '', b'Patient ID : 1297254': '', b'Name :': '', b'Gender :': '', b'Age :': '', b'Department :': '', b'Hospital Name :': '', b'----------------------': '', b'FiO2 : 0.21': '', b'Pat. Temp : 37.0': '', b'TRef : 26.250': '', b'BLOOD GAS': '', b'pCO2': b'24.86 mmHg', b'pO2': b'56.84 mmHg', b'HEMATOCRIT': '', b'Hct': b'29.67 %', b'SO2': b'92.84 %', b'Hb': b'9.89 g/dL', b'ELECTROLYTES': '', b'Na': b'146.8 mmol/L', b'K': b'3.26 mmol/L', b'iCa': b'0.93 mmol/L', b'Cl': b'115.6 mmol/L', b'Li': b'NA NA', b'nCa': b'1.00 mmol/L', b'TCa': b'1.99 mmol/L', b'METABOLITES': '', b'GLU': b'104.9 mg/dL', b'LAC': b'1.60 mmol/L', b'CALCULATED PARAMETERS': '', b'HCO3': b'20.99 mmol/L', b'TCO2': b'21.74 mmol/L', b'SBC': b'24.33 mmol/L', b'O2Ct': b'12.94 Vol%', b'pO2%': b'7.48 %', b'BE': b'-1.36 mmol/L', b'BE-B': b'-0.13 mmol/L', b'BE-ECF': b'-1.89 mmol/L', b'Anion Gap': '', b'AG-Na': b'10.24 mmol/L', b'AG-K': b'13.50 mmol/L', b'Alveolar oxygen': '', b'A': b'119.9 mmHg', b'AaDO2': b'63.12 mmHg', b'a/A': b'47.38 %', b'\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0': ''}} {b'1297254': { b'Date': b'time: 18-11-2021 11:46:59', b'': '', b'Patient ID : 1297254': '', b'Name :': '', b'Gender :': '', b'Age :': '', b'Department :': '', b'Hospital Name :': '', b'----------------------': '', b'FiO2 : 0.21': '', b'Pat. Temp : 37.0': '', b'TRef : 26.250': '', b'BLOOD GAS': '', b'pH': b'7.531', b'pCO2': b'24.86 mmHg', b'pO2': b'56.84 mmHg', b'HEMATOCRIT': '', b'Hct': b'29.67 %', b'SO2': b'92.84 %', b'Hb': b'9.89 g/dL', b'ELECTROLYTES': '', b'Na': b'146.8 mmol/L', b'K': b'3.26 mmol/L', b'iCa': b'0.93 mmol/L', b'Cl': b'115.6 mmol/L', b'Li': b'NA NA', b'nCa': b'1.00 mmol/L', b'TCa': b'1.99 mmol/L', b'METABOLITES': '', b'GLU': b'104.9 mg/dL', b'LAC': b'1.60 mmol/L', b'CALCULATED PARAMETERS': '', b'HCO3': b'20.99 mmol/L', b'TCO2': b'21.74 mmol/L', b'SBC': b'24.33 mmol/L', b'O2Ct': b'12.94 Vol%', b'pO2%': b'7.48 %', b'BE': b'-1.36 mmol/L', b'BE-B': b'-0.13 mmol/L', b'BE-ECF': b'-1.89 mmol/L', b'Anion Gap': '', b'AG-Na': b'10.24 mmol/L', b'AG-K': b'13.50 mmol/L', b'Alveolar oxygen': '', b'A': b'119.9 mmHg', b'AaDO2': b'63.12 mmHg', b'a/A': b'47.38 %', b'\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0': ''}} 021-11-19 18:03:05,825 data: { b'Date': b'time: 19-11-2021 17:39:09', b'': '', b'Patient ID : 1298280': '', b'Name :': '', b'Gender :': '', b'Age :': '', b'Department :': '', b'Hospital Name :': '', b'----------------------': '', b'FiO2 : 0.21': '', b'Pat. Temp : 37.0': '', b'TRef : 26.375': '', b'BLOOD GAS': '', b'pH': b'7.594', b'pCO2': b'24.65 mmHg', b'pO2': b'214.3 mmHg', b'HEMATOCRIT': '', b'Hct': b'29.06 %', b'SO2': b'99.88 %', b'Hb': b'9.69 g/dL', b'ELECTROLYTES': '', b'Na': b'147.8 mmol/L', b'K': b'2.00 mmol/L', b'iCa': b'0.80 mmol/L', b'Cl': b'124.1 mmol/L', b'Li': b'NA NA', b'nCa': b'0.89 mmol/L', b'TCa': b'1.78 mmol/L', b'METABOLITES': '', b'GLU': b'66.91 mg/dL', b'LAC': b'2.17 mmol/L', b'CALCULATED PARAMETERS': '', b'HCO3': b'24.09 mmol/L', b'TCO2': b'24.83 mmol/L', b'SBC': b'27.72 mmol/L', b'O2Ct': b'14.11 Vol%', b'pO2%': b'28.21 %', b'BE': b'2.39 mmol/L', b'BE-B': b'3.69 mmol/L', b'BE-ECF': b'2.23 mmol/L', b'Anion Gap': '', b'AG-Na': b'-0.29 mmol/L', b'AG-K': b'1.71 mmol/L', b'Alveolar oxygen': '', b'A': b'120.2 mmHg', b'AaDO2': b'-94.1 mmHg', b'a/A': b'178.3 %', b'\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0\xc2\xb0': ''} 2021-11-19 18:03:05,825 pH: b'7.594' 2021-11-19 18:03:05,825 pCO2: b'24.65 mmHg' 2021-11-19 18:03:05,825 Na: b'147.8 mmol/L' 2021-11-19 18:03:05,825 K: b'2.00 mmol/L' 2021-11-19 18:03:05,825 iCa: b'0.80 mmol/L' 2021-11-19 18:03:05,825 Cl: b'124.1 mmol/L'
none
1
1.225119
1
Algoritmos/AproximacaoMinimosQuadrados_CaduSantana.py
CaduSantana/hacktoberfest-2021-codigos
2
6613671
from sklearn.datasets import make_regression from matplotlib import pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression # Functions def gram_schmidt(a): q = [] for i in range(len(a)): #orthogonalization q_tilde = a[i] for j in range(len(q)): q_tilde = q_tilde - (q[j] @ a[i])*q[j] #Test for dependennce if np.sqrt(sum(q_tilde**2)) <= 1e-10: print('Vectors are linearly dependent.') print('GS algorithm terminates at iteration ', i+1) return q #Normalization else: q_tilde = q_tilde / np.sqrt(sum(q_tilde**2)) q.append(q_tilde) print('Vectors are linearly independent.') return q def QR_factorization(A): Q_transpose = np.array(gram_schmidt(A.T)) R = Q_transpose @ A Q = Q_transpose.T return Q, R def back_subst(R,b_tilde): n = R.shape[0] x = np.zeros(n) for i in reversed(range(n)): x[i] = b_tilde[i] for j in range(i+1,n): x[i] = x[i] - R[i,j]*x[j] x[i] = x[i]/R[i,i] return x def solve_via_backsub(A,b): Q,R = QR_factorization(A) b_tilde = Q.T @ b x = back_subst(R,b_tilde) return x ######### # # Least squares problem # A = np.array([[2,0],[-1,1],[0,2]]) # b = np.array([1,0,-1]) # x_hat = np.array([1/3, -1/3]) # r_hat = A @ x_hat - b # print(np.linalg.norm(r_hat)) # x = np.array([1/2, -1/2]) #other value of x # r = A @ x - b # print(np.linalg.norm(r)) # print(np.linalg.inv(A.T @ A) @ A.T @ b) # print(np.linalg.pinv(A) @ b) # print((A.T @ A) @ x_hat - A.T @ b) #Check that normal equations hold # # Principio da ortogonalidade # z = np.array([-1.1,2.3]) # print(A @ z).T @ r_hat) # z = np.array([5.3, -1.2]) # print((A @ z).T @ r_hat) # # Resolvendo problemas de quadrados mínimos # A = np.random.normal(size = (100,20)) # b = np.random.normal(size = 100) # x1 = solve_via_backsub(A,b) # x2 = np.linalg.inv(A.T @ A) @ (A.T @ b) # x3 = np.linalg.pinv(A) @ b # print(np.linalg.norm(x1-x2)) # print(np.linalg.norm(x2-x3)) # print(np.linalg.norm(x3-x1)) # Exemplo página 234 n = 10 # número de lâmpadas # posições (x,y) das lâmpadas e altura acima do chão lamps = np.array([[4.1 ,20.4, 4], [14.1, 21.3, 3.5], [22.6, 17.1,6], [5.5 ,12.3, 4.0], [12.2, 9.7, 4.0], [15.3, 13.8, 6], [21.3, 10.5, 5.5], [3.9 ,3.3, 5.0], [13.1, 4.3, 5.0], [20.3,4.2, 4.5]]) N = 25 # grid size m = N*N # Número de pixels # construct m x 2 matrix with coordinates of pixel centers pixels = np.hstack([np.outer(np.arange(0.5,N,1),np.ones(N)).reshape(m,1), np.outer(np.ones(N),np.arange(0.5,N,1)).reshape(m,1)]) # The m x n matrix A maps lamp powers to pixel intensities. # A[i,j] is inversely proportional to the squared distance of # lamp j to pixel i. A = np.zeros((m,n)) for i in range(m): for j in range(n): A[i,j] = 1.0 / (np.linalg.norm(np.hstack([pixels[i,:], 0]) - lamps[j,:])**2) A = (m / np.sum(A)) * A # scale elements of A # Least squares solution x = solve_via_backsub(A, np.ones(m)) rms_ls = (sum((A @ x - 1)**2)/m)**0.5 print(rms_ls) import matplotlib.pyplot as plt plt.ion() plt.hist(A @ x, bins = 25) plt.show() plt.pause(10) # Intensity if all lamp powers are one rms_uniform = (sum((A @ np.ones(n) - 1)**2)/m)**0.5 print(rms_uniform) plt.hist(A @ np.ones(n), bins = 25) plt.show() plt.pause(10)
from sklearn.datasets import make_regression from matplotlib import pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression # Functions def gram_schmidt(a): q = [] for i in range(len(a)): #orthogonalization q_tilde = a[i] for j in range(len(q)): q_tilde = q_tilde - (q[j] @ a[i])*q[j] #Test for dependennce if np.sqrt(sum(q_tilde**2)) <= 1e-10: print('Vectors are linearly dependent.') print('GS algorithm terminates at iteration ', i+1) return q #Normalization else: q_tilde = q_tilde / np.sqrt(sum(q_tilde**2)) q.append(q_tilde) print('Vectors are linearly independent.') return q def QR_factorization(A): Q_transpose = np.array(gram_schmidt(A.T)) R = Q_transpose @ A Q = Q_transpose.T return Q, R def back_subst(R,b_tilde): n = R.shape[0] x = np.zeros(n) for i in reversed(range(n)): x[i] = b_tilde[i] for j in range(i+1,n): x[i] = x[i] - R[i,j]*x[j] x[i] = x[i]/R[i,i] return x def solve_via_backsub(A,b): Q,R = QR_factorization(A) b_tilde = Q.T @ b x = back_subst(R,b_tilde) return x ######### # # Least squares problem # A = np.array([[2,0],[-1,1],[0,2]]) # b = np.array([1,0,-1]) # x_hat = np.array([1/3, -1/3]) # r_hat = A @ x_hat - b # print(np.linalg.norm(r_hat)) # x = np.array([1/2, -1/2]) #other value of x # r = A @ x - b # print(np.linalg.norm(r)) # print(np.linalg.inv(A.T @ A) @ A.T @ b) # print(np.linalg.pinv(A) @ b) # print((A.T @ A) @ x_hat - A.T @ b) #Check that normal equations hold # # Principio da ortogonalidade # z = np.array([-1.1,2.3]) # print(A @ z).T @ r_hat) # z = np.array([5.3, -1.2]) # print((A @ z).T @ r_hat) # # Resolvendo problemas de quadrados mínimos # A = np.random.normal(size = (100,20)) # b = np.random.normal(size = 100) # x1 = solve_via_backsub(A,b) # x2 = np.linalg.inv(A.T @ A) @ (A.T @ b) # x3 = np.linalg.pinv(A) @ b # print(np.linalg.norm(x1-x2)) # print(np.linalg.norm(x2-x3)) # print(np.linalg.norm(x3-x1)) # Exemplo página 234 n = 10 # número de lâmpadas # posições (x,y) das lâmpadas e altura acima do chão lamps = np.array([[4.1 ,20.4, 4], [14.1, 21.3, 3.5], [22.6, 17.1,6], [5.5 ,12.3, 4.0], [12.2, 9.7, 4.0], [15.3, 13.8, 6], [21.3, 10.5, 5.5], [3.9 ,3.3, 5.0], [13.1, 4.3, 5.0], [20.3,4.2, 4.5]]) N = 25 # grid size m = N*N # Número de pixels # construct m x 2 matrix with coordinates of pixel centers pixels = np.hstack([np.outer(np.arange(0.5,N,1),np.ones(N)).reshape(m,1), np.outer(np.ones(N),np.arange(0.5,N,1)).reshape(m,1)]) # The m x n matrix A maps lamp powers to pixel intensities. # A[i,j] is inversely proportional to the squared distance of # lamp j to pixel i. A = np.zeros((m,n)) for i in range(m): for j in range(n): A[i,j] = 1.0 / (np.linalg.norm(np.hstack([pixels[i,:], 0]) - lamps[j,:])**2) A = (m / np.sum(A)) * A # scale elements of A # Least squares solution x = solve_via_backsub(A, np.ones(m)) rms_ls = (sum((A @ x - 1)**2)/m)**0.5 print(rms_ls) import matplotlib.pyplot as plt plt.ion() plt.hist(A @ x, bins = 25) plt.show() plt.pause(10) # Intensity if all lamp powers are one rms_uniform = (sum((A @ np.ones(n) - 1)**2)/m)**0.5 print(rms_uniform) plt.hist(A @ np.ones(n), bins = 25) plt.show() plt.pause(10)
en
0.37897
# Functions #orthogonalization #Test for dependennce #Normalization ######### # # Least squares problem # A = np.array([[2,0],[-1,1],[0,2]]) # b = np.array([1,0,-1]) # x_hat = np.array([1/3, -1/3]) # r_hat = A @ x_hat - b # print(np.linalg.norm(r_hat)) # x = np.array([1/2, -1/2]) #other value of x # r = A @ x - b # print(np.linalg.norm(r)) # print(np.linalg.inv(A.T @ A) @ A.T @ b) # print(np.linalg.pinv(A) @ b) # print((A.T @ A) @ x_hat - A.T @ b) #Check that normal equations hold # # Principio da ortogonalidade # z = np.array([-1.1,2.3]) # print(A @ z).T @ r_hat) # z = np.array([5.3, -1.2]) # print((A @ z).T @ r_hat) # # Resolvendo problemas de quadrados mínimos # A = np.random.normal(size = (100,20)) # b = np.random.normal(size = 100) # x1 = solve_via_backsub(A,b) # x2 = np.linalg.inv(A.T @ A) @ (A.T @ b) # x3 = np.linalg.pinv(A) @ b # print(np.linalg.norm(x1-x2)) # print(np.linalg.norm(x2-x3)) # print(np.linalg.norm(x3-x1)) # Exemplo página 234 # número de lâmpadas # posições (x,y) das lâmpadas e altura acima do chão # grid size # Número de pixels # construct m x 2 matrix with coordinates of pixel centers # The m x n matrix A maps lamp powers to pixel intensities. # A[i,j] is inversely proportional to the squared distance of # lamp j to pixel i. # scale elements of A # Least squares solution # Intensity if all lamp powers are one
3.506223
4
ms/protobufs/protobuf_to_dict.py
jcnelson/syndicate
16
6613672
# public domain code # source: https://github.com/benhodgson/protobuf-to-dict/blob/master/src/protobuf_to_dict.py # accessed 2/12/2013 from googlepb.protobuf.descriptor import FieldDescriptor __all__ = ["protobuf_to_dict", "TYPE_CALLABLE_MAP"] TYPE_CALLABLE_MAP = { FieldDescriptor.TYPE_DOUBLE: float, FieldDescriptor.TYPE_FLOAT: float, FieldDescriptor.TYPE_INT32: int, FieldDescriptor.TYPE_INT64: long, FieldDescriptor.TYPE_UINT32: int, FieldDescriptor.TYPE_UINT64: long, FieldDescriptor.TYPE_SINT32: int, FieldDescriptor.TYPE_SINT64: long, FieldDescriptor.TYPE_FIXED32: int, FieldDescriptor.TYPE_FIXED64: long, FieldDescriptor.TYPE_SFIXED32: int, FieldDescriptor.TYPE_SFIXED64: long, FieldDescriptor.TYPE_BOOL: bool, FieldDescriptor.TYPE_STRING: unicode, FieldDescriptor.TYPE_BYTES: lambda b: b.encode("base64"), FieldDescriptor.TYPE_ENUM: int, } def repeated(type_callable): return lambda value_list: [type_callable(value) for value in value_list] def enum_label_name(field, value): return field.enum_type.values_by_number[int(value)].name def protobuf_to_dict(pb, type_callable_map=TYPE_CALLABLE_MAP, use_enum_labels=False): result_dict = {} for field, value in pb.ListFields(): if field.type not in type_callable_map: raise TypeError("Field %s.%s has unrecognised type id %d" % ( pb.__class__.__name__, field.name, field.type)) type_callable = type_callable_map[field.type] if use_enum_labels and field.type == FieldDescriptor.TYPE_ENUM: type_callable = lambda value: enum_label_name(field, value) if field.label == FieldDescriptor.LABEL_REPEATED: type_callable = repeated(type_callable) result_dict[field.name] = type_callable(value) return result_dict # recursion! TYPE_CALLABLE_MAP[FieldDescriptor.TYPE_MESSAGE] = protobuf_to_dict
# public domain code # source: https://github.com/benhodgson/protobuf-to-dict/blob/master/src/protobuf_to_dict.py # accessed 2/12/2013 from googlepb.protobuf.descriptor import FieldDescriptor __all__ = ["protobuf_to_dict", "TYPE_CALLABLE_MAP"] TYPE_CALLABLE_MAP = { FieldDescriptor.TYPE_DOUBLE: float, FieldDescriptor.TYPE_FLOAT: float, FieldDescriptor.TYPE_INT32: int, FieldDescriptor.TYPE_INT64: long, FieldDescriptor.TYPE_UINT32: int, FieldDescriptor.TYPE_UINT64: long, FieldDescriptor.TYPE_SINT32: int, FieldDescriptor.TYPE_SINT64: long, FieldDescriptor.TYPE_FIXED32: int, FieldDescriptor.TYPE_FIXED64: long, FieldDescriptor.TYPE_SFIXED32: int, FieldDescriptor.TYPE_SFIXED64: long, FieldDescriptor.TYPE_BOOL: bool, FieldDescriptor.TYPE_STRING: unicode, FieldDescriptor.TYPE_BYTES: lambda b: b.encode("base64"), FieldDescriptor.TYPE_ENUM: int, } def repeated(type_callable): return lambda value_list: [type_callable(value) for value in value_list] def enum_label_name(field, value): return field.enum_type.values_by_number[int(value)].name def protobuf_to_dict(pb, type_callable_map=TYPE_CALLABLE_MAP, use_enum_labels=False): result_dict = {} for field, value in pb.ListFields(): if field.type not in type_callable_map: raise TypeError("Field %s.%s has unrecognised type id %d" % ( pb.__class__.__name__, field.name, field.type)) type_callable = type_callable_map[field.type] if use_enum_labels and field.type == FieldDescriptor.TYPE_ENUM: type_callable = lambda value: enum_label_name(field, value) if field.label == FieldDescriptor.LABEL_REPEATED: type_callable = repeated(type_callable) result_dict[field.name] = type_callable(value) return result_dict # recursion! TYPE_CALLABLE_MAP[FieldDescriptor.TYPE_MESSAGE] = protobuf_to_dict
en
0.521397
# public domain code # source: https://github.com/benhodgson/protobuf-to-dict/blob/master/src/protobuf_to_dict.py # accessed 2/12/2013 # recursion!
2.298323
2
zerionAPI/ifb_utilities.py
jhsu98/zws-py
4
6613673
<reponame>jhsu98/zws-py from zerionAPI import IFB from pprint import pprint import json import os import requests import shutil import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def exportImages(api, profile_id, page_id, isRecursive=False, directory = '.'): print( 'Getting page...', result := api.Pages('GET', profile_id, page_id) ) if result.status_code == 200: count = 0 page = result.response try: directory = f'{directory}/{page["name"]}' os.makedirs(directory, exist_ok=True) except FileExistsError as e: print(e) pass elements_field_grammar = 'name,data_type((="11")|(="18")|(="28")),data_size' if isRecursive else 'name,data_type((="11")|(="28"))' print( 'Getting elements...', result := api.Elements('GET', profile_id, page['id'], params={'fields': elements_field_grammar}) ) if result.status_code == 200 and len(result.response) > 0: elements = result.response image_elements = [element for element in elements if element['data_type'] in (11, 28)] subform_elements = [element for element in elements if element['data_type'] == 18] # Image Element Loop if len(image_elements) > 0: print('Getting records...') result = api.Records('GET', profile_id, page['id'], params={'fields': ','.join([e['name'] for e in image_elements])}) if result.status_code == 200 and len(result.response) > 0: records = result.response total = int(result.headers.get('Total-Count')) print(f'Retrieved {len(records)}/{total} records...') while len(records) < total: result = api.Records('GET', profile_id, page['id'], params={'fields': ','.join([e['name'] for e in image_elements]), 'offset': len(records)}) if result.status_code == 200 and len(result.response) > 0: records += result.response for record in records: record_id = record['id'] elements = {key: record[key] for key in record if key != 'id' and record[key] != None} for element in elements: r = requests.get(record[element], verify=False, stream=True) r.raw.decode_content = True filename = f'{record_id}_{element}.{record[element].split(".")[-1]}' filepath = f'{directory}/{filename}' with open(filepath, 'wb') as f: print(f'Exporting <{record[element]}> as "{filepath}"') shutil.copyfileobj(r.raw, f) else: print('No records found...') else: print('No image elements found...') # Subform Element Loop if isRecursive and len(subform_elements) > 0: for element in subform_elements: print(f'Recursing into {element["name"]}...') count += exportImages(api, profile_id, element['data_size'], isRecursive, directory=directory) else: print('No image elements found...') return 0 else: print('Page not found...') return 0 if __name__ == "__main__": print('Not directly accessible') exit()
from zerionAPI import IFB from pprint import pprint import json import os import requests import shutil import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def exportImages(api, profile_id, page_id, isRecursive=False, directory = '.'): print( 'Getting page...', result := api.Pages('GET', profile_id, page_id) ) if result.status_code == 200: count = 0 page = result.response try: directory = f'{directory}/{page["name"]}' os.makedirs(directory, exist_ok=True) except FileExistsError as e: print(e) pass elements_field_grammar = 'name,data_type((="11")|(="18")|(="28")),data_size' if isRecursive else 'name,data_type((="11")|(="28"))' print( 'Getting elements...', result := api.Elements('GET', profile_id, page['id'], params={'fields': elements_field_grammar}) ) if result.status_code == 200 and len(result.response) > 0: elements = result.response image_elements = [element for element in elements if element['data_type'] in (11, 28)] subform_elements = [element for element in elements if element['data_type'] == 18] # Image Element Loop if len(image_elements) > 0: print('Getting records...') result = api.Records('GET', profile_id, page['id'], params={'fields': ','.join([e['name'] for e in image_elements])}) if result.status_code == 200 and len(result.response) > 0: records = result.response total = int(result.headers.get('Total-Count')) print(f'Retrieved {len(records)}/{total} records...') while len(records) < total: result = api.Records('GET', profile_id, page['id'], params={'fields': ','.join([e['name'] for e in image_elements]), 'offset': len(records)}) if result.status_code == 200 and len(result.response) > 0: records += result.response for record in records: record_id = record['id'] elements = {key: record[key] for key in record if key != 'id' and record[key] != None} for element in elements: r = requests.get(record[element], verify=False, stream=True) r.raw.decode_content = True filename = f'{record_id}_{element}.{record[element].split(".")[-1]}' filepath = f'{directory}/{filename}' with open(filepath, 'wb') as f: print(f'Exporting <{record[element]}> as "{filepath}"') shutil.copyfileobj(r.raw, f) else: print('No records found...') else: print('No image elements found...') # Subform Element Loop if isRecursive and len(subform_elements) > 0: for element in subform_elements: print(f'Recursing into {element["name"]}...') count += exportImages(api, profile_id, element['data_size'], isRecursive, directory=directory) else: print('No image elements found...') return 0 else: print('Page not found...') return 0 if __name__ == "__main__": print('Not directly accessible') exit()
en
0.357114
# Image Element Loop # Subform Element Loop
2.282277
2
Python Exercises/Mundo1/exercicio18.py
joaopblume/Curso-em-video-exercicios
0
6613674
# Faça um programa que leia um ângulo qualquer e mostre na tela # o valor do seno, cosseno e tangente desse ângulos import math angulo = int(input('Digite o ângulo desejado: ')) sen = math.sin(math.radians(angulo)) cos = math.cos(math.radians(angulo)) tg = math.tan(math.radians(angulo)) print(f'O ângulo de {angulo} tem seno de {sen:.2f}, cosseno de {cos:.2f} e tangente de {tg:.2f}.')
# Faça um programa que leia um ângulo qualquer e mostre na tela # o valor do seno, cosseno e tangente desse ângulos import math angulo = int(input('Digite o ângulo desejado: ')) sen = math.sin(math.radians(angulo)) cos = math.cos(math.radians(angulo)) tg = math.tan(math.radians(angulo)) print(f'O ângulo de {angulo} tem seno de {sen:.2f}, cosseno de {cos:.2f} e tangente de {tg:.2f}.')
pt
0.863731
# Faça um programa que leia um ângulo qualquer e mostre na tela # o valor do seno, cosseno e tangente desse ângulos
3.955292
4
ample/util/reference_manager.py
fsimkovic/ample
6
6613675
<filename>ample/util/reference_manager.py """Various miscellaneous functions""" __author__ = "<NAME>, and <NAME>" __date__ = "16 Jul 2018" from collections import OrderedDict import copy from enum import Enum import os from ample.util.ample_util import is_file from ample.constants import SHARE_DIR from ample.ensembler.constants import SPICKER_RMSD, SPICKER_TM class ReferenceManager: # Section Names class SECTIONS(Enum): __order__ = 'GENERAL MODELLING MODEL_PREP MR REFINEMENT DM AUTOBUILD' GENERAL = 'General' MODELLING = 'Modelling' MODEL_PREP = 'Search model preparation' MR = 'Molecular Replacement' REFINEMENT = 'Refinement' DM = 'Main-chain tracing and density modification' AUTOBUILD = 'Autobuilding' SEC_TAG = 'h3' def __init__(self, optd): self.references = {} self.ordered_labels = [] self.citation_file_path = None self.section_labels = OrderedDict() self.setup_references() self.setup_sections(optd) def setup_references(self): ref_fname = os.path.join(SHARE_DIR, "include", "ample.bib") if not is_file(ref_fname): msg = "Cannot find BibTex file containing references. " "Please determine them yourself and cite AMPLE." return msg article = {} entry = False with open(ref_fname, "r") as fhin: for line in fhin.readlines(): line = line.strip() if not line: continue elif line.startswith("@"): # Beginning of all BibTex entry blocks entry = True unique_id = line.replace("@article{", "").replace(",", "") article = {'unique_id': unique_id} # Reset the article dictionary elif line == "}": # End of all BibTex entry blocks entry = False self.references[article['label']] = article elif entry: # BibTex entry block # Some dirty line handling. # Not very bulletproof but should do for now line = line.replace("{", "").replace("}", "") key, value = [l.strip() for l in line.split("=")] value = value.rstrip(",").replace("\"", "") # Save the data to the article entry article[key] = value return def setup_sections(self, optd): # Create default lists for section in self.SECTIONS: self.section_labels[section] = [] # Build up list of program reference labels, ordered by sections for section in self.SECTIONS: if section == self.SECTIONS.GENERAL: self.section_labels[section] = ['AMPLE', 'CCP4', 'AMPLE_COILED-COILS', 'AMPLE_CONTACTS'] elif section == self.SECTIONS.MODELLING: labels = [] if optd.get('ideal_helices') or optd.get('helical_ensembles'): labels.append('AMPLE_COILED-COILS') if optd.get('make_models'): labels.append('ROSETTA') if optd.get('nmr_model_in'): labels.append('AMPLE_NMR') if optd.get('quark_models'): labels.append('QUARK') labels.append('AMPLE_QUARK') if optd.get('transmembrane'): labels.append('AMPLE_TRANSMEMBRANE') self.section_labels[section] = labels elif section == self.SECTIONS.MODEL_PREP: labels = [] if not optd.get('import_ensembles'): labels += ['CCTBX', 'THESEUS', 'GESAMT'] if optd.get('use_scwrl'): labels.append('SCWRL4') elif optd['cluster_method'] in [SPICKER_RMSD, SPICKER_TM]: labels.append('SPICKER') elif optd['cluster_method'] in ['fast_protein_cluster']: labels.append('FPC') self.section_labels[section] = labels if optd.get('do_mr'): if section == self.SECTIONS.MR: labels = ['MRBUMP'] if optd.get('mrbump_programs'): if 'molrep' in optd['mrbump_programs']: labels.append('MOLREP') if 'phaser' in optd['mrbump_programs']: labels.append('PHASER') self.section_labels[section] = labels elif section == self.SECTIONS.REFINEMENT: self.section_labels[self.SECTIONS.REFINEMENT] = ['REFMAC'] elif section == self.SECTIONS.DM: if optd.get('use_shelxe'): self.section_labels[self.SECTIONS.DM].append('SHELXE') elif section == self.SECTIONS.AUTOBUILD: labels = [] if optd.get('refine_rebuild_arpwarp') or optd.get('shelxe_rebuild_arpwarp'): labels += ['ARPWARP'] elif optd.get('refine_rebuild_buccaneer') or optd.get('shelxe_rebuild_buccaneer'): labels += ['BUCCANEER'] self.section_labels[section] = labels # Generate ordered list of all relevant reference labels for section in self.SECTIONS: if section in self.section_labels: self.ordered_labels += self.section_labels[section] return @property def methods_as_html(self): html = ( "<p>This section lists the programs and algorithms that were used in this job and the references that should be cited. " + "Numbers in superscript next to program/reference names refer to the number of the program reference in the overall list of references.</p>" ) for section in self.SECTIONS: if section == self.SECTIONS.GENERAL: html += ( '<p>The first 2 references should be cited in all cases.</p>' + '<p>If your protein was a coiled-coil protein, please cite reference number 3.</p>' + '<p>If coevolutionary contact information was used in the generation of your models, please cite reference number 4.</p>' ) elif section == self.SECTIONS.MODELLING and len(self.section_labels[self.SECTIONS.MODELLING]): standfirst = "<p>The following programs or algorithims were used for model building:</p>" html += self._methods_section_html(self.SECTIONS.MODELLING, standfirst) elif section == self.SECTIONS.MODEL_PREP and len(self.section_labels[self.SECTIONS.MODEL_PREP]): standfirst = ( '<p>Model analysis and search model preparation was carried out with the following programs:</p>' ) html += self._methods_section_html(self.SECTIONS.MODEL_PREP, standfirst) elif section == self.SECTIONS.MR and len(self.section_labels[self.SECTIONS.MR]): standfirst = '<p>Molecular Replacement was carried out with the following programs:</p>' html += self._methods_section_html(self.SECTIONS.MR, standfirst) elif section == self.SECTIONS.REFINEMENT and len(self.section_labels[self.SECTIONS.REFINEMENT]): standfirst = '<pRefinement of the MR solutions carried out with the following programs:</p>' html += self._methods_section_html(self.SECTIONS.REFINEMENT, standfirst) elif section == self.SECTIONS.DM and len(self.section_labels[self.SECTIONS.DM]): standfirst = ( '<p>Density modification and main-chain tracing was carried out with the following programs:</p>' ) html += self._methods_section_html(self.SECTIONS.DM, standfirst) elif section == self.SECTIONS.AUTOBUILD and len(self.section_labels[self.SECTIONS.AUTOBUILD]): standfirst = 'Autobuilding of the final structure was carried out with the following programs:</p>' html += self._methods_section_html(self.SECTIONS.AUTOBUILD, standfirst) return html def _methods_section_html(self, section, standfirst): mysec = self.SECTIONS(section) html = '<{}>{}</{}>'.format(self.SEC_TAG, mysec.value, self.SEC_TAG) html += standfirst html += '<ul>' for label in self.section_labels[mysec]: html += "<li>{}<sup>{}</sup></li>".format(label, self.ordered_labels.index(label) + 1) html += "</ul>" return html @property def citations_as_html(self): html = '<{}>References</{}>'.format(self.SEC_TAG, self.SEC_TAG) html += '<ol>' template_txt = "<li> {author} ({year}). {title}. {journal} {volume}({number}), {pages}. [doi:{doi}]</li>" for label in self.ordered_labels: ref = copy.copy(self.references[label]) ref['author'] = ref['author'].split(" and ")[0].split(",")[0] + " et al." ref['pages'] = ref['pages'].replace("--", "-") html += template_txt.format(**ref) html += '</ol>' return html @property def citations_as_text(self): txt = """A number of programs and algorithms were used within the this run of AMPLE. The following is a list of citations for this run: {0} """.format( self.citation_list_as_text ) if self.citation_file_path: txt += """ A bibtex file with these references has been saved to the following file: {0} """.format( self.citation_file_path ) return txt @property def citation_list_as_text(self): template_txt = "* {author} ({year}). {title}. {journal} {volume}({number}), {pages}. [doi:{doi}]" text = "" for label in self.ordered_labels: ref = copy.copy(self.references[label]) ref['author'] = ref['author'].split(" and ")[0].split(",")[0] + " et al." ref['pages'] = ref['pages'].replace("--", "-") text += template_txt.format(**ref) + os.linesep * 2 return text def save_citations_to_file(self, optd): # ========================================================================= # Somewhat a template of how we want to write each article in BibTex format # ========================================================================= template_bib = ( "@article{{{unique_id},{sep}author = {{{author}}},{sep}doi = {{{doi}}},{sep}" "journal = {{{journal}}},{sep}number = {{{number}}},{sep}pages = {{{pages}}},{sep}" "title = {{{{{title}}}}},{sep}volume = {{{volume}}},{sep}year = {{{year}}},{sep}}}{sep}" ) references_bib = [template_bib.format(sep=os.linesep, **self.references[l]) for l in self.ordered_labels] ref_fname = os.path.join(optd['work_dir'], optd['name'] + ".bib") with open(ref_fname, "w") as fhout: fhout.write(os.linesep.join(references_bib)) self.citation_file_path = ref_fname return ref_fname # ====================================================================== # Some default string messages that we need during the program to inform # the user of certain information # ====================================================================== header = """ ######################################################################### ######################################################################### ######################################################################### # CCP4: AMPLE - Ab Initio Modelling Molecular Replacement # ######################################################################### """ # ====================================================================== # ====================================================================== survey_url = "http://goo.gl/forms/7xP9M4P81O" footer = """ ######################################################################### #***********************************************************************# #* How did we do? *# #* *# #* Please follow this link and leave some feedback! *# #* *# #* {url} *# #***********************************************************************# ######################################################################### """.format( url=survey_url ) # ====================================================================== # ======================================================================
<filename>ample/util/reference_manager.py """Various miscellaneous functions""" __author__ = "<NAME>, and <NAME>" __date__ = "16 Jul 2018" from collections import OrderedDict import copy from enum import Enum import os from ample.util.ample_util import is_file from ample.constants import SHARE_DIR from ample.ensembler.constants import SPICKER_RMSD, SPICKER_TM class ReferenceManager: # Section Names class SECTIONS(Enum): __order__ = 'GENERAL MODELLING MODEL_PREP MR REFINEMENT DM AUTOBUILD' GENERAL = 'General' MODELLING = 'Modelling' MODEL_PREP = 'Search model preparation' MR = 'Molecular Replacement' REFINEMENT = 'Refinement' DM = 'Main-chain tracing and density modification' AUTOBUILD = 'Autobuilding' SEC_TAG = 'h3' def __init__(self, optd): self.references = {} self.ordered_labels = [] self.citation_file_path = None self.section_labels = OrderedDict() self.setup_references() self.setup_sections(optd) def setup_references(self): ref_fname = os.path.join(SHARE_DIR, "include", "ample.bib") if not is_file(ref_fname): msg = "Cannot find BibTex file containing references. " "Please determine them yourself and cite AMPLE." return msg article = {} entry = False with open(ref_fname, "r") as fhin: for line in fhin.readlines(): line = line.strip() if not line: continue elif line.startswith("@"): # Beginning of all BibTex entry blocks entry = True unique_id = line.replace("@article{", "").replace(",", "") article = {'unique_id': unique_id} # Reset the article dictionary elif line == "}": # End of all BibTex entry blocks entry = False self.references[article['label']] = article elif entry: # BibTex entry block # Some dirty line handling. # Not very bulletproof but should do for now line = line.replace("{", "").replace("}", "") key, value = [l.strip() for l in line.split("=")] value = value.rstrip(",").replace("\"", "") # Save the data to the article entry article[key] = value return def setup_sections(self, optd): # Create default lists for section in self.SECTIONS: self.section_labels[section] = [] # Build up list of program reference labels, ordered by sections for section in self.SECTIONS: if section == self.SECTIONS.GENERAL: self.section_labels[section] = ['AMPLE', 'CCP4', 'AMPLE_COILED-COILS', 'AMPLE_CONTACTS'] elif section == self.SECTIONS.MODELLING: labels = [] if optd.get('ideal_helices') or optd.get('helical_ensembles'): labels.append('AMPLE_COILED-COILS') if optd.get('make_models'): labels.append('ROSETTA') if optd.get('nmr_model_in'): labels.append('AMPLE_NMR') if optd.get('quark_models'): labels.append('QUARK') labels.append('AMPLE_QUARK') if optd.get('transmembrane'): labels.append('AMPLE_TRANSMEMBRANE') self.section_labels[section] = labels elif section == self.SECTIONS.MODEL_PREP: labels = [] if not optd.get('import_ensembles'): labels += ['CCTBX', 'THESEUS', 'GESAMT'] if optd.get('use_scwrl'): labels.append('SCWRL4') elif optd['cluster_method'] in [SPICKER_RMSD, SPICKER_TM]: labels.append('SPICKER') elif optd['cluster_method'] in ['fast_protein_cluster']: labels.append('FPC') self.section_labels[section] = labels if optd.get('do_mr'): if section == self.SECTIONS.MR: labels = ['MRBUMP'] if optd.get('mrbump_programs'): if 'molrep' in optd['mrbump_programs']: labels.append('MOLREP') if 'phaser' in optd['mrbump_programs']: labels.append('PHASER') self.section_labels[section] = labels elif section == self.SECTIONS.REFINEMENT: self.section_labels[self.SECTIONS.REFINEMENT] = ['REFMAC'] elif section == self.SECTIONS.DM: if optd.get('use_shelxe'): self.section_labels[self.SECTIONS.DM].append('SHELXE') elif section == self.SECTIONS.AUTOBUILD: labels = [] if optd.get('refine_rebuild_arpwarp') or optd.get('shelxe_rebuild_arpwarp'): labels += ['ARPWARP'] elif optd.get('refine_rebuild_buccaneer') or optd.get('shelxe_rebuild_buccaneer'): labels += ['BUCCANEER'] self.section_labels[section] = labels # Generate ordered list of all relevant reference labels for section in self.SECTIONS: if section in self.section_labels: self.ordered_labels += self.section_labels[section] return @property def methods_as_html(self): html = ( "<p>This section lists the programs and algorithms that were used in this job and the references that should be cited. " + "Numbers in superscript next to program/reference names refer to the number of the program reference in the overall list of references.</p>" ) for section in self.SECTIONS: if section == self.SECTIONS.GENERAL: html += ( '<p>The first 2 references should be cited in all cases.</p>' + '<p>If your protein was a coiled-coil protein, please cite reference number 3.</p>' + '<p>If coevolutionary contact information was used in the generation of your models, please cite reference number 4.</p>' ) elif section == self.SECTIONS.MODELLING and len(self.section_labels[self.SECTIONS.MODELLING]): standfirst = "<p>The following programs or algorithims were used for model building:</p>" html += self._methods_section_html(self.SECTIONS.MODELLING, standfirst) elif section == self.SECTIONS.MODEL_PREP and len(self.section_labels[self.SECTIONS.MODEL_PREP]): standfirst = ( '<p>Model analysis and search model preparation was carried out with the following programs:</p>' ) html += self._methods_section_html(self.SECTIONS.MODEL_PREP, standfirst) elif section == self.SECTIONS.MR and len(self.section_labels[self.SECTIONS.MR]): standfirst = '<p>Molecular Replacement was carried out with the following programs:</p>' html += self._methods_section_html(self.SECTIONS.MR, standfirst) elif section == self.SECTIONS.REFINEMENT and len(self.section_labels[self.SECTIONS.REFINEMENT]): standfirst = '<pRefinement of the MR solutions carried out with the following programs:</p>' html += self._methods_section_html(self.SECTIONS.REFINEMENT, standfirst) elif section == self.SECTIONS.DM and len(self.section_labels[self.SECTIONS.DM]): standfirst = ( '<p>Density modification and main-chain tracing was carried out with the following programs:</p>' ) html += self._methods_section_html(self.SECTIONS.DM, standfirst) elif section == self.SECTIONS.AUTOBUILD and len(self.section_labels[self.SECTIONS.AUTOBUILD]): standfirst = 'Autobuilding of the final structure was carried out with the following programs:</p>' html += self._methods_section_html(self.SECTIONS.AUTOBUILD, standfirst) return html def _methods_section_html(self, section, standfirst): mysec = self.SECTIONS(section) html = '<{}>{}</{}>'.format(self.SEC_TAG, mysec.value, self.SEC_TAG) html += standfirst html += '<ul>' for label in self.section_labels[mysec]: html += "<li>{}<sup>{}</sup></li>".format(label, self.ordered_labels.index(label) + 1) html += "</ul>" return html @property def citations_as_html(self): html = '<{}>References</{}>'.format(self.SEC_TAG, self.SEC_TAG) html += '<ol>' template_txt = "<li> {author} ({year}). {title}. {journal} {volume}({number}), {pages}. [doi:{doi}]</li>" for label in self.ordered_labels: ref = copy.copy(self.references[label]) ref['author'] = ref['author'].split(" and ")[0].split(",")[0] + " et al." ref['pages'] = ref['pages'].replace("--", "-") html += template_txt.format(**ref) html += '</ol>' return html @property def citations_as_text(self): txt = """A number of programs and algorithms were used within the this run of AMPLE. The following is a list of citations for this run: {0} """.format( self.citation_list_as_text ) if self.citation_file_path: txt += """ A bibtex file with these references has been saved to the following file: {0} """.format( self.citation_file_path ) return txt @property def citation_list_as_text(self): template_txt = "* {author} ({year}). {title}. {journal} {volume}({number}), {pages}. [doi:{doi}]" text = "" for label in self.ordered_labels: ref = copy.copy(self.references[label]) ref['author'] = ref['author'].split(" and ")[0].split(",")[0] + " et al." ref['pages'] = ref['pages'].replace("--", "-") text += template_txt.format(**ref) + os.linesep * 2 return text def save_citations_to_file(self, optd): # ========================================================================= # Somewhat a template of how we want to write each article in BibTex format # ========================================================================= template_bib = ( "@article{{{unique_id},{sep}author = {{{author}}},{sep}doi = {{{doi}}},{sep}" "journal = {{{journal}}},{sep}number = {{{number}}},{sep}pages = {{{pages}}},{sep}" "title = {{{{{title}}}}},{sep}volume = {{{volume}}},{sep}year = {{{year}}},{sep}}}{sep}" ) references_bib = [template_bib.format(sep=os.linesep, **self.references[l]) for l in self.ordered_labels] ref_fname = os.path.join(optd['work_dir'], optd['name'] + ".bib") with open(ref_fname, "w") as fhout: fhout.write(os.linesep.join(references_bib)) self.citation_file_path = ref_fname return ref_fname # ====================================================================== # Some default string messages that we need during the program to inform # the user of certain information # ====================================================================== header = """ ######################################################################### ######################################################################### ######################################################################### # CCP4: AMPLE - Ab Initio Modelling Molecular Replacement # ######################################################################### """ # ====================================================================== # ====================================================================== survey_url = "http://goo.gl/forms/7xP9M4P81O" footer = """ ######################################################################### #***********************************************************************# #* How did we do? *# #* *# #* Please follow this link and leave some feedback! *# #* *# #* {url} *# #***********************************************************************# ######################################################################### """.format( url=survey_url ) # ====================================================================== # ======================================================================
en
0.454993
Various miscellaneous functions # Section Names # Beginning of all BibTex entry blocks # Reset the article dictionary # End of all BibTex entry blocks # BibTex entry block # Some dirty line handling. # Not very bulletproof but should do for now # Save the data to the article entry # Create default lists # Build up list of program reference labels, ordered by sections # Generate ordered list of all relevant reference labels A number of programs and algorithms were used within the this run of AMPLE. The following is a list of citations for this run: {0} A bibtex file with these references has been saved to the following file: {0} # ========================================================================= # Somewhat a template of how we want to write each article in BibTex format # ========================================================================= # ====================================================================== # Some default string messages that we need during the program to inform # the user of certain information # ====================================================================== ######################################################################### ######################################################################### ######################################################################### # CCP4: AMPLE - Ab Initio Modelling Molecular Replacement # ######################################################################### # ====================================================================== # ====================================================================== ######################################################################### #***********************************************************************# #* How did we do? *# #* *# #* Please follow this link and leave some feedback! *# #* *# #* {url} *# #***********************************************************************# ######################################################################### # ====================================================================== # ======================================================================
2.307497
2
default.py
cursedzz/Movies
0
6613676
<filename>default.py<gh_stars>0 import xbmcaddon,os,requests,xbmc,xbmcgui,urllib,urllib2,re,xbmcplugin def CATEGORIES(): addDir3('Live Tv','http://cursedzz.noads.biz/channels.txt',3,'http://original.livestream.com/filestore/logos/6a941358-6c7f-2ebf-e8ac-b05f4f338270-banner.png','','') addDir3('Movies','http://cursedzz.noads.biz/movies.txt',4,'https://www.offerpop.com/wp-content/uploads/2014/08/Movies.jpg','','') def channel(): r = requests.get('http://cursedzz.noads.biz/channels.txt') match = re.compile('name= (.+?) url= "(.+?)" logo= "(.+?)"').findall(r.content) for name,link, logo in match: addLink(name,link,logo,'','') def Moviess(): r = requests.get('http://cursedzz.noads.biz/movies.txt') match = re.compile('name= (.+?) url= "(.+?)" logo= "(.+?)"').findall(r.content) for name,link, logo in match: addLink(name,link,logo,'','') def addLink(name,url,image,urlType,fanart): ok=True liz=xbmcgui.ListItem(name, iconImage=image, thumbnailImage=image) liz.setInfo( type="Video", infoLabels={ "Title": name } ) liz.setProperty('IsPlayable','true') liz.setProperty('fanart_image', fanart) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz) def get_params(): param=[] paramstring=sys.argv[2] if len(paramstring)>=2: params=sys.argv[2] cleanedparams=params.replace('?','') if (params[len(params)-1]=='/'): params=params[0:len(params)-2] pairsofparams=cleanedparams.split('&') param={} for i in range(len(pairsofparams)): splitparams={} splitparams=pairsofparams[i].split('=') if (len(splitparams))==2: param[splitparams[0]]=splitparams[1] return param ################################################################################################################# # NEED BELOW CHANGED def addDir(name,url,mode,iconimage): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True) return ok def addDir2(name,url,mode,iconimage): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False) return ok ############################################################################################################### def addDir3(name,url,mode,iconimage,fanart,description): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&fanart="+urllib.quote_plus(fanart)+"&description="+urllib.quote_plus(description) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description } ) liz.setProperty( "Fanart_Image", fanart ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True) return ok def setView(content, viewType): # set content type so library shows more views and info if content: xbmcplugin.setContent(int(sys.argv[1]), content) if ADDON.getSetting('auto-view')=='true': xbmc.executebuiltin("Container.SetViewMode(%s)" % viewType ) params=get_params() url=None name=None mode=None iconimage=None fanart=None description=None try: url=urllib.unquote_plus(params["url"]) except: pass try: name=urllib.unquote_plus(params["name"]) except: pass try: iconimage=urllib.unquote_plus(params["iconimage"]) except: pass try: mode=int(params["mode"]) except: pass try: fanart=urllib.unquote_plus(params["fanart"]) except: pass try: description=urllib.unquote_plus(params["description"]) except: pass print "Mode: "+str(mode) print "URL: "+str(url) print "Name: "+str(name) if mode==None or url==None or len(url)<1: print "" CATEGORIES() elif mode==1: OPEN_URL(url) elif mode==3: channel() elif mode==4: Moviess() xbmcplugin.endOfDirectory(int(sys.argv[1]))
<filename>default.py<gh_stars>0 import xbmcaddon,os,requests,xbmc,xbmcgui,urllib,urllib2,re,xbmcplugin def CATEGORIES(): addDir3('Live Tv','http://cursedzz.noads.biz/channels.txt',3,'http://original.livestream.com/filestore/logos/6a941358-6c7f-2ebf-e8ac-b05f4f338270-banner.png','','') addDir3('Movies','http://cursedzz.noads.biz/movies.txt',4,'https://www.offerpop.com/wp-content/uploads/2014/08/Movies.jpg','','') def channel(): r = requests.get('http://cursedzz.noads.biz/channels.txt') match = re.compile('name= (.+?) url= "(.+?)" logo= "(.+?)"').findall(r.content) for name,link, logo in match: addLink(name,link,logo,'','') def Moviess(): r = requests.get('http://cursedzz.noads.biz/movies.txt') match = re.compile('name= (.+?) url= "(.+?)" logo= "(.+?)"').findall(r.content) for name,link, logo in match: addLink(name,link,logo,'','') def addLink(name,url,image,urlType,fanart): ok=True liz=xbmcgui.ListItem(name, iconImage=image, thumbnailImage=image) liz.setInfo( type="Video", infoLabels={ "Title": name } ) liz.setProperty('IsPlayable','true') liz.setProperty('fanart_image', fanart) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz) def get_params(): param=[] paramstring=sys.argv[2] if len(paramstring)>=2: params=sys.argv[2] cleanedparams=params.replace('?','') if (params[len(params)-1]=='/'): params=params[0:len(params)-2] pairsofparams=cleanedparams.split('&') param={} for i in range(len(pairsofparams)): splitparams={} splitparams=pairsofparams[i].split('=') if (len(splitparams))==2: param[splitparams[0]]=splitparams[1] return param ################################################################################################################# # NEED BELOW CHANGED def addDir(name,url,mode,iconimage): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True) return ok def addDir2(name,url,mode,iconimage): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name } ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False) return ok ############################################################################################################### def addDir3(name,url,mode,iconimage,fanart,description): u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&fanart="+urllib.quote_plus(fanart)+"&description="+urllib.quote_plus(description) ok=True liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage) liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description } ) liz.setProperty( "Fanart_Image", fanart ) ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True) return ok def setView(content, viewType): # set content type so library shows more views and info if content: xbmcplugin.setContent(int(sys.argv[1]), content) if ADDON.getSetting('auto-view')=='true': xbmc.executebuiltin("Container.SetViewMode(%s)" % viewType ) params=get_params() url=None name=None mode=None iconimage=None fanart=None description=None try: url=urllib.unquote_plus(params["url"]) except: pass try: name=urllib.unquote_plus(params["name"]) except: pass try: iconimage=urllib.unquote_plus(params["iconimage"]) except: pass try: mode=int(params["mode"]) except: pass try: fanart=urllib.unquote_plus(params["fanart"]) except: pass try: description=urllib.unquote_plus(params["description"]) except: pass print "Mode: "+str(mode) print "URL: "+str(url) print "Name: "+str(name) if mode==None or url==None or len(url)<1: print "" CATEGORIES() elif mode==1: OPEN_URL(url) elif mode==3: channel() elif mode==4: Moviess() xbmcplugin.endOfDirectory(int(sys.argv[1]))
de
0.733191
################################################################################################################# # NEED BELOW CHANGED ############################################################################################################### # set content type so library shows more views and info
2.390607
2
CustomWidgets/CCountUp.py
PythonDesktopApps/PyQtCustomWidgets
0
6613677
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2019年7月31日 @author: Irony @site: https://pyqt5.com https://github.com/892768447 @email: <EMAIL> @file: CustomWidgets.CCountUp @description: Digital animation """ from PyQt5.QtCore import QTimeLine, QEasingCurve from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QLabel __Author__ = 'Irony' __Copyright__ = 'Copyright (c) 2019 Irony' __Version__ = 1.0 class CCountUp(QLabel): def __init__(self, *args, **kwargs): super(CCountUp, self).__init__(*args, **kwargs) self.isFloat = False # Is it a decimal? font = self.font() or QFont() font.setBold(True) self.setFont(font) self.timeline = QTimeLine(6000, self) self.timeline.setEasingCurve(QEasingCurve.OutExpo) self.timeline.frameChanged.connect(self.onFrameChanged) def pause(self): """pause """ self.timeline.setPaused(True) def resume(self): """continue """ self.timeline.resume() def isPaused(self): """Will it be paused? """ return self.timeline.state() == QTimeLine.Paused def reset(self): """Reset """ self.timeline.stop() self.isFloat = False # Is it a decimal? self.setText('0') def onFrameChanged(self, value): if self.isFloat: value = round(value / 100.0 + 0.00001, 2) value = str(format(value, ',')) self.setText(value + '0' if value.endswith('.0') else value) def setDuration(self, duration): """Set up animation duration :param duration: """ self.timeline.setDuration(duration) def setNum(self, number): """Set numbers :param number: int or float """ if isinstance(number, int): self.isFloat = False self.timeline.setFrameRange(0, number) elif isinstance(number, float): self.isFloat = True self.timeline.setFrameRange(0, number * 100) self.timeline.stop() self.setText('0') self.timeline.start()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 2019年7月31日 @author: Irony @site: https://pyqt5.com https://github.com/892768447 @email: <EMAIL> @file: CustomWidgets.CCountUp @description: Digital animation """ from PyQt5.QtCore import QTimeLine, QEasingCurve from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QLabel __Author__ = 'Irony' __Copyright__ = 'Copyright (c) 2019 Irony' __Version__ = 1.0 class CCountUp(QLabel): def __init__(self, *args, **kwargs): super(CCountUp, self).__init__(*args, **kwargs) self.isFloat = False # Is it a decimal? font = self.font() or QFont() font.setBold(True) self.setFont(font) self.timeline = QTimeLine(6000, self) self.timeline.setEasingCurve(QEasingCurve.OutExpo) self.timeline.frameChanged.connect(self.onFrameChanged) def pause(self): """pause """ self.timeline.setPaused(True) def resume(self): """continue """ self.timeline.resume() def isPaused(self): """Will it be paused? """ return self.timeline.state() == QTimeLine.Paused def reset(self): """Reset """ self.timeline.stop() self.isFloat = False # Is it a decimal? self.setText('0') def onFrameChanged(self, value): if self.isFloat: value = round(value / 100.0 + 0.00001, 2) value = str(format(value, ',')) self.setText(value + '0' if value.endswith('.0') else value) def setDuration(self, duration): """Set up animation duration :param duration: """ self.timeline.setDuration(duration) def setNum(self, number): """Set numbers :param number: int or float """ if isinstance(number, int): self.isFloat = False self.timeline.setFrameRange(0, number) elif isinstance(number, float): self.isFloat = True self.timeline.setFrameRange(0, number * 100) self.timeline.stop() self.setText('0') self.timeline.start()
en
0.395234
#!/usr/bin/env python # -*- coding: utf-8 -*- Created on 2019年7月31日 @author: Irony @site: https://pyqt5.com https://github.com/892768447 @email: <EMAIL> @file: CustomWidgets.CCountUp @description: Digital animation # Is it a decimal? pause continue Will it be paused? Reset # Is it a decimal? Set up animation duration :param duration: Set numbers :param number: int or float
2.998317
3
app/code.py
martinlindholdt/dj-service
0
6613678
<gh_stars>0 import os, sys, random from bottle.bottle import route, run, template from time import sleep rndwait = False def setWait(): if rndwait: return random.randint(0, 5) else: return 0 @route('/hello/<name>') def index(name): return template('<b>Hello, {{name}}!</b>', name=name) @route('/') def index(): waittime = setWait() sleep(waittime) host = os.getenv('HOSTNAME', 'unknown host') version = os.getenv('VERSION', 'unknown version') return template('{{host}} running {{version}} waiting {{wait}} seconds', host=host, version= version, wait=waittime) @route('/random/<state>') def doRandom(state): global rndwait if state == "on" or state == "true": rndwait = True else: rndwait = False return template('Random repsonsetime 0-5 seconds now {{rndwait}}</b>', rndwait=rndwait) @route('/crash') def crachApp(): sys.stderr.close() # rather ugly hack but there are no exit function return "<h1>Goodbye cruel world...</h2>" @route('/health') def alive(): return "true" run(host='0.0.0.0', port=8080, reloader=True)
import os, sys, random from bottle.bottle import route, run, template from time import sleep rndwait = False def setWait(): if rndwait: return random.randint(0, 5) else: return 0 @route('/hello/<name>') def index(name): return template('<b>Hello, {{name}}!</b>', name=name) @route('/') def index(): waittime = setWait() sleep(waittime) host = os.getenv('HOSTNAME', 'unknown host') version = os.getenv('VERSION', 'unknown version') return template('{{host}} running {{version}} waiting {{wait}} seconds', host=host, version= version, wait=waittime) @route('/random/<state>') def doRandom(state): global rndwait if state == "on" or state == "true": rndwait = True else: rndwait = False return template('Random repsonsetime 0-5 seconds now {{rndwait}}</b>', rndwait=rndwait) @route('/crash') def crachApp(): sys.stderr.close() # rather ugly hack but there are no exit function return "<h1>Goodbye cruel world...</h2>" @route('/health') def alive(): return "true" run(host='0.0.0.0', port=8080, reloader=True)
en
0.889674
# rather ugly hack but there are no exit function
2.167588
2
utility.py
FaiZaman/Steganograph-app-y
0
6613679
""" Utility functions """ import os import cv2 import numpy as np from unidecode import unidecode # convert any message to a binary string def message_to_binary(message): ascii_message = unidecode(message) binary_message = ''.join(format(ord(char), '08b') for char in ascii_message) return binary_message # convert any integer into 8-bit binary value def integer_to_binary(integer): binary_value = format(integer, "08b") return binary_value # convert a binary string into a UTF-8 string message def binary_to_string(binary_message, delimiter): delimiter_length = len(delimiter) * -1 delimiter_present = False # split into bytes message_bytes = [binary_message[i : i + 8] for i in range(0, len(binary_message), 8)] message = "" # convert each byte and append to message for byte in message_bytes: char = chr(int(byte, 2)) message += char if message[delimiter_length:] == delimiter: # reached the delimiter message = message[:delimiter_length] delimiter_present = True break return message, delimiter_present def is_message_complete(binary_message, delimiter): # split into bytes message_bytes = [binary_message[i : i + 8] for i in range(0, len(binary_message), 8)] message = "" # convert each byte and append to message for byte in message_bytes: char = chr(int(byte, 2)) message += char # if delimiter is in message then it is complete if delimiter in message: return True return False # set all the LSBs to zero before detecting edges so same edges are detected in embedding and extraction def mask_LSB(image): # uses binary 11111100 to AND all pixels in image to reset 2 LSBs to 0 mask = np.full(image.shape, 252, np.uint8) masked_image = cv2.bitwise_and(image, mask) return masked_image def save_image(save_path, image_name, time_string, stego): #cv2.imwrite(os.path.join(save_path, image_name), stego) saved_image = cv2.imwrite(os.path.join(save_path, '{0}_{1}'.format(time_string, image_name)), stego) return saved_image def save_message(save_path, time_string, message): file_path = os.path.join(save_path, "{0}.txt".format(time_string)) message_file = open(file_path, "w") try: message_file.write(message) message_file.close() return True except UnicodeEncodeError: message_file.close() os.remove(file_path) return False
""" Utility functions """ import os import cv2 import numpy as np from unidecode import unidecode # convert any message to a binary string def message_to_binary(message): ascii_message = unidecode(message) binary_message = ''.join(format(ord(char), '08b') for char in ascii_message) return binary_message # convert any integer into 8-bit binary value def integer_to_binary(integer): binary_value = format(integer, "08b") return binary_value # convert a binary string into a UTF-8 string message def binary_to_string(binary_message, delimiter): delimiter_length = len(delimiter) * -1 delimiter_present = False # split into bytes message_bytes = [binary_message[i : i + 8] for i in range(0, len(binary_message), 8)] message = "" # convert each byte and append to message for byte in message_bytes: char = chr(int(byte, 2)) message += char if message[delimiter_length:] == delimiter: # reached the delimiter message = message[:delimiter_length] delimiter_present = True break return message, delimiter_present def is_message_complete(binary_message, delimiter): # split into bytes message_bytes = [binary_message[i : i + 8] for i in range(0, len(binary_message), 8)] message = "" # convert each byte and append to message for byte in message_bytes: char = chr(int(byte, 2)) message += char # if delimiter is in message then it is complete if delimiter in message: return True return False # set all the LSBs to zero before detecting edges so same edges are detected in embedding and extraction def mask_LSB(image): # uses binary 11111100 to AND all pixels in image to reset 2 LSBs to 0 mask = np.full(image.shape, 252, np.uint8) masked_image = cv2.bitwise_and(image, mask) return masked_image def save_image(save_path, image_name, time_string, stego): #cv2.imwrite(os.path.join(save_path, image_name), stego) saved_image = cv2.imwrite(os.path.join(save_path, '{0}_{1}'.format(time_string, image_name)), stego) return saved_image def save_message(save_path, time_string, message): file_path = os.path.join(save_path, "{0}.txt".format(time_string)) message_file = open(file_path, "w") try: message_file.write(message) message_file.close() return True except UnicodeEncodeError: message_file.close() os.remove(file_path) return False
en
0.689055
Utility functions # convert any message to a binary string # convert any integer into 8-bit binary value # convert a binary string into a UTF-8 string message # split into bytes # convert each byte and append to message # reached the delimiter # split into bytes # convert each byte and append to message # if delimiter is in message then it is complete # set all the LSBs to zero before detecting edges so same edges are detected in embedding and extraction # uses binary 11111100 to AND all pixels in image to reset 2 LSBs to 0 #cv2.imwrite(os.path.join(save_path, image_name), stego)
3.242614
3
huaweicloud-sdk-cpts/huaweicloudsdkcpts/v1/model/reportdetails_info.py
huaweicloud/huaweicloud-sdk-python-v3
64
6613680
# coding: utf-8 import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class ReportdetailsInfo: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'data': 'list[ReportdetailItemInfo]', 'page_index': 'int', 'page_size': 'int', 'total': 'int' } attribute_map = { 'data': 'data', 'page_index': 'pageIndex', 'page_size': 'pageSize', 'total': 'total' } def __init__(self, data=None, page_index=None, page_size=None, total=None): """ReportdetailsInfo - a model defined in huaweicloud sdk""" self._data = None self._page_index = None self._page_size = None self._total = None self.discriminator = None if data is not None: self.data = data if page_index is not None: self.page_index = page_index if page_size is not None: self.page_size = page_size if total is not None: self.total = total @property def data(self): """Gets the data of this ReportdetailsInfo. data :return: The data of this ReportdetailsInfo. :rtype: list[ReportdetailItemInfo] """ return self._data @data.setter def data(self, data): """Sets the data of this ReportdetailsInfo. data :param data: The data of this ReportdetailsInfo. :type: list[ReportdetailItemInfo] """ self._data = data @property def page_index(self): """Gets the page_index of this ReportdetailsInfo. pageIndex :return: The page_index of this ReportdetailsInfo. :rtype: int """ return self._page_index @page_index.setter def page_index(self, page_index): """Sets the page_index of this ReportdetailsInfo. pageIndex :param page_index: The page_index of this ReportdetailsInfo. :type: int """ self._page_index = page_index @property def page_size(self): """Gets the page_size of this ReportdetailsInfo. pageSize :return: The page_size of this ReportdetailsInfo. :rtype: int """ return self._page_size @page_size.setter def page_size(self, page_size): """Sets the page_size of this ReportdetailsInfo. pageSize :param page_size: The page_size of this ReportdetailsInfo. :type: int """ self._page_size = page_size @property def total(self): """Gets the total of this ReportdetailsInfo. total :return: The total of this ReportdetailsInfo. :rtype: int """ return self._total @total.setter def total(self, total): """Sets the total of this ReportdetailsInfo. total :param total: The total of this ReportdetailsInfo. :type: int """ self._total = total def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ReportdetailsInfo): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
# coding: utf-8 import re import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class ReportdetailsInfo: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'data': 'list[ReportdetailItemInfo]', 'page_index': 'int', 'page_size': 'int', 'total': 'int' } attribute_map = { 'data': 'data', 'page_index': 'pageIndex', 'page_size': 'pageSize', 'total': 'total' } def __init__(self, data=None, page_index=None, page_size=None, total=None): """ReportdetailsInfo - a model defined in huaweicloud sdk""" self._data = None self._page_index = None self._page_size = None self._total = None self.discriminator = None if data is not None: self.data = data if page_index is not None: self.page_index = page_index if page_size is not None: self.page_size = page_size if total is not None: self.total = total @property def data(self): """Gets the data of this ReportdetailsInfo. data :return: The data of this ReportdetailsInfo. :rtype: list[ReportdetailItemInfo] """ return self._data @data.setter def data(self, data): """Sets the data of this ReportdetailsInfo. data :param data: The data of this ReportdetailsInfo. :type: list[ReportdetailItemInfo] """ self._data = data @property def page_index(self): """Gets the page_index of this ReportdetailsInfo. pageIndex :return: The page_index of this ReportdetailsInfo. :rtype: int """ return self._page_index @page_index.setter def page_index(self, page_index): """Sets the page_index of this ReportdetailsInfo. pageIndex :param page_index: The page_index of this ReportdetailsInfo. :type: int """ self._page_index = page_index @property def page_size(self): """Gets the page_size of this ReportdetailsInfo. pageSize :return: The page_size of this ReportdetailsInfo. :rtype: int """ return self._page_size @page_size.setter def page_size(self, page_size): """Sets the page_size of this ReportdetailsInfo. pageSize :param page_size: The page_size of this ReportdetailsInfo. :type: int """ self._page_size = page_size @property def total(self): """Gets the total of this ReportdetailsInfo. total :return: The total of this ReportdetailsInfo. :rtype: int """ return self._total @total.setter def total(self, total): """Sets the total of this ReportdetailsInfo. total :param total: The total of this ReportdetailsInfo. :type: int """ self._total = total def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ReportdetailsInfo): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
en
0.568668
# coding: utf-8 Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. ReportdetailsInfo - a model defined in huaweicloud sdk Gets the data of this ReportdetailsInfo. data :return: The data of this ReportdetailsInfo. :rtype: list[ReportdetailItemInfo] Sets the data of this ReportdetailsInfo. data :param data: The data of this ReportdetailsInfo. :type: list[ReportdetailItemInfo] Gets the page_index of this ReportdetailsInfo. pageIndex :return: The page_index of this ReportdetailsInfo. :rtype: int Sets the page_index of this ReportdetailsInfo. pageIndex :param page_index: The page_index of this ReportdetailsInfo. :type: int Gets the page_size of this ReportdetailsInfo. pageSize :return: The page_size of this ReportdetailsInfo. :rtype: int Sets the page_size of this ReportdetailsInfo. pageSize :param page_size: The page_size of this ReportdetailsInfo. :type: int Gets the total of this ReportdetailsInfo. total :return: The total of this ReportdetailsInfo. :rtype: int Sets the total of this ReportdetailsInfo. total :param total: The total of this ReportdetailsInfo. :type: int Returns the model properties as a dict Returns the string representation of the model For `print` Returns true if both objects are equal Returns true if both objects are not equal
2.488631
2
lakegallery/map/migrations/0001_initial.py
TNRIS/lake-gallery
3
6613681
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-12 19:32 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MajorReservoirs', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('res_name', models.CharField(max_length=50)), ('type', models.CharField(max_length=50)), ('status', models.CharField(max_length=50)), ('res_lbl', models.CharField(max_length=100)), ('region', models.CharField(max_length=50)), ('geom', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)), ], ), migrations.CreateModel( name='RWPAs', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('objectid', models.BigIntegerField()), ('reg_name', models.CharField(max_length=25)), ('letter', models.CharField(max_length=1)), ('shape_leng', models.FloatField()), ('shape_area', models.FloatField()), ('geom', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)), ], ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-12 19:32 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MajorReservoirs', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('res_name', models.CharField(max_length=50)), ('type', models.CharField(max_length=50)), ('status', models.CharField(max_length=50)), ('res_lbl', models.CharField(max_length=100)), ('region', models.CharField(max_length=50)), ('geom', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)), ], ), migrations.CreateModel( name='RWPAs', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('objectid', models.BigIntegerField()), ('reg_name', models.CharField(max_length=25)), ('letter', models.CharField(max_length=1)), ('shape_leng', models.FloatField()), ('shape_area', models.FloatField()), ('geom', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)), ], ), ]
en
0.765513
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-12 19:32
1.654024
2
setup.py
RonenNess/grepfunc
8
6613682
from distutils.core import setup setup( name='grepfunc', packages=['grepfunc'], package_data={'grepfunc' : ["*.py", "README.md"], }, version='1.0.3', description='Unix\'s grep, implemented as a Python function.', author='<NAME>', author_email='<EMAIL>', url='https://github.com/RonenNess/grepfunc', download_url='https://github.com/RonenNess/grepfunc/tarball/1.0.3', keywords=['grep', 'regex', 'filter', 'search', 'strings'], classifiers=[], )
from distutils.core import setup setup( name='grepfunc', packages=['grepfunc'], package_data={'grepfunc' : ["*.py", "README.md"], }, version='1.0.3', description='Unix\'s grep, implemented as a Python function.', author='<NAME>', author_email='<EMAIL>', url='https://github.com/RonenNess/grepfunc', download_url='https://github.com/RonenNess/grepfunc/tarball/1.0.3', keywords=['grep', 'regex', 'filter', 'search', 'strings'], classifiers=[], )
none
1
1.240308
1
utils.py
afshinrahimi/mmner
74
6613683
<filename>utils.py from io import open import logging import pdb import random import os import numpy as np import shutil from collections import Counter import tarfile import json import random from collections import defaultdict import io import gzip import sys import argparse np.random.seed(7) random.seed(7) logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) def check_num_records(filename): records = 0 with open(filename, 'r', encoding='utf-8') as fin: for line in fin: if line.strip() == '': records += 1 logging.info('{} records in {}'.format(records, filename)) return records def check_num_records_by_content(filehandle, filename): records = 0 for line in filehandle: line = line.decode('utf-8') if line.strip() == '': records += 1 logging.info('{} records in {}'.format(records, filename)) return records def extract_records(input_file, output_file, num_records): records = 0 all_records = [] with open(input_file, 'r', encoding='utf-8') as fin: record = [] for line in fin: line = line.strip() if 'docstart' in line.lower(): continue if line == '' and len(record) > 0: all_records.append(record) record = [] elif line != '': record.append(line) all_records.append(record) selected_records = all_records[0:num_records] with open(output_file, 'w', encoding='utf-8') as fout: for i, record in enumerate(selected_records): for r in record: fout.write(r + '\n') fout.write('\n') def create_train_dev_test_from_one_file(conll_file, lang, output_dir): records = 0 all_records = [] with open(conll_file, 'r', encoding='utf-8') as fin: record = [] for line in fin: line = line.strip() if 'docstart' in line.lower(): continue if line == '' and len(record) > 0: all_records.append(record) record = [] elif line != '': fields = line.split() if len(fields) > 1: line = fields[0] + '\t' + fields[-1] record.append(line) if len(record) > 0: all_records.append(record) logging.info('{} sentences for {} detected.'.format(len(all_records), lang)) train_100 = all_records[0:100] train_1000 = all_records[0:1000] train_10000 = all_records[0:10000] test_count = dev_count = min(len(all_records) - 10000 // 2, 10000) dev = all_records[10000:10000 + dev_count] test = all_records[10000 + dev_count: 10000 + dev_count + test_count] train_100_file = os.path.join(output_dir, '{}.train.{}'.format(lang, 100)) train_1000_file = os.path.join(output_dir, '{}.train.{}'.format(lang, 1000)) train_10000_file = os.path.join(output_dir, '{}.train.{}'.format(lang, 10000)) dev_file = os.path.join(output_dir, '{}.dev'.format(lang)) test_file = os.path.join(output_dir, '{}.test'.format(lang)) file_records = [(train_100, train_100_file), (train_1000, train_1000_file), (train_10000, train_10000_file), (dev, dev_file), (test, test_file)] for file_record in file_records: with open(file_record[1], 'w', encoding='utf-8') as fout: for i, record in enumerate(file_record[0]): for r in record: fout.write(r + '\n') fout.write('\n') logging.info('created train dev test splits for {} in {}'.format(lang, output_dir)) def add_lang_to_each_word(dir_name, name_index, lang_separator=':', embfile=None): if embfile: files = [embfile] else: files = [f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f))] for file in files: if not embfile: if file[-5:] == 'multi' or 'cca-59' in str(file): continue lang = file.split('.')[name_index] print('lang:{}'.format(lang)) filename = os.path.join(dir_name, file) lines = [] with open(filename, 'r', encoding='utf-8') as fin: for line in fin: if line.strip() != '': line = lang + lang_separator + line lines.append(line) with open(filename + '.multi', 'w', encoding='utf-8') as fout: for line in lines: fout.write(line) def create_ner_training_datasets(): for lang in ['de', 'en', 'nl']: for i in [100, 1000, 10000]: extract_records(input_file='./datasets/ner/{}.train'.format(lang), output_file='./datasets/ner/{}.train.{}'.format(lang, i), num_records=i) check_num_records('./datasets/ner/{}.train.{}'.format(lang, i)) def collect_vocab_and_tags(dir_name, fname=None): ''' :param dir_name: :return set of all the vocab (+$UNK$ and +$NUM$ in all the files in the directory (expect all the files to be in conll2003 format): ''' tags = set() vocab = set() chars = set() files = [f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f))] if not fname else [os.path.join(dir_name, fname)] for file in files: #we just want the files where language id is added to the beginning of the words if file[-5:] != 'multi': continue filename = os.path.join(dir_name, file) with open(filename, 'r', encoding='utf-8') as fin: for line in fin: if line.strip() != '' and 'docstart' not in line.lower(): fields = line.split() if len(fields) > 1: word, tag = fields[0], fields[-1] else: logging.info('warning: error in line {} in file {}'.format(line, filename)) vocab.add(word.lower()) tags.add(tag) chars.update(word) return vocab, tags, chars def collect_vocab_and_tags_panx(panx_dir_name, fname=None): ''' :param dir_name: contains tar.gz files each with train test dev conll files :return set of all the vocab (+$UNK$ and +$NUM$ in all the files in the directory (expect all the files to be in conll2003 format): important note: all vocab in wikiembs :https://fasttext.cc/docs/en/pretrained-vectors.html are lowercase while words in wikiemb+crawlemb: https://fasttext.cc/docs/en/crawl-vectors.html have upper case words so it will make a huge difference in terms of OOVs and how we match words in NER datasets to words in the pre-trained word embeddings. ''' tags = set() vocab = set() chars = set() files = [f for f in os.listdir(panx_dir_name) if os.path.isfile(os.path.join(panx_dir_name, f))] if not fname else [fname] for file in files: targz_file = os.path.join(panx_dir_name, file) tar = tarfile.open(targz_file, "r:gz") for member in tar.getmembers(): #don't collect the vocabulary of extra annotated data if member.name == 'extra': continue bio_file = tar.extractfile(member) for line in bio_file: line = line.decode('utf-8') if line.strip() != '' and 'docstart' not in line.lower(): fields = line.split() if len(fields) > 1: word, tag = fields[0], fields[-1] else: logging.info('warning: error in line {} in file {}'.format(line, targz_file)) vocab.add(word) tags.add(tag) chars.update(word) tar.close() return vocab, tags, chars def collect_embedding_vocabs(dir_name, embfile=None): ''' :param dir_name: directory where all the word embeddings with different languages are located expected that lang id- (e.g. en-) is added to the beginning of each word so that exact words in different languages are distinguishable :return: set of vocab ''' vocab_emb = set() filename = os.path.join(dir_name, emb_file) with gzip.open(filename, 'rt', encoding='utf-8') if 'gz' in embfile else open(filename, 'r', encoding='utf-8') as fin: for line in fin: if line.strip() != '': word = line.split(' ')[0] vocab_emb.add(word) vocab_lang_distribution = [v.split(':')[0] for v in vocab_emb] vocab_lang_distribution = Counter(vocab_lang_distribution) logging.info('embedding file vocab stats: {}'.format(str(vocab_lang_distribution))) return vocab_emb def write_list(items, output_file): with open(output_file, 'w', encoding='utf-8') as fout: for i, item in enumerate(sorted(items)): if i != len(items) - 1: fout.write('{}\n'.format(item)) else: fout.write(item) def read_list(filename): items = [] with open(filename, 'r', encoding='utf-8') as fin: for item in fin: items.append(item.strip()) return items def write_vocab_tags_chars_embs(vocab_ner, tags, chars, vocab_emb, output_dir): write_list(tags, os.path.join(output_dir, 'tags.txt')) write_list(chars, os.path.join(output_dir, 'chars.txt')) ''' now we should add any vocab that might have uppercase in vocab_ner but is lowercase in vocab_emmb. note that lowercase=True should be turned to lowercase=False in mconfig file to reflect this. question: what about the cases when a lower case word is in NER but an uppercase is in emb? ''' vocab = vocab_ner & vocab_emb for v in vocab_ner: vlow = v.lower() if v == vlow: continue if v not in vocab_emb and vlow in vocab_emb: vocab.add(vlow) vocab_lang_distribution = [v.split(':')[0] for v in vocab] vocab_lang_distribution = Counter(vocab_lang_distribution) logging.info(vocab_lang_distribution) with open(os.path.join(output_dir, 'stats'), 'w') as fout: fout.write(str(vocab_lang_distribution)) vocab.add('$UNK$') vocab.add('$NUM$') write_list(vocab, os.path.join(output_dir, 'words.txt')) def build_vocab(conll_dir, emb_dir, output_dir, emb_file=None, panx=False, fname=None): if panx: vocab, tags, chars = collect_vocab_and_tags_panx(conll_dir, fname=fname) else: vocab, tags, chars = collect_vocab_and_tags(conll_dir) vocab_emb = collect_embedding_vocabs(emb_dir, emb_file) write_vocab_tags_chars_embs(vocab, tags, chars, vocab_emb, output_dir) return vocab, tags, chars def trim_embs(emb_dir, vocab_file, output_dir, dim, emb_file=None): vocab = read_list(vocab_file) vocabset = set(vocab) vocab_emb = set() embeddings = np.zeros([len(vocab), dim]) filename = os.path.join(emb_dir, emb_file) with gzip.open(filename, 'rt', encoding='utf-8') if 'gz' in emb_file else open(filename, 'r', encoding='utf-8') as fin: for line in fin: line = line.strip().split(' ') word = line[0] if word not in vocabset: continue embedding = [float(x) for x in line[1:]] word_idx = vocab.index(word) embeddings[word_idx] = np.asarray(embedding) np.savez_compressed(os.path.join(output_dir, 'trimmed_embs.npz'), embeddings=embeddings) def data_to_byteio(records, name): data = '' for i, record in enumerate(records): for r in record: data += r + '\n' data += '\n' encoded_data = data.encode('utf8') data_byteio = io.BytesIO(encoded_data) tarinfo = tarfile.TarInfo(name) tarinfo.size = len(encoded_data) return data_byteio, tarinfo def annotation_to_byteio(records, name): data = '' for i, record in enumerate(records): data += '\n'.join([str(c) for c in record]) + '\n\n' encoded_data = data.encode('utf8') data_byteio = io.BytesIO(encoded_data) tarinfo = tarfile.TarInfo(name) tarinfo.size = len(encoded_data) return data_byteio, tarinfo def annotation_to_byteio_yuan(records, name): data = '' for i, record in enumerate(records): data += '\t'.join([str(c) for c in record]) + '\n' encoded_data = data.encode('utf8') data_byteio = io.BytesIO(encoded_data) tarinfo = tarfile.TarInfo(name) tarinfo.size = len(encoded_data) return data_byteio, tarinfo def write_panx_preprocessed(filehandle, filename, output_dir): langid = filename.split('.')[0] records = 0 all_records = [] record = [] tag_records = defaultdict(set) last_label_in_record = None for line in filehandle: line = line.decode('utf-8') line = line.strip() if 'docstart' in line.lower(): continue if line == '' and len(record) > 0: all_records.append(record) if last_label_in_record: tag_records[last_label_in_record].add(len(all_records) - 1) last_label_in_record = None record = [] elif line != '': fields = line.split() if len(fields) > 1: line = langid + ':' + fields[0] + '\t' + fields[-1] if 'B-' in fields[-1]: last_label_in_record = fields[-1] record.append(line) if len(record) > 0: all_records.append(record) #find the minimum count of B- tag, used for stratified sampling min_count_tag = min([len(v) for v in tag_records.values()]) #now sample min_count_tag records from each tag new_records = [] for _, records in tag_records.items(): new_records.extend(random.sample(records, min_count_tag)) #new records contains indices of items in all_records random.seed(0) np.random.seed(0) random.shuffle(new_records) all_records = [all_records[i] for i in new_records] total_records = len(all_records) if total_records > 30000: num_recs = 10000 elif total_records > 3000: num_recs = 1000 elif total_records > 300: num_recs = 100 else: return num_train = min((total_records - 2 * num_recs) - (total_records - 2 * num_recs) % 1000, 20000) num_train = max((num_train // 5000) * 5000, num_recs) train_set = all_records[0:num_train] dev_set = all_records[num_train:num_train + num_recs] test_set = all_records[num_train + num_recs:num_train + 2 * num_recs] extra_set = all_records[num_train + 2 * num_recs:] print(langid, 'train', num_train, 'dev/test', num_recs) tar = tarfile.open(os.path.join(output_dir, filename), "w:gz") train_data, train_tarinfo = data_to_byteio(train_set, 'train') dev_data, dev_tarinfo = data_to_byteio(dev_set, 'dev') test_data, test_tarinfo = data_to_byteio(test_set, 'test') extra_data, extra_tarinfo = data_to_byteio(extra_set, 'extra') tar.addfile(tarinfo=train_tarinfo, fileobj=train_data) tar.addfile(tarinfo=dev_tarinfo, fileobj=dev_data) tar.addfile(tarinfo=test_tarinfo, fileobj=test_data) tar.addfile(tarinfo=extra_tarinfo, fileobj=extra_data) tar.close() def get_cca59_languages(cca_59_file): lang_count = Counter() with gzip.open(cca_59_file, 'rt', encoding='utf-8') if 'gz' in cca_59_file else io.open(cca_59_file, 'r', encoding='utf-8') as fin: for line in fin: lang = line.split(':')[0] lang_count[lang] += 1 return lang_count def panx_to_dataset(input_dir, output_dir, supported_langs=None, count=False): files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))] if count: file_record = {} for file in files: targz_file = os.path.join(input_dir, file) tar = tarfile.open(targz_file, "r:gz") for member in tar.getmembers(): if '.bio' in member.name: bio_file = tar.extractfile(member) if bio_file is not None: num_records = check_num_records_by_content(bio_file, file) file_record[file] = num_records file_record = Counter(file_record) print(file_record.most_common()) with open(os.path.join(output_dir, 'lang_stats.json'), 'w') as fout: json.dump(file_record, fout) for file in files: langid = file.split('.')[0] if supported_langs and langid not in supported_langs: continue targz_file_in = os.path.join(input_dir, file) targz_file_out = os.path.join(output_dir, file) tar = tarfile.open(targz_file_in, "r:gz") for member in tar.getmembers(): if '.bio' in member.name: bio_file = tar.extractfile(member) if bio_file is not None: write_panx_preprocessed(bio_file, file, output_dir) tar.close() def parse_args(argv): """ Parse commandline arguments. Arguments: argv -- An argument list without the program name. """ parser = argparse.ArgumentParser() parser.add_argument('--embs_dir', type=str, required=True, help='directory containing the complete word embeddings') parser.add_argument('--ner_built_dir', type=str, required=True, help='directory where built output (trimmed embs + vocab) will be written into.') args = parser.parse_args(argv) return args if __name__ == '__main__': args = parse_args(sys.argv[1:]) logging.info(args) #facebook or allenai multilingual embeddings? embs_dir = args.embs_dir ner_built_dir = args.ner_built_dir #raw ner downloaded from panx wiki_ner_input_dir = './datasets/panx2_all/' #directory for converted raw ner data to train/test/dev stratified wiki_ner_output_dir = './datasets/panx_datasets' #'./datasets/panx2_supported45' wiki_embsupported_languages = ['af', 'ar', 'bg', 'bn', 'bs', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'fa', 'fi', 'fr', 'he', 'hi', 'hr', 'hu', 'id', 'it', 'lt', 'lv', 'mk', 'ms', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sq', 'sv', 'ta', 'tl', 'tr', 'uk', 'vi'] print(f"num langs: {len(wiki_embsupported_languages)}") create_ner_datasets = False if create_ner_datasets: #only run this once to create stratified train/dev/test splits from wikiann, and save them. panx_to_dataset(wiki_ner_input_dir, wiki_ner_output_dir, supported_langs=None)#wiki_embsupported_languages) sys.exit(0) all_chars = set() if not os.path.exists(ner_built_dir): os.mkdir(ner_built_dir) for lang in wiki_embsupported_languages: output_dir = os.path.join(ner_built_dir , f'builtdata_{lang}') emb_file = lang + '.multi.gz' #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/de/wikiann-de.bio', lang='de', output_dir=ner_dir) #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/en/wikiann-en.bio', lang='en', output_dir=ner_dir) #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/nl/wikiann-nl.bio', lang='nl', output_dir=ner_dir) if os.path.exists(output_dir): shutil.rmtree(output_dir) print(f"directory exists:{output_dir}") os.mkdir(output_dir) #for panx langid is already added to conll terms #add_lang_to_each_word(ner_dir, name_index=0, lang_separator=':') #embeddings already have lang identifier vocab, tags, chars = build_vocab(wiki_ner_output_dir, os.path.join(embs_dir, lang), output_dir, emb_file=emb_file, panx=True, fname='{}.tar.gz'.format(lang)) all_chars = all_chars | chars trim_embs(os.path.join(embs_dir, lang), os.path.join(output_dir, 'words.txt'), output_dir, 300, emb_file=emb_file) write_list(all_chars, os.path.join(ner_built_dir, 'chars.txt')) write_list(tags, os.path.join(ner_built_dir, 'tags.txt'))
<filename>utils.py from io import open import logging import pdb import random import os import numpy as np import shutil from collections import Counter import tarfile import json import random from collections import defaultdict import io import gzip import sys import argparse np.random.seed(7) random.seed(7) logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) def check_num_records(filename): records = 0 with open(filename, 'r', encoding='utf-8') as fin: for line in fin: if line.strip() == '': records += 1 logging.info('{} records in {}'.format(records, filename)) return records def check_num_records_by_content(filehandle, filename): records = 0 for line in filehandle: line = line.decode('utf-8') if line.strip() == '': records += 1 logging.info('{} records in {}'.format(records, filename)) return records def extract_records(input_file, output_file, num_records): records = 0 all_records = [] with open(input_file, 'r', encoding='utf-8') as fin: record = [] for line in fin: line = line.strip() if 'docstart' in line.lower(): continue if line == '' and len(record) > 0: all_records.append(record) record = [] elif line != '': record.append(line) all_records.append(record) selected_records = all_records[0:num_records] with open(output_file, 'w', encoding='utf-8') as fout: for i, record in enumerate(selected_records): for r in record: fout.write(r + '\n') fout.write('\n') def create_train_dev_test_from_one_file(conll_file, lang, output_dir): records = 0 all_records = [] with open(conll_file, 'r', encoding='utf-8') as fin: record = [] for line in fin: line = line.strip() if 'docstart' in line.lower(): continue if line == '' and len(record) > 0: all_records.append(record) record = [] elif line != '': fields = line.split() if len(fields) > 1: line = fields[0] + '\t' + fields[-1] record.append(line) if len(record) > 0: all_records.append(record) logging.info('{} sentences for {} detected.'.format(len(all_records), lang)) train_100 = all_records[0:100] train_1000 = all_records[0:1000] train_10000 = all_records[0:10000] test_count = dev_count = min(len(all_records) - 10000 // 2, 10000) dev = all_records[10000:10000 + dev_count] test = all_records[10000 + dev_count: 10000 + dev_count + test_count] train_100_file = os.path.join(output_dir, '{}.train.{}'.format(lang, 100)) train_1000_file = os.path.join(output_dir, '{}.train.{}'.format(lang, 1000)) train_10000_file = os.path.join(output_dir, '{}.train.{}'.format(lang, 10000)) dev_file = os.path.join(output_dir, '{}.dev'.format(lang)) test_file = os.path.join(output_dir, '{}.test'.format(lang)) file_records = [(train_100, train_100_file), (train_1000, train_1000_file), (train_10000, train_10000_file), (dev, dev_file), (test, test_file)] for file_record in file_records: with open(file_record[1], 'w', encoding='utf-8') as fout: for i, record in enumerate(file_record[0]): for r in record: fout.write(r + '\n') fout.write('\n') logging.info('created train dev test splits for {} in {}'.format(lang, output_dir)) def add_lang_to_each_word(dir_name, name_index, lang_separator=':', embfile=None): if embfile: files = [embfile] else: files = [f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f))] for file in files: if not embfile: if file[-5:] == 'multi' or 'cca-59' in str(file): continue lang = file.split('.')[name_index] print('lang:{}'.format(lang)) filename = os.path.join(dir_name, file) lines = [] with open(filename, 'r', encoding='utf-8') as fin: for line in fin: if line.strip() != '': line = lang + lang_separator + line lines.append(line) with open(filename + '.multi', 'w', encoding='utf-8') as fout: for line in lines: fout.write(line) def create_ner_training_datasets(): for lang in ['de', 'en', 'nl']: for i in [100, 1000, 10000]: extract_records(input_file='./datasets/ner/{}.train'.format(lang), output_file='./datasets/ner/{}.train.{}'.format(lang, i), num_records=i) check_num_records('./datasets/ner/{}.train.{}'.format(lang, i)) def collect_vocab_and_tags(dir_name, fname=None): ''' :param dir_name: :return set of all the vocab (+$UNK$ and +$NUM$ in all the files in the directory (expect all the files to be in conll2003 format): ''' tags = set() vocab = set() chars = set() files = [f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f))] if not fname else [os.path.join(dir_name, fname)] for file in files: #we just want the files where language id is added to the beginning of the words if file[-5:] != 'multi': continue filename = os.path.join(dir_name, file) with open(filename, 'r', encoding='utf-8') as fin: for line in fin: if line.strip() != '' and 'docstart' not in line.lower(): fields = line.split() if len(fields) > 1: word, tag = fields[0], fields[-1] else: logging.info('warning: error in line {} in file {}'.format(line, filename)) vocab.add(word.lower()) tags.add(tag) chars.update(word) return vocab, tags, chars def collect_vocab_and_tags_panx(panx_dir_name, fname=None): ''' :param dir_name: contains tar.gz files each with train test dev conll files :return set of all the vocab (+$UNK$ and +$NUM$ in all the files in the directory (expect all the files to be in conll2003 format): important note: all vocab in wikiembs :https://fasttext.cc/docs/en/pretrained-vectors.html are lowercase while words in wikiemb+crawlemb: https://fasttext.cc/docs/en/crawl-vectors.html have upper case words so it will make a huge difference in terms of OOVs and how we match words in NER datasets to words in the pre-trained word embeddings. ''' tags = set() vocab = set() chars = set() files = [f for f in os.listdir(panx_dir_name) if os.path.isfile(os.path.join(panx_dir_name, f))] if not fname else [fname] for file in files: targz_file = os.path.join(panx_dir_name, file) tar = tarfile.open(targz_file, "r:gz") for member in tar.getmembers(): #don't collect the vocabulary of extra annotated data if member.name == 'extra': continue bio_file = tar.extractfile(member) for line in bio_file: line = line.decode('utf-8') if line.strip() != '' and 'docstart' not in line.lower(): fields = line.split() if len(fields) > 1: word, tag = fields[0], fields[-1] else: logging.info('warning: error in line {} in file {}'.format(line, targz_file)) vocab.add(word) tags.add(tag) chars.update(word) tar.close() return vocab, tags, chars def collect_embedding_vocabs(dir_name, embfile=None): ''' :param dir_name: directory where all the word embeddings with different languages are located expected that lang id- (e.g. en-) is added to the beginning of each word so that exact words in different languages are distinguishable :return: set of vocab ''' vocab_emb = set() filename = os.path.join(dir_name, emb_file) with gzip.open(filename, 'rt', encoding='utf-8') if 'gz' in embfile else open(filename, 'r', encoding='utf-8') as fin: for line in fin: if line.strip() != '': word = line.split(' ')[0] vocab_emb.add(word) vocab_lang_distribution = [v.split(':')[0] for v in vocab_emb] vocab_lang_distribution = Counter(vocab_lang_distribution) logging.info('embedding file vocab stats: {}'.format(str(vocab_lang_distribution))) return vocab_emb def write_list(items, output_file): with open(output_file, 'w', encoding='utf-8') as fout: for i, item in enumerate(sorted(items)): if i != len(items) - 1: fout.write('{}\n'.format(item)) else: fout.write(item) def read_list(filename): items = [] with open(filename, 'r', encoding='utf-8') as fin: for item in fin: items.append(item.strip()) return items def write_vocab_tags_chars_embs(vocab_ner, tags, chars, vocab_emb, output_dir): write_list(tags, os.path.join(output_dir, 'tags.txt')) write_list(chars, os.path.join(output_dir, 'chars.txt')) ''' now we should add any vocab that might have uppercase in vocab_ner but is lowercase in vocab_emmb. note that lowercase=True should be turned to lowercase=False in mconfig file to reflect this. question: what about the cases when a lower case word is in NER but an uppercase is in emb? ''' vocab = vocab_ner & vocab_emb for v in vocab_ner: vlow = v.lower() if v == vlow: continue if v not in vocab_emb and vlow in vocab_emb: vocab.add(vlow) vocab_lang_distribution = [v.split(':')[0] for v in vocab] vocab_lang_distribution = Counter(vocab_lang_distribution) logging.info(vocab_lang_distribution) with open(os.path.join(output_dir, 'stats'), 'w') as fout: fout.write(str(vocab_lang_distribution)) vocab.add('$UNK$') vocab.add('$NUM$') write_list(vocab, os.path.join(output_dir, 'words.txt')) def build_vocab(conll_dir, emb_dir, output_dir, emb_file=None, panx=False, fname=None): if panx: vocab, tags, chars = collect_vocab_and_tags_panx(conll_dir, fname=fname) else: vocab, tags, chars = collect_vocab_and_tags(conll_dir) vocab_emb = collect_embedding_vocabs(emb_dir, emb_file) write_vocab_tags_chars_embs(vocab, tags, chars, vocab_emb, output_dir) return vocab, tags, chars def trim_embs(emb_dir, vocab_file, output_dir, dim, emb_file=None): vocab = read_list(vocab_file) vocabset = set(vocab) vocab_emb = set() embeddings = np.zeros([len(vocab), dim]) filename = os.path.join(emb_dir, emb_file) with gzip.open(filename, 'rt', encoding='utf-8') if 'gz' in emb_file else open(filename, 'r', encoding='utf-8') as fin: for line in fin: line = line.strip().split(' ') word = line[0] if word not in vocabset: continue embedding = [float(x) for x in line[1:]] word_idx = vocab.index(word) embeddings[word_idx] = np.asarray(embedding) np.savez_compressed(os.path.join(output_dir, 'trimmed_embs.npz'), embeddings=embeddings) def data_to_byteio(records, name): data = '' for i, record in enumerate(records): for r in record: data += r + '\n' data += '\n' encoded_data = data.encode('utf8') data_byteio = io.BytesIO(encoded_data) tarinfo = tarfile.TarInfo(name) tarinfo.size = len(encoded_data) return data_byteio, tarinfo def annotation_to_byteio(records, name): data = '' for i, record in enumerate(records): data += '\n'.join([str(c) for c in record]) + '\n\n' encoded_data = data.encode('utf8') data_byteio = io.BytesIO(encoded_data) tarinfo = tarfile.TarInfo(name) tarinfo.size = len(encoded_data) return data_byteio, tarinfo def annotation_to_byteio_yuan(records, name): data = '' for i, record in enumerate(records): data += '\t'.join([str(c) for c in record]) + '\n' encoded_data = data.encode('utf8') data_byteio = io.BytesIO(encoded_data) tarinfo = tarfile.TarInfo(name) tarinfo.size = len(encoded_data) return data_byteio, tarinfo def write_panx_preprocessed(filehandle, filename, output_dir): langid = filename.split('.')[0] records = 0 all_records = [] record = [] tag_records = defaultdict(set) last_label_in_record = None for line in filehandle: line = line.decode('utf-8') line = line.strip() if 'docstart' in line.lower(): continue if line == '' and len(record) > 0: all_records.append(record) if last_label_in_record: tag_records[last_label_in_record].add(len(all_records) - 1) last_label_in_record = None record = [] elif line != '': fields = line.split() if len(fields) > 1: line = langid + ':' + fields[0] + '\t' + fields[-1] if 'B-' in fields[-1]: last_label_in_record = fields[-1] record.append(line) if len(record) > 0: all_records.append(record) #find the minimum count of B- tag, used for stratified sampling min_count_tag = min([len(v) for v in tag_records.values()]) #now sample min_count_tag records from each tag new_records = [] for _, records in tag_records.items(): new_records.extend(random.sample(records, min_count_tag)) #new records contains indices of items in all_records random.seed(0) np.random.seed(0) random.shuffle(new_records) all_records = [all_records[i] for i in new_records] total_records = len(all_records) if total_records > 30000: num_recs = 10000 elif total_records > 3000: num_recs = 1000 elif total_records > 300: num_recs = 100 else: return num_train = min((total_records - 2 * num_recs) - (total_records - 2 * num_recs) % 1000, 20000) num_train = max((num_train // 5000) * 5000, num_recs) train_set = all_records[0:num_train] dev_set = all_records[num_train:num_train + num_recs] test_set = all_records[num_train + num_recs:num_train + 2 * num_recs] extra_set = all_records[num_train + 2 * num_recs:] print(langid, 'train', num_train, 'dev/test', num_recs) tar = tarfile.open(os.path.join(output_dir, filename), "w:gz") train_data, train_tarinfo = data_to_byteio(train_set, 'train') dev_data, dev_tarinfo = data_to_byteio(dev_set, 'dev') test_data, test_tarinfo = data_to_byteio(test_set, 'test') extra_data, extra_tarinfo = data_to_byteio(extra_set, 'extra') tar.addfile(tarinfo=train_tarinfo, fileobj=train_data) tar.addfile(tarinfo=dev_tarinfo, fileobj=dev_data) tar.addfile(tarinfo=test_tarinfo, fileobj=test_data) tar.addfile(tarinfo=extra_tarinfo, fileobj=extra_data) tar.close() def get_cca59_languages(cca_59_file): lang_count = Counter() with gzip.open(cca_59_file, 'rt', encoding='utf-8') if 'gz' in cca_59_file else io.open(cca_59_file, 'r', encoding='utf-8') as fin: for line in fin: lang = line.split(':')[0] lang_count[lang] += 1 return lang_count def panx_to_dataset(input_dir, output_dir, supported_langs=None, count=False): files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))] if count: file_record = {} for file in files: targz_file = os.path.join(input_dir, file) tar = tarfile.open(targz_file, "r:gz") for member in tar.getmembers(): if '.bio' in member.name: bio_file = tar.extractfile(member) if bio_file is not None: num_records = check_num_records_by_content(bio_file, file) file_record[file] = num_records file_record = Counter(file_record) print(file_record.most_common()) with open(os.path.join(output_dir, 'lang_stats.json'), 'w') as fout: json.dump(file_record, fout) for file in files: langid = file.split('.')[0] if supported_langs and langid not in supported_langs: continue targz_file_in = os.path.join(input_dir, file) targz_file_out = os.path.join(output_dir, file) tar = tarfile.open(targz_file_in, "r:gz") for member in tar.getmembers(): if '.bio' in member.name: bio_file = tar.extractfile(member) if bio_file is not None: write_panx_preprocessed(bio_file, file, output_dir) tar.close() def parse_args(argv): """ Parse commandline arguments. Arguments: argv -- An argument list without the program name. """ parser = argparse.ArgumentParser() parser.add_argument('--embs_dir', type=str, required=True, help='directory containing the complete word embeddings') parser.add_argument('--ner_built_dir', type=str, required=True, help='directory where built output (trimmed embs + vocab) will be written into.') args = parser.parse_args(argv) return args if __name__ == '__main__': args = parse_args(sys.argv[1:]) logging.info(args) #facebook or allenai multilingual embeddings? embs_dir = args.embs_dir ner_built_dir = args.ner_built_dir #raw ner downloaded from panx wiki_ner_input_dir = './datasets/panx2_all/' #directory for converted raw ner data to train/test/dev stratified wiki_ner_output_dir = './datasets/panx_datasets' #'./datasets/panx2_supported45' wiki_embsupported_languages = ['af', 'ar', 'bg', 'bn', 'bs', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'fa', 'fi', 'fr', 'he', 'hi', 'hr', 'hu', 'id', 'it', 'lt', 'lv', 'mk', 'ms', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sq', 'sv', 'ta', 'tl', 'tr', 'uk', 'vi'] print(f"num langs: {len(wiki_embsupported_languages)}") create_ner_datasets = False if create_ner_datasets: #only run this once to create stratified train/dev/test splits from wikiann, and save them. panx_to_dataset(wiki_ner_input_dir, wiki_ner_output_dir, supported_langs=None)#wiki_embsupported_languages) sys.exit(0) all_chars = set() if not os.path.exists(ner_built_dir): os.mkdir(ner_built_dir) for lang in wiki_embsupported_languages: output_dir = os.path.join(ner_built_dir , f'builtdata_{lang}') emb_file = lang + '.multi.gz' #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/de/wikiann-de.bio', lang='de', output_dir=ner_dir) #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/en/wikiann-en.bio', lang='en', output_dir=ner_dir) #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/nl/wikiann-nl.bio', lang='nl', output_dir=ner_dir) if os.path.exists(output_dir): shutil.rmtree(output_dir) print(f"directory exists:{output_dir}") os.mkdir(output_dir) #for panx langid is already added to conll terms #add_lang_to_each_word(ner_dir, name_index=0, lang_separator=':') #embeddings already have lang identifier vocab, tags, chars = build_vocab(wiki_ner_output_dir, os.path.join(embs_dir, lang), output_dir, emb_file=emb_file, panx=True, fname='{}.tar.gz'.format(lang)) all_chars = all_chars | chars trim_embs(os.path.join(embs_dir, lang), os.path.join(output_dir, 'words.txt'), output_dir, 300, emb_file=emb_file) write_list(all_chars, os.path.join(ner_built_dir, 'chars.txt')) write_list(tags, os.path.join(ner_built_dir, 'tags.txt'))
en
0.697125
:param dir_name: :return set of all the vocab (+$UNK$ and +$NUM$ in all the files in the directory (expect all the files to be in conll2003 format): #we just want the files where language id is added to the beginning of the words :param dir_name: contains tar.gz files each with train test dev conll files :return set of all the vocab (+$UNK$ and +$NUM$ in all the files in the directory (expect all the files to be in conll2003 format): important note: all vocab in wikiembs :https://fasttext.cc/docs/en/pretrained-vectors.html are lowercase while words in wikiemb+crawlemb: https://fasttext.cc/docs/en/crawl-vectors.html have upper case words so it will make a huge difference in terms of OOVs and how we match words in NER datasets to words in the pre-trained word embeddings. #don't collect the vocabulary of extra annotated data :param dir_name: directory where all the word embeddings with different languages are located expected that lang id- (e.g. en-) is added to the beginning of each word so that exact words in different languages are distinguishable :return: set of vocab now we should add any vocab that might have uppercase in vocab_ner but is lowercase in vocab_emmb. note that lowercase=True should be turned to lowercase=False in mconfig file to reflect this. question: what about the cases when a lower case word is in NER but an uppercase is in emb? #find the minimum count of B- tag, used for stratified sampling #now sample min_count_tag records from each tag #new records contains indices of items in all_records Parse commandline arguments. Arguments: argv -- An argument list without the program name. #facebook or allenai multilingual embeddings? #raw ner downloaded from panx #directory for converted raw ner data to train/test/dev stratified #'./datasets/panx2_supported45' #only run this once to create stratified train/dev/test splits from wikiann, and save them. #wiki_embsupported_languages) #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/de/wikiann-de.bio', lang='de', output_dir=ner_dir) #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/en/wikiann-en.bio', lang='en', output_dir=ner_dir) #create_train_dev_test_from_one_file(conll_file='./datasets/originals/ner/nl/wikiann-nl.bio', lang='nl', output_dir=ner_dir) #for panx langid is already added to conll terms #add_lang_to_each_word(ner_dir, name_index=0, lang_separator=':') #embeddings already have lang identifier
2.437597
2
evaluate_sket.py
ExaNLP/sket
4
6613684
<reponame>ExaNLP/sket<gh_stars>1-10 import numpy as np import json import glob import os import argparse from sklearn.metrics import hamming_loss, accuracy_score, classification_report parser = argparse.ArgumentParser() parser.add_argument('--gt', default='./ground_truth/lung/aoec/lung_labels_allDS.json', type=str, help='Ground truth file.') parser.add_argument('--outputs', default='./outputs/labels/aoec/lung/*.json', type=str, help='SKET results file.') parser.add_argument('--use_case', default='lung', choices=['colon', 'cervix', 'lung'], help='Considered use-case.') parser.add_argument('--hospital', default='aoec', choices=['aoec', 'radboud'], help='Considered hospital.') parser.add_argument('--debug', default=False, action='store_true', help='Whether to use evaluation for debugging purposes.') args = parser.parse_args() label2class = { 'cervix': { 'Normal glands': 'glands_norm', 'Normal squamous': 'squamous_norm', 'Cancer - squamous cell carcinoma in situ': 'cancer_scc_insitu', 'Low grade dysplasia': 'lgd', 'Cancer - squamous cell carcinoma invasive': 'cancer_scc_inv', 'High grade dysplasia': 'hgd', 'Koilocytes': 'koilocytes', 'Cancer - adenocarcinoma invasive': 'cancer_adeno_inv', 'Cancer - adenocarcinoma in situ': 'cancer_adeno_insitu', 'HPV infection present': 'hpv' }, 'colon': { 'Hyperplastic polyp': 'hyperplastic', 'Cancer': 'cancer', 'Adenomatous polyp - high grade dysplasia': 'hgd', 'Adenomatous polyp - low grade dysplasia': 'lgd', 'Non-informative': 'ni' }, 'lung': { 'No cancer': 'no_cancer', 'Cancer - non-small cell cancer, adenocarcinoma': 'cancer_nscc_adeno', 'Cancer - non-small cell cancer, squamous cell carcinoma': 'cancer_nscc_squamous', 'Cancer - small cell cancer': 'cancer_scc', 'Cancer - non-small cell cancer, large cell carcinoma': 'cancer_nscc_large' } } def main(): # create path for debugging debug_path = './logs/debug/' + args.hospital + '/' + args.use_case + '/' os.makedirs(os.path.dirname(debug_path), exist_ok=True) # read ground-truth with open(args.gt, 'r') as gtf: ground_truth = json.load(gtf) gt = {} # prepare ground-truth for evaluation if args.use_case == 'colon' and args.hospital == 'aoec': gt = ground_truth else: ground_truth = ground_truth['ground_truth'] for data in ground_truth: rid = data['report_id_not_hashed'] if len(rid.split('_')) == 3 and args.hospital == 'aoec': # contains codeint info not present within new processed reports rid = rid.split('_') rid = rid[0] + '_' + rid[2] gt[rid] = {label2class[args.use_case][label]: 0 for label in label2class[args.use_case].keys()} for datum in data['labels']: label = label2class[args.use_case][datum['label']] if label in gt[rid]: gt[rid][label] = 1 # gt name gt_name = args.gt.split('/')[-1].split('.')[0] # read SKET results if '*.json' == args.outputs.split('/')[-1]: # read files # read file paths rsfps = glob.glob(args.outputs) # set dict rs = {} for rsfp in rsfps: with open(rsfp, 'r') as rsf: rs.update(json.load(rsf)) else: # read file with open(args.outputs, 'r') as rsf: rs = json.load(rsf) sket = {} # prepare SKET results for evaluation for rid, rdata in rs.items(): if args.use_case == 'colon' and args.hospital == 'aoec' and '2ndDS' in args.gt: rid = rid.split('_')[0] if args.hospital == 'radboud' and args.use_case == 'colon': sket[rid] = rdata['labels'] else: sket[rid] = rdata # fix class order to avoid inconsistencies rids = list(sket.keys()) classes = list(sket[rids[0]].keys()) # obtain ground-truth and SKET scores gt_scores = [] sket_scores = [] if args.debug: # open output for debugging debugf = open(debug_path + gt_name + '.txt', 'w+') for rid in gt.keys(): gt_rscores = [] sket_rscores = [] if rid not in sket: print('skipped gt record: {}'.format(rid)) continue if args.debug: first = True for c in classes: gt_rscores.append(gt[rid][c]) sket_rscores.append(sket[rid][c]) if args.debug: # perform debugging if gt[rid][c] != sket[rid][c]: # store info for debugging purposes if first: # first occurence debugf.write('\nReport ID: {}\n'.format(rid)) first = False debugf.write(c + ': gt = {}, sket = {}\n'.format(gt[rid][c], sket[rid][c])) gt_scores.append(gt_rscores) sket_scores.append(sket_rscores) if args.debug: # close output for debugging debugf.close() # convert to numpy gt_scores = np.array(gt_scores) sket_scores = np.array(sket_scores) # compute evaluation measures print('Compute evaluation measures') # exact match accuracy & hamming loss print("Accuracy (exact match): {}".format(accuracy_score(gt_scores, sket_scores))) print("Hamming loss: {}\n".format(hamming_loss(gt_scores, sket_scores))) # compute classification report print("Classification report:") print(classification_report(y_true=gt_scores, y_pred=sket_scores, target_names=classes)) if __name__ == "__main__": main()
import numpy as np import json import glob import os import argparse from sklearn.metrics import hamming_loss, accuracy_score, classification_report parser = argparse.ArgumentParser() parser.add_argument('--gt', default='./ground_truth/lung/aoec/lung_labels_allDS.json', type=str, help='Ground truth file.') parser.add_argument('--outputs', default='./outputs/labels/aoec/lung/*.json', type=str, help='SKET results file.') parser.add_argument('--use_case', default='lung', choices=['colon', 'cervix', 'lung'], help='Considered use-case.') parser.add_argument('--hospital', default='aoec', choices=['aoec', 'radboud'], help='Considered hospital.') parser.add_argument('--debug', default=False, action='store_true', help='Whether to use evaluation for debugging purposes.') args = parser.parse_args() label2class = { 'cervix': { 'Normal glands': 'glands_norm', 'Normal squamous': 'squamous_norm', 'Cancer - squamous cell carcinoma in situ': 'cancer_scc_insitu', 'Low grade dysplasia': 'lgd', 'Cancer - squamous cell carcinoma invasive': 'cancer_scc_inv', 'High grade dysplasia': 'hgd', 'Koilocytes': 'koilocytes', 'Cancer - adenocarcinoma invasive': 'cancer_adeno_inv', 'Cancer - adenocarcinoma in situ': 'cancer_adeno_insitu', 'HPV infection present': 'hpv' }, 'colon': { 'Hyperplastic polyp': 'hyperplastic', 'Cancer': 'cancer', 'Adenomatous polyp - high grade dysplasia': 'hgd', 'Adenomatous polyp - low grade dysplasia': 'lgd', 'Non-informative': 'ni' }, 'lung': { 'No cancer': 'no_cancer', 'Cancer - non-small cell cancer, adenocarcinoma': 'cancer_nscc_adeno', 'Cancer - non-small cell cancer, squamous cell carcinoma': 'cancer_nscc_squamous', 'Cancer - small cell cancer': 'cancer_scc', 'Cancer - non-small cell cancer, large cell carcinoma': 'cancer_nscc_large' } } def main(): # create path for debugging debug_path = './logs/debug/' + args.hospital + '/' + args.use_case + '/' os.makedirs(os.path.dirname(debug_path), exist_ok=True) # read ground-truth with open(args.gt, 'r') as gtf: ground_truth = json.load(gtf) gt = {} # prepare ground-truth for evaluation if args.use_case == 'colon' and args.hospital == 'aoec': gt = ground_truth else: ground_truth = ground_truth['ground_truth'] for data in ground_truth: rid = data['report_id_not_hashed'] if len(rid.split('_')) == 3 and args.hospital == 'aoec': # contains codeint info not present within new processed reports rid = rid.split('_') rid = rid[0] + '_' + rid[2] gt[rid] = {label2class[args.use_case][label]: 0 for label in label2class[args.use_case].keys()} for datum in data['labels']: label = label2class[args.use_case][datum['label']] if label in gt[rid]: gt[rid][label] = 1 # gt name gt_name = args.gt.split('/')[-1].split('.')[0] # read SKET results if '*.json' == args.outputs.split('/')[-1]: # read files # read file paths rsfps = glob.glob(args.outputs) # set dict rs = {} for rsfp in rsfps: with open(rsfp, 'r') as rsf: rs.update(json.load(rsf)) else: # read file with open(args.outputs, 'r') as rsf: rs = json.load(rsf) sket = {} # prepare SKET results for evaluation for rid, rdata in rs.items(): if args.use_case == 'colon' and args.hospital == 'aoec' and '2ndDS' in args.gt: rid = rid.split('_')[0] if args.hospital == 'radboud' and args.use_case == 'colon': sket[rid] = rdata['labels'] else: sket[rid] = rdata # fix class order to avoid inconsistencies rids = list(sket.keys()) classes = list(sket[rids[0]].keys()) # obtain ground-truth and SKET scores gt_scores = [] sket_scores = [] if args.debug: # open output for debugging debugf = open(debug_path + gt_name + '.txt', 'w+') for rid in gt.keys(): gt_rscores = [] sket_rscores = [] if rid not in sket: print('skipped gt record: {}'.format(rid)) continue if args.debug: first = True for c in classes: gt_rscores.append(gt[rid][c]) sket_rscores.append(sket[rid][c]) if args.debug: # perform debugging if gt[rid][c] != sket[rid][c]: # store info for debugging purposes if first: # first occurence debugf.write('\nReport ID: {}\n'.format(rid)) first = False debugf.write(c + ': gt = {}, sket = {}\n'.format(gt[rid][c], sket[rid][c])) gt_scores.append(gt_rscores) sket_scores.append(sket_rscores) if args.debug: # close output for debugging debugf.close() # convert to numpy gt_scores = np.array(gt_scores) sket_scores = np.array(sket_scores) # compute evaluation measures print('Compute evaluation measures') # exact match accuracy & hamming loss print("Accuracy (exact match): {}".format(accuracy_score(gt_scores, sket_scores))) print("Hamming loss: {}\n".format(hamming_loss(gt_scores, sket_scores))) # compute classification report print("Classification report:") print(classification_report(y_true=gt_scores, y_pred=sket_scores, target_names=classes)) if __name__ == "__main__": main()
en
0.820588
# create path for debugging # read ground-truth # prepare ground-truth for evaluation # contains codeint info not present within new processed reports # gt name # read SKET results # read files # read file paths # set dict # read file # prepare SKET results for evaluation # fix class order to avoid inconsistencies # obtain ground-truth and SKET scores # open output for debugging # perform debugging # store info for debugging purposes # first occurence # close output for debugging # convert to numpy # compute evaluation measures # exact match accuracy & hamming loss # compute classification report
2.359874
2
tests/asm_logical/test_asm_ora.py
CyberZHG/mos-6502-restricted-assembler
0
6613685
from unittest import TestCase from asm_6502 import Assembler class TestAssembleORA(TestCase): def setUp(self) -> None: self.assembler = Assembler() def test_ora_immediate(self): code = "ORA #$10" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x09, 0x10]), ], results) def test_ora_zero_page(self): code = "ORA $10" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x05, 0x10]), ], results) def test_ora_zero_page_x(self): code = "ORA $10,X" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x15, 0x10]), ], results) def test_ora_absolute(self): code = "ORA $ABCD" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x0D, 0xCD, 0xAB]), ], results) def test_ora_absolute_indexed(self): code = "ORA $ABCD,X\n" \ "ORA $ABCD,Y" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x1D, 0xCD, 0xAB, 0x19, 0xCD, 0xAB]), ], results) def test_ora_indexed_indirect(self): code = "ORA ($10,X)" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x01, 0x10]), ], results) def test_ora_indirect_indexed(self): code = "ORA ($10),Y" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x11, 0x10]), ], results)
from unittest import TestCase from asm_6502 import Assembler class TestAssembleORA(TestCase): def setUp(self) -> None: self.assembler = Assembler() def test_ora_immediate(self): code = "ORA #$10" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x09, 0x10]), ], results) def test_ora_zero_page(self): code = "ORA $10" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x05, 0x10]), ], results) def test_ora_zero_page_x(self): code = "ORA $10,X" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x15, 0x10]), ], results) def test_ora_absolute(self): code = "ORA $ABCD" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x0D, 0xCD, 0xAB]), ], results) def test_ora_absolute_indexed(self): code = "ORA $ABCD,X\n" \ "ORA $ABCD,Y" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x1D, 0xCD, 0xAB, 0x19, 0xCD, 0xAB]), ], results) def test_ora_indexed_indirect(self): code = "ORA ($10,X)" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x01, 0x10]), ], results) def test_ora_indirect_indexed(self): code = "ORA ($10),Y" results = self.assembler.assemble(code, add_entry=False) self.assertEqual([ (0x0000, [0x11, 0x10]), ], results)
none
1
2.601373
3
nicos_mlz/labs/battery/setups/battery.py
jkrueger1/nicos
12
6613686
<gh_stars>10-100 description = 'Battery temperature sensors' includes = ['battery01', 'battery02', 'battery03']
description = 'Battery temperature sensors' includes = ['battery01', 'battery02', 'battery03']
none
1
1.076291
1
apps/simauth/apps.py
gilsonbp/simcapital
0
6613687
from django.apps import AppConfig class SIMAuthConfig(AppConfig): name = 'apps.simauth' label = 'simauth' verbose_name = 'SIM Auth'
from django.apps import AppConfig class SIMAuthConfig(AppConfig): name = 'apps.simauth' label = 'simauth' verbose_name = 'SIM Auth'
none
1
1.217937
1
pydarkstar/tests/test_item.py
Korrbit/pydarkstar
18
6613688
<reponame>Korrbit/pydarkstar import unittest import_error = False try: from ..item import Item except ImportError: import_error = True Item = None class TestCase00(unittest.TestCase): def test_import(self): self.assertFalse(import_error) class TestCase01(unittest.TestCase): def setUp(self): if import_error: self.skipTest('ImportError') def test_init(self): i0 = Item(0, 'A') self.assertEqual(i0.itemid, 0) self.assertEqual(i0.name, 'A') def test_price01(self): Item(0, price01=+1) with self.assertRaises(ValueError): Item(0, price01=+0) with self.assertRaises(ValueError): Item(0, price01=-1) def test_price12(self): Item(0, price12=+1) with self.assertRaises(ValueError): Item(0, price12=+0) with self.assertRaises(ValueError): Item(0, price12=-1) def test_stock01(self): Item(0, stock01=+0) with self.assertRaises(ValueError): Item(0, stock01=-1) def test_stock12(self): Item(0, stock12=+0) with self.assertRaises(ValueError): Item(0, stock12=-1) def test_rate01(self): i = Item(0) self.assertEqual(i.rate01, 1.0) Item(0, rate01=0.0) Item(0, rate01=0.5) Item(0, rate01=1.0) with self.assertRaises(ValueError): Item(0, rate01=-1.5) with self.assertRaises(ValueError): Item(0, rate01=+1.5) def test_rate12(self): i = Item(0) self.assertEqual(i.rate12, 1.0) Item(0, rate12=0.0) Item(0, rate12=0.5) Item(0, rate12=1.0) with self.assertRaises(ValueError): Item(0, rate12=-1.5) with self.assertRaises(ValueError): Item(0, rate12=+1.5)
import unittest import_error = False try: from ..item import Item except ImportError: import_error = True Item = None class TestCase00(unittest.TestCase): def test_import(self): self.assertFalse(import_error) class TestCase01(unittest.TestCase): def setUp(self): if import_error: self.skipTest('ImportError') def test_init(self): i0 = Item(0, 'A') self.assertEqual(i0.itemid, 0) self.assertEqual(i0.name, 'A') def test_price01(self): Item(0, price01=+1) with self.assertRaises(ValueError): Item(0, price01=+0) with self.assertRaises(ValueError): Item(0, price01=-1) def test_price12(self): Item(0, price12=+1) with self.assertRaises(ValueError): Item(0, price12=+0) with self.assertRaises(ValueError): Item(0, price12=-1) def test_stock01(self): Item(0, stock01=+0) with self.assertRaises(ValueError): Item(0, stock01=-1) def test_stock12(self): Item(0, stock12=+0) with self.assertRaises(ValueError): Item(0, stock12=-1) def test_rate01(self): i = Item(0) self.assertEqual(i.rate01, 1.0) Item(0, rate01=0.0) Item(0, rate01=0.5) Item(0, rate01=1.0) with self.assertRaises(ValueError): Item(0, rate01=-1.5) with self.assertRaises(ValueError): Item(0, rate01=+1.5) def test_rate12(self): i = Item(0) self.assertEqual(i.rate12, 1.0) Item(0, rate12=0.0) Item(0, rate12=0.5) Item(0, rate12=1.0) with self.assertRaises(ValueError): Item(0, rate12=-1.5) with self.assertRaises(ValueError): Item(0, rate12=+1.5)
none
1
3.158523
3
newBlock.py
Anubhav-Bhargava/Decentralized-Authentication-System
5
6613689
<reponame>Anubhav-Bhargava/Decentralized-Authentication-System<gh_stars>1-10 from block import * import datetime as dt def next_block(last_block, data): this_index = last_block.index + 1 this_timestamp = dt.datetime.now() # A one level deep copy of data has been created since data is modified repeatedly # in the calling function and if data is a direct pointer, it leads to modification # of old data in the chain. this_data = data[:] this_prev_hash = last_block.hash return Block(this_index, this_timestamp, this_data, this_prev_hash) def add_block(form, data, blockchain): '''i = 1 while form.get("roll_no{}".format(i)): data[-1].append(form.get("roll_no{}".format(i))) i += 1''' previous_block = blockchain[-1] block_to_add = next_block(previous_block, data) blockchain.append(block_to_add) previous_block = block_to_add return "Block #{} has been added to the blockchain!".format(block_to_add.index)
from block import * import datetime as dt def next_block(last_block, data): this_index = last_block.index + 1 this_timestamp = dt.datetime.now() # A one level deep copy of data has been created since data is modified repeatedly # in the calling function and if data is a direct pointer, it leads to modification # of old data in the chain. this_data = data[:] this_prev_hash = last_block.hash return Block(this_index, this_timestamp, this_data, this_prev_hash) def add_block(form, data, blockchain): '''i = 1 while form.get("roll_no{}".format(i)): data[-1].append(form.get("roll_no{}".format(i))) i += 1''' previous_block = blockchain[-1] block_to_add = next_block(previous_block, data) blockchain.append(block_to_add) previous_block = block_to_add return "Block #{} has been added to the blockchain!".format(block_to_add.index)
en
0.813729
# A one level deep copy of data has been created since data is modified repeatedly # in the calling function and if data is a direct pointer, it leads to modification # of old data in the chain. i = 1 while form.get("roll_no{}".format(i)): data[-1].append(form.get("roll_no{}".format(i))) i += 1 #{} has been added to the blockchain!".format(block_to_add.index)
3.122696
3
day02/3-post.py
Mhh123/spider
0
6613690
import urllib.request import urllib.parse post_url = 'http://fanyi.baidu.com/sug' word = input('请输入您要查询到单词') data = { 'kw': word, } # 对表单数据进行处理,先转化为字符串,再转化为字节格式 data = urllib.parse.urlencode(data).encode('utf8') headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1;Win64; x64) AppleWebkit/537.36 (' 'KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36', } request = urllib.request.Request(post_url, headers=headers) response = urllib.request.urlopen(request, data=data) print(response.read().decode('utf8'))
import urllib.request import urllib.parse post_url = 'http://fanyi.baidu.com/sug' word = input('请输入您要查询到单词') data = { 'kw': word, } # 对表单数据进行处理,先转化为字符串,再转化为字节格式 data = urllib.parse.urlencode(data).encode('utf8') headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1;Win64; x64) AppleWebkit/537.36 (' 'KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36', } request = urllib.request.Request(post_url, headers=headers) response = urllib.request.urlopen(request, data=data) print(response.read().decode('utf8'))
zh
0.968124
# 对表单数据进行处理,先转化为字符串,再转化为字节格式
3.391943
3
__checkdIfIntegerDifferByTen.py
simdevex/01.Basics
0
6613691
''' Python program to test a list of one hundred integers between 0 and 999, which all differ by ten from one another. Return true or false. Input: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800, 810, 820, 830, 840, 850, 860, 870, 880, 890, 900, 910, 920, 930, 940, 950, 960, 970, 980, 990] Output: True Input: [0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400, 420, 440, 460, 480, 500, 520, 540, 560, 580, 600, 620, 640, 660, 680, 700, 720, 740, 760, 780, 800, 820, 840, 860, 880, 900, 920, 940, 960, 980] Output: False ''' #License: https://bit.ly/3oLErEI def test(li): #all() function returns True if all items in an iterable are true, otherwise it returns False. #If the iterable object is empty, the all() function also returns True. all() only works on iteratable #Long single line return statement ''' for i in li: for j in li: if i != j : return (i in range(1000) and abs(i - j) >= 10) and len(set(li)) == 100 ''' return all(i in range(1000) and abs(i - j) >= 10 for i in li for j in li if i != j) and len(set(li)) == 100 nums = list(range(0, 1000, 10)) print("Original list:") print(nums) print("Check whether the said list contains one hundred integers between 0 and 999 which all differ by ten from one another:") print(test(nums)) nums = list(range(0, 1000, 20)) print("Original list:") print(nums) print("Check whether the said list contains one hundred integers between 0 and 999 which all differ by ten from one another:") print(test(nums))
''' Python program to test a list of one hundred integers between 0 and 999, which all differ by ten from one another. Return true or false. Input: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800, 810, 820, 830, 840, 850, 860, 870, 880, 890, 900, 910, 920, 930, 940, 950, 960, 970, 980, 990] Output: True Input: [0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400, 420, 440, 460, 480, 500, 520, 540, 560, 580, 600, 620, 640, 660, 680, 700, 720, 740, 760, 780, 800, 820, 840, 860, 880, 900, 920, 940, 960, 980] Output: False ''' #License: https://bit.ly/3oLErEI def test(li): #all() function returns True if all items in an iterable are true, otherwise it returns False. #If the iterable object is empty, the all() function also returns True. all() only works on iteratable #Long single line return statement ''' for i in li: for j in li: if i != j : return (i in range(1000) and abs(i - j) >= 10) and len(set(li)) == 100 ''' return all(i in range(1000) and abs(i - j) >= 10 for i in li for j in li if i != j) and len(set(li)) == 100 nums = list(range(0, 1000, 10)) print("Original list:") print(nums) print("Check whether the said list contains one hundred integers between 0 and 999 which all differ by ten from one another:") print(test(nums)) nums = list(range(0, 1000, 20)) print("Original list:") print(nums) print("Check whether the said list contains one hundred integers between 0 and 999 which all differ by ten from one another:") print(test(nums))
en
0.360962
Python program to test a list of one hundred integers between 0 and 999, which all differ by ten from one another. Return true or false. Input: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800, 810, 820, 830, 840, 850, 860, 870, 880, 890, 900, 910, 920, 930, 940, 950, 960, 970, 980, 990] Output: True Input: [0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400, 420, 440, 460, 480, 500, 520, 540, 560, 580, 600, 620, 640, 660, 680, 700, 720, 740, 760, 780, 800, 820, 840, 860, 880, 900, 920, 940, 960, 980] Output: False #License: https://bit.ly/3oLErEI #all() function returns True if all items in an iterable are true, otherwise it returns False. #If the iterable object is empty, the all() function also returns True. all() only works on iteratable #Long single line return statement for i in li: for j in li: if i != j : return (i in range(1000) and abs(i - j) >= 10) and len(set(li)) == 100
3.747006
4
phylip2eigenstrat.py
btmartin721/phylip2eigenstrat
2
6613692
#!/usr/bin/env python import argparse from datastruct import Struct def get_arguments(): parser = argparse.ArgumentParser(description="Generates Eigenstrat .snp and .ind files \ for use with AdmixTools software package") parser.add_argument("-p", "--phylip", type=str, required=True, help="Input filename in PHYLIP format") parser.add_argument("-i", "--ind", type=str, required=False, help="ind output filename; Default = out.ind", nargs="?", default="out.ind") parser.add_argument("-n", "--snp", type=str, required=False, help="snp output filename; Default = out.snp", nargs="?", default="out.snp") parser.add_argument("-s", "--start", type=int, required=False, nargs="?", default="1", help="Specify first character of sample ID to be used as pattern for population ID; default=1") parser.add_argument("-e", "--end", type=int, required=False, nargs="?", default="4", help="Specify last character of sample ID to be used as pattern for population ID; default=4") args = parser.parse_args() return args def read_phylip(line): line = line.rstrip("\r\n") ids_loci = line.strip().split(None, 1) ids = ids_loci[0] loc = ids_loci[1] return ids, loc, header def make_indfile(ID, file, pattern): file.write(ID + "\t" + "U" + "\t" + pattern + "\n") def make_snpfile(file, header): initial = 0.000000 numInd, loci = header.split() for i in range(1, int(loci)+1): file.write("a" + "_" + str(i) + "\t" + "1" + "\t" + '%0.6f' % initial + "\t" + str(i) + "\n") initial += 0.000010 def get_unique_identifiers(pattern, hit, number): if not hit: dataset.make_dict(number, hit, pattern) elif pattern not in hit: number += 1 dataset.make_dict(number, hit, pattern) return number ##################################################################################################### ##################################MAIN############################################################### ##################################################################################################### args = get_arguments() unique_ids = dict() popnum = 1 with open(args.phylip, "r") as fin: with open(args.ind, "w") as indout: with open(args.snp, "w") as snpout: header = fin.readline() header = header.rstrip() for lines in fin: ids, loc, header = read_phylip(lines) dataset = Struct(ids, loc) patt = dataset.id[args.start-1:args.end] popnum = get_unique_identifiers(patt, unique_ids, popnum) # Returns popID and adds 1 for each unique ID popid = unique_ids[patt] # dictionary with unique ids (key), popID (value) make_indfile(dataset.id, indout, str(patt)) make_snpfile(snpout, header)
#!/usr/bin/env python import argparse from datastruct import Struct def get_arguments(): parser = argparse.ArgumentParser(description="Generates Eigenstrat .snp and .ind files \ for use with AdmixTools software package") parser.add_argument("-p", "--phylip", type=str, required=True, help="Input filename in PHYLIP format") parser.add_argument("-i", "--ind", type=str, required=False, help="ind output filename; Default = out.ind", nargs="?", default="out.ind") parser.add_argument("-n", "--snp", type=str, required=False, help="snp output filename; Default = out.snp", nargs="?", default="out.snp") parser.add_argument("-s", "--start", type=int, required=False, nargs="?", default="1", help="Specify first character of sample ID to be used as pattern for population ID; default=1") parser.add_argument("-e", "--end", type=int, required=False, nargs="?", default="4", help="Specify last character of sample ID to be used as pattern for population ID; default=4") args = parser.parse_args() return args def read_phylip(line): line = line.rstrip("\r\n") ids_loci = line.strip().split(None, 1) ids = ids_loci[0] loc = ids_loci[1] return ids, loc, header def make_indfile(ID, file, pattern): file.write(ID + "\t" + "U" + "\t" + pattern + "\n") def make_snpfile(file, header): initial = 0.000000 numInd, loci = header.split() for i in range(1, int(loci)+1): file.write("a" + "_" + str(i) + "\t" + "1" + "\t" + '%0.6f' % initial + "\t" + str(i) + "\n") initial += 0.000010 def get_unique_identifiers(pattern, hit, number): if not hit: dataset.make_dict(number, hit, pattern) elif pattern not in hit: number += 1 dataset.make_dict(number, hit, pattern) return number ##################################################################################################### ##################################MAIN############################################################### ##################################################################################################### args = get_arguments() unique_ids = dict() popnum = 1 with open(args.phylip, "r") as fin: with open(args.ind, "w") as indout: with open(args.snp, "w") as snpout: header = fin.readline() header = header.rstrip() for lines in fin: ids, loc, header = read_phylip(lines) dataset = Struct(ids, loc) patt = dataset.id[args.start-1:args.end] popnum = get_unique_identifiers(patt, unique_ids, popnum) # Returns popID and adds 1 for each unique ID popid = unique_ids[patt] # dictionary with unique ids (key), popID (value) make_indfile(dataset.id, indout, str(patt)) make_snpfile(snpout, header)
de
0.737424
#!/usr/bin/env python ##################################################################################################### ##################################MAIN############################################################### ##################################################################################################### # Returns popID and adds 1 for each unique ID # dictionary with unique ids (key), popID (value)
2.869272
3
identity.py
kamens/gae_bingo
34
6613693
from __future__ import absolute_import import base64 import logging import os import re from google.appengine.ext import db from gae_bingo.config import config from gae_bingo import cookies from gae_bingo import request_cache from .models import GAEBingoIdentityModel IDENTITY_COOKIE_KEY = "gae_b_id" IDENTITY_COOKIE_AGE = 365 * 24 * 60 * 60 # ~1 year in seconds CAN_CONTROL_CACHE_KEY = "CAN_CONTROL_CACHE" IDENTITY_CACHE_KEY = "IDENTITY_CACHE" LOGGED_IN_IDENTITY_CACHE_KEY = "LOGGED_IN_IDENTITY_CACHE" ID_TO_PUT_CACHE_KEY = "ID_TO_PUT" def can_control_experiments(): if request_cache.cache.get(CAN_CONTROL_CACHE_KEY) is None: request_cache.cache[CAN_CONTROL_CACHE_KEY] = ( config.can_control_experiments()) return request_cache.cache[CAN_CONTROL_CACHE_KEY] def logged_in_bingo_identity(): if request_cache.cache.get(LOGGED_IN_IDENTITY_CACHE_KEY) is None: request_cache.cache[LOGGED_IN_IDENTITY_CACHE_KEY] = config.current_logged_in_identity() return request_cache.cache[LOGGED_IN_IDENTITY_CACHE_KEY] def flush_caches(): """Flush the caches associated with the logged in identity. This is useful if the logged in identity changed for some reason mid-request. """ request_cache.cache.pop(CAN_CONTROL_CACHE_KEY, None) request_cache.cache.pop(IDENTITY_CACHE_KEY, None) request_cache.cache.pop(LOGGED_IN_IDENTITY_CACHE_KEY, None) request_cache.cache.pop(ID_TO_PUT_CACHE_KEY, None) def identity(identity_val=None): """ Determines the Bingo identity for the specified user. If no user is specified, this will attempt to infer one based on cookies/logged in user identity_val -- a string or instance of GAEBingoIdentityModel specifying which bingo identity to retrieve. """ if identity_val: # Don't cache for arbitrarily passed in identity_val return bingo_identity_for_value(identity_val, associate_with_cookie=False) if request_cache.cache.get(IDENTITY_CACHE_KEY) is None: if is_bot(): # Just make all bots identify as the same single user so they don't # bias results. Following simple suggestion in # http://www.bingocardcreator.com/abingo/faq request_cache.cache[IDENTITY_CACHE_KEY] = "_gae_bingo_bot" else: # Try to get unique (hopefully persistent) identity from user's implementation, # otherwise grab the current cookie value, otherwise grab random value. request_cache.cache[IDENTITY_CACHE_KEY] = str(get_logged_in_bingo_identity_value() or get_identity_cookie_value() or get_random_identity_value()) return request_cache.cache[IDENTITY_CACHE_KEY] def using_logged_in_bingo_identity(): return identity() and identity() == get_logged_in_bingo_identity_value() def get_logged_in_bingo_identity_value(): val = logged_in_bingo_identity() return bingo_identity_for_value(val) def bingo_identity_for_value(val, associate_with_cookie=True): # We cache the ID we generate here, to put only at the end of the request if val is None: return None if isinstance(val, db.Model): if isinstance(val, GAEBingoIdentityModel): # If it's a db.Model that inherited from GAEBingoIdentityModel, return bingo identity if not val.gae_bingo_identity: if (is_random_identity_value(get_identity_cookie_value()) and associate_with_cookie): # If the current model doesn't have a bingo identity associated w/ it # and we have a random cookie value already set, associate it with this identity model. # # This keeps the user's experience consistent between using the site pre- and post-login. request_cache.cache[ID_TO_PUT_CACHE_KEY] = get_identity_cookie_value() else: # Otherwise just use the key, it's guaranteed to be unique request_cache.cache[ID_TO_PUT_CACHE_KEY] = str(val.key()) return val.gae_bingo_identity # If it's just a normal db instance, just use its unique key return str(val.key()) # Otherwise it's just a plain unique string return str(val) def get_random_identity_value(): return "_gae_bingo_random:%s" % base64.urlsafe_b64encode(os.urandom(30)) def is_random_identity_value(val): return val and val.startswith("_gae_bingo_random") def get_identity_cookie_value(): cookie_val = cookies.get_cookie_value(IDENTITY_COOKIE_KEY) if cookie_val: try: return base64.urlsafe_b64decode(cookie_val) except: pass return None def put_id_if_necessary(): """To be called at the end of a request. Check to see if we should put() the gae_bingo_identity, and put() it if so. """ id_to_put = request_cache.cache.get(ID_TO_PUT_CACHE_KEY) if id_to_put: val = config.current_logged_in_identity() if val is None: return if isinstance(val, GAEBingoIdentityModel): if val.gae_bingo_identity and id_to_put != val.gae_bingo_identity: logging.warning( "val.gae_bingo_identity got set to %s unexpectedly," "but id_to_put is %s" % (val.gae_bingo_identity, id_to_put)) else: # If the UserData has been updated in the course of this # request current_logged_in_identity might read a stale version # of the UserData from the request_cache. In order to make # sure we have the latest userData we will get the the userData # again. val = db.get(val.key()) val.gae_bingo_identity = id_to_put val.put() # Flush the transaction so the HR datastore doesn't suffer from # eventual consistency issues when next grabbing this UserData. db.get(val.key()) def set_identity_cookie_header(): return cookies.set_cookie_value(IDENTITY_COOKIE_KEY, base64.urlsafe_b64encode(identity()), max_age=IDENTITY_COOKIE_AGE) def delete_identity_cookie_header(): return cookies.set_cookie_value(IDENTITY_COOKIE_KEY, "") # I am well aware that this is a far-from-perfect, hacky method of quickly # determining who's a bot or not. If necessary, in the future we could implement # a javascript check like a/bingo and django-lean do -- but for now, I'm sticking # w/ the simplest possible implementation for devs (don't need to add JS in any template code) # that doesn't strongly bias the statistical outcome (undetected bots aren't a distaster, # because they shouldn't favor one side over the other). bot_regex = re.compile("(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)", re.IGNORECASE) def is_bot(): return bool(bot_regex.search(os.environ.get("HTTP_USER_AGENT") or ""))
from __future__ import absolute_import import base64 import logging import os import re from google.appengine.ext import db from gae_bingo.config import config from gae_bingo import cookies from gae_bingo import request_cache from .models import GAEBingoIdentityModel IDENTITY_COOKIE_KEY = "gae_b_id" IDENTITY_COOKIE_AGE = 365 * 24 * 60 * 60 # ~1 year in seconds CAN_CONTROL_CACHE_KEY = "CAN_CONTROL_CACHE" IDENTITY_CACHE_KEY = "IDENTITY_CACHE" LOGGED_IN_IDENTITY_CACHE_KEY = "LOGGED_IN_IDENTITY_CACHE" ID_TO_PUT_CACHE_KEY = "ID_TO_PUT" def can_control_experiments(): if request_cache.cache.get(CAN_CONTROL_CACHE_KEY) is None: request_cache.cache[CAN_CONTROL_CACHE_KEY] = ( config.can_control_experiments()) return request_cache.cache[CAN_CONTROL_CACHE_KEY] def logged_in_bingo_identity(): if request_cache.cache.get(LOGGED_IN_IDENTITY_CACHE_KEY) is None: request_cache.cache[LOGGED_IN_IDENTITY_CACHE_KEY] = config.current_logged_in_identity() return request_cache.cache[LOGGED_IN_IDENTITY_CACHE_KEY] def flush_caches(): """Flush the caches associated with the logged in identity. This is useful if the logged in identity changed for some reason mid-request. """ request_cache.cache.pop(CAN_CONTROL_CACHE_KEY, None) request_cache.cache.pop(IDENTITY_CACHE_KEY, None) request_cache.cache.pop(LOGGED_IN_IDENTITY_CACHE_KEY, None) request_cache.cache.pop(ID_TO_PUT_CACHE_KEY, None) def identity(identity_val=None): """ Determines the Bingo identity for the specified user. If no user is specified, this will attempt to infer one based on cookies/logged in user identity_val -- a string or instance of GAEBingoIdentityModel specifying which bingo identity to retrieve. """ if identity_val: # Don't cache for arbitrarily passed in identity_val return bingo_identity_for_value(identity_val, associate_with_cookie=False) if request_cache.cache.get(IDENTITY_CACHE_KEY) is None: if is_bot(): # Just make all bots identify as the same single user so they don't # bias results. Following simple suggestion in # http://www.bingocardcreator.com/abingo/faq request_cache.cache[IDENTITY_CACHE_KEY] = "_gae_bingo_bot" else: # Try to get unique (hopefully persistent) identity from user's implementation, # otherwise grab the current cookie value, otherwise grab random value. request_cache.cache[IDENTITY_CACHE_KEY] = str(get_logged_in_bingo_identity_value() or get_identity_cookie_value() or get_random_identity_value()) return request_cache.cache[IDENTITY_CACHE_KEY] def using_logged_in_bingo_identity(): return identity() and identity() == get_logged_in_bingo_identity_value() def get_logged_in_bingo_identity_value(): val = logged_in_bingo_identity() return bingo_identity_for_value(val) def bingo_identity_for_value(val, associate_with_cookie=True): # We cache the ID we generate here, to put only at the end of the request if val is None: return None if isinstance(val, db.Model): if isinstance(val, GAEBingoIdentityModel): # If it's a db.Model that inherited from GAEBingoIdentityModel, return bingo identity if not val.gae_bingo_identity: if (is_random_identity_value(get_identity_cookie_value()) and associate_with_cookie): # If the current model doesn't have a bingo identity associated w/ it # and we have a random cookie value already set, associate it with this identity model. # # This keeps the user's experience consistent between using the site pre- and post-login. request_cache.cache[ID_TO_PUT_CACHE_KEY] = get_identity_cookie_value() else: # Otherwise just use the key, it's guaranteed to be unique request_cache.cache[ID_TO_PUT_CACHE_KEY] = str(val.key()) return val.gae_bingo_identity # If it's just a normal db instance, just use its unique key return str(val.key()) # Otherwise it's just a plain unique string return str(val) def get_random_identity_value(): return "_gae_bingo_random:%s" % base64.urlsafe_b64encode(os.urandom(30)) def is_random_identity_value(val): return val and val.startswith("_gae_bingo_random") def get_identity_cookie_value(): cookie_val = cookies.get_cookie_value(IDENTITY_COOKIE_KEY) if cookie_val: try: return base64.urlsafe_b64decode(cookie_val) except: pass return None def put_id_if_necessary(): """To be called at the end of a request. Check to see if we should put() the gae_bingo_identity, and put() it if so. """ id_to_put = request_cache.cache.get(ID_TO_PUT_CACHE_KEY) if id_to_put: val = config.current_logged_in_identity() if val is None: return if isinstance(val, GAEBingoIdentityModel): if val.gae_bingo_identity and id_to_put != val.gae_bingo_identity: logging.warning( "val.gae_bingo_identity got set to %s unexpectedly," "but id_to_put is %s" % (val.gae_bingo_identity, id_to_put)) else: # If the UserData has been updated in the course of this # request current_logged_in_identity might read a stale version # of the UserData from the request_cache. In order to make # sure we have the latest userData we will get the the userData # again. val = db.get(val.key()) val.gae_bingo_identity = id_to_put val.put() # Flush the transaction so the HR datastore doesn't suffer from # eventual consistency issues when next grabbing this UserData. db.get(val.key()) def set_identity_cookie_header(): return cookies.set_cookie_value(IDENTITY_COOKIE_KEY, base64.urlsafe_b64encode(identity()), max_age=IDENTITY_COOKIE_AGE) def delete_identity_cookie_header(): return cookies.set_cookie_value(IDENTITY_COOKIE_KEY, "") # I am well aware that this is a far-from-perfect, hacky method of quickly # determining who's a bot or not. If necessary, in the future we could implement # a javascript check like a/bingo and django-lean do -- but for now, I'm sticking # w/ the simplest possible implementation for devs (don't need to add JS in any template code) # that doesn't strongly bias the statistical outcome (undetected bots aren't a distaster, # because they shouldn't favor one side over the other). bot_regex = re.compile("(Baidu|Gigabot|Googlebot|libwww-perl|lwp-trivial|msnbot|SiteUptime|Slurp|WordPress|ZIBB|ZyBorg)", re.IGNORECASE) def is_bot(): return bool(bot_regex.search(os.environ.get("HTTP_USER_AGENT") or ""))
en
0.865962
# ~1 year in seconds Flush the caches associated with the logged in identity. This is useful if the logged in identity changed for some reason mid-request. Determines the Bingo identity for the specified user. If no user is specified, this will attempt to infer one based on cookies/logged in user identity_val -- a string or instance of GAEBingoIdentityModel specifying which bingo identity to retrieve. # Don't cache for arbitrarily passed in identity_val # Just make all bots identify as the same single user so they don't # bias results. Following simple suggestion in # http://www.bingocardcreator.com/abingo/faq # Try to get unique (hopefully persistent) identity from user's implementation, # otherwise grab the current cookie value, otherwise grab random value. # We cache the ID we generate here, to put only at the end of the request # If it's a db.Model that inherited from GAEBingoIdentityModel, return bingo identity # If the current model doesn't have a bingo identity associated w/ it # and we have a random cookie value already set, associate it with this identity model. # # This keeps the user's experience consistent between using the site pre- and post-login. # Otherwise just use the key, it's guaranteed to be unique # If it's just a normal db instance, just use its unique key # Otherwise it's just a plain unique string To be called at the end of a request. Check to see if we should put() the gae_bingo_identity, and put() it if so. # If the UserData has been updated in the course of this # request current_logged_in_identity might read a stale version # of the UserData from the request_cache. In order to make # sure we have the latest userData we will get the the userData # again. # Flush the transaction so the HR datastore doesn't suffer from # eventual consistency issues when next grabbing this UserData. # I am well aware that this is a far-from-perfect, hacky method of quickly # determining who's a bot or not. If necessary, in the future we could implement # a javascript check like a/bingo and django-lean do -- but for now, I'm sticking # w/ the simplest possible implementation for devs (don't need to add JS in any template code) # that doesn't strongly bias the statistical outcome (undetected bots aren't a distaster, # because they shouldn't favor one side over the other).
2.223537
2
usaspending_api/broker/tests/integration/test_get_delete_pks_for_afa_keys.py
g4brielvs/usaspending-api
217
6613694
import pytest from django.db import connections from django.test import TestCase from usaspending_api.broker.helpers.delete_fabs_transactions import get_delete_pks_for_afa_keys @pytest.mark.usefixtures("broker_db_setup") class TestThingWithMultipleDatabases(TestCase): databases = "__all__" @classmethod def setUpTestData(cls): connection = connections["data_broker"] with connection.cursor() as cursor: cursor.execute("select count(*) from published_award_financial_assistance") assert cursor.fetchone()[0] == 0, "Another test somewhere is leaking data" cursor.execute( """ insert into published_award_financial_assistance ( published_award_financial_assistance_id, afa_generated_unique, is_active ) (values (1, 'abc', false), (2, 'aBc', false), (3, 'ABC', true), (4, 'xyz', false), (5, 'xYz', false), (6, 'XYZ', false), (7, 'lmn', false), (8, 'opq', true) ) """ ) def test_get_delete_pks_for_afa_keys(self): assert get_delete_pks_for_afa_keys(None) == [] assert get_delete_pks_for_afa_keys([]) == [] assert set(get_delete_pks_for_afa_keys(["abc", "xyZ"])) == {1, 2, 4, 5, 6}
import pytest from django.db import connections from django.test import TestCase from usaspending_api.broker.helpers.delete_fabs_transactions import get_delete_pks_for_afa_keys @pytest.mark.usefixtures("broker_db_setup") class TestThingWithMultipleDatabases(TestCase): databases = "__all__" @classmethod def setUpTestData(cls): connection = connections["data_broker"] with connection.cursor() as cursor: cursor.execute("select count(*) from published_award_financial_assistance") assert cursor.fetchone()[0] == 0, "Another test somewhere is leaking data" cursor.execute( """ insert into published_award_financial_assistance ( published_award_financial_assistance_id, afa_generated_unique, is_active ) (values (1, 'abc', false), (2, 'aBc', false), (3, 'ABC', true), (4, 'xyz', false), (5, 'xYz', false), (6, 'XYZ', false), (7, 'lmn', false), (8, 'opq', true) ) """ ) def test_get_delete_pks_for_afa_keys(self): assert get_delete_pks_for_afa_keys(None) == [] assert get_delete_pks_for_afa_keys([]) == [] assert set(get_delete_pks_for_afa_keys(["abc", "xyZ"])) == {1, 2, 4, 5, 6}
en
0.232439
insert into published_award_financial_assistance ( published_award_financial_assistance_id, afa_generated_unique, is_active ) (values (1, 'abc', false), (2, 'aBc', false), (3, 'ABC', true), (4, 'xyz', false), (5, 'xYz', false), (6, 'XYZ', false), (7, 'lmn', false), (8, 'opq', true) )
2.04819
2
tests/cogctl/cli/test_version.py
operable/cogctl
3
6613695
<gh_stars>1-10 import re from cogctl.cli.version import version def test_version(cogctl): result = cogctl(version) assert result.exit_code == 0 expr = re.compile('^cogctl ([a-z0-9\-/])+ \(build: (([a-f0-9]){7}|unknown)\)') output = result.output.strip() assert re.fullmatch(expr, output) is not None
import re from cogctl.cli.version import version def test_version(cogctl): result = cogctl(version) assert result.exit_code == 0 expr = re.compile('^cogctl ([a-z0-9\-/])+ \(build: (([a-f0-9]){7}|unknown)\)') output = result.output.strip() assert re.fullmatch(expr, output) is not None
none
1
2.485997
2
bot.py
gothraven/instabot.py
0
6613696
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from instabot_py import InstaBot bot = InstaBot( login=os.environ.get('INSTA_USER', ''), password=os.environ.get('INSTA_PASSWORD', ''), start_at_h=10, start_at_m=0, end_at_h=20, end_at_m=0, like_per_day=500, comments_per_day=50, tag_list=[ 'l:212999109', #Los Angeles 'l:6889842', #Paris 'l:219370504', #Algers 'l:213326726', #Warsaw 'l:213385402', #London # 'change', 'lavieestbelle', 'doglover', 'tweegram', 'nature', 'cool', 'cat', 'cutie', 'onedirection', 'black', # 'igparis', 'igersparis', 'fuckology', 'red', 'music', 'inspiration', 'dogsofinstagram', 'bestoftheday', # 'white', 'goodmorning', 'instagramhub', 'school', 'green', 'nofilter', 'iphonesia', 'petsagram', # 'celibataire', 'doglovers', 'girl', 'pretty', 'travel', 'halloween', 'bored', 'adorable', 'precious', # 'motivationalquotes', 'equipedefrance', 'clouds', 'puppies', 'ilovedog', 'hair', 'summer', 'blue', # 'awesome', 'petstagram', 'night', 'versagram', 'dogoftheday', 'quotestoliveby', 'picpets', 'instagramers', # 'party', 'animals', 'yum', 'dogs', 'igers', 'iphoneonly', 'positivevibes', 'lyon', 'amazing', 'photo', # 'cute', 'love', 'puppy', 'parisienne', 'pet', 'parisien', 'food', 'bleublancrouge', 'sweet', 'lifequotes', # 'comment', 'girls', 'repost', 'fuckologyquotes', 'animal', 'parisjetaime', 'family', 'naturephotography', # 'morningmotivation', 'goodvibes', 'quote', 'igdaily', 'ilovemydog', 'morningvibes', 'quoteoftheday', # 'lol', 'word', 'friends', 'bestfriend', 'beautiful', 'igaddict', 'instadaily', 'pets', 'indiea', # 'instamood', 'sun', 'swag', 'life', 'mornings', 'instagood', 'allezlesbleus', 'throwbackthursday', # 'sunrise', 'me', 'parismonamour', 'poetry', 'funny', 'instagramdogs', 'harrystyles', 'baby', 'happy', # 'igfrance', 'all_shots', 'fashion', 'ilovedogs', 'ig', 'follow', 'bordeaux', 'smile', 'tagblender', # 'creativity', 'allezlesbleues', 'lifestyle', 'sunset', 'photooftheday', 'followback', 'photography', # 'pink', 'inspirationalquotes', 'instahub', 'jj', 'picstitch', 'like', 'dog', 'comments', 'followme', # 'doggy', 'instalove', 'eyes', 'motivation', 'impatience', 'hot', 'picoftheday', 'tail', 'tea', 'my', # 'yummy', 'fucklove', 'fitfrenchies', 'tbt', 'instago', 'naturel', 'quotes', 'morning', 'beach', 'art', # 'jj_forum', 'paris', 'sky', 'pup', 'dogstagram', 'fun', 'bhfyp', ], tag_blacklist=[], user_blacklist={}, max_like_for_one_tag=100, follow_per_day=0, #follow_per_day = 500 follow_time=0, #follow_time=1 * 60 * 60, unfollow_per_day=0, #unfollow_per_day=300 unfollow_break_min=0, #unfollow_break_min=15 * 60, unfollow_break_max=0, #unfollow_break_max=30 * 60 log_mod=0, proxy='', # List of list of words, each of which will be used to generate comment # For example: "This shot feels wow!" comment_list=[['👆', '👌', '💪'], ['😎', '😍', '😉'], ['🤙', '👍']], # Use unwanted_username_list to block usernames containing a string ## Will do partial matches; i.e. 'mozart' will block 'legend_mozart' ### 'free_followers' will be blocked because it contains 'free' unwanted_username_list=[ 'second', 'stuff', 'art', 'project', 'love', 'life', 'food', 'blog', 'free', 'keren', 'photo', 'graphy', 'indo', 'travel', 'art', 'shop', 'store', 'sex', 'toko', 'jual', 'online', 'murah', 'jam', 'kaos', 'case', 'baju', 'fashion', 'corp', 'tas', 'butik', 'grosir', 'karpet', 'sosis', 'salon', 'skin', 'care', 'cloth', 'tech', 'rental', 'kamera', 'beauty', 'express', 'kredit', 'collection', 'impor', 'preloved', 'follow', 'follower', 'gain', '.id', '_id', 'bags' ], unfollow_whitelist=[]) bot.mainloop()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from instabot_py import InstaBot bot = InstaBot( login=os.environ.get('INSTA_USER', ''), password=os.environ.get('INSTA_PASSWORD', ''), start_at_h=10, start_at_m=0, end_at_h=20, end_at_m=0, like_per_day=500, comments_per_day=50, tag_list=[ 'l:212999109', #Los Angeles 'l:6889842', #Paris 'l:219370504', #Algers 'l:213326726', #Warsaw 'l:213385402', #London # 'change', 'lavieestbelle', 'doglover', 'tweegram', 'nature', 'cool', 'cat', 'cutie', 'onedirection', 'black', # 'igparis', 'igersparis', 'fuckology', 'red', 'music', 'inspiration', 'dogsofinstagram', 'bestoftheday', # 'white', 'goodmorning', 'instagramhub', 'school', 'green', 'nofilter', 'iphonesia', 'petsagram', # 'celibataire', 'doglovers', 'girl', 'pretty', 'travel', 'halloween', 'bored', 'adorable', 'precious', # 'motivationalquotes', 'equipedefrance', 'clouds', 'puppies', 'ilovedog', 'hair', 'summer', 'blue', # 'awesome', 'petstagram', 'night', 'versagram', 'dogoftheday', 'quotestoliveby', 'picpets', 'instagramers', # 'party', 'animals', 'yum', 'dogs', 'igers', 'iphoneonly', 'positivevibes', 'lyon', 'amazing', 'photo', # 'cute', 'love', 'puppy', 'parisienne', 'pet', 'parisien', 'food', 'bleublancrouge', 'sweet', 'lifequotes', # 'comment', 'girls', 'repost', 'fuckologyquotes', 'animal', 'parisjetaime', 'family', 'naturephotography', # 'morningmotivation', 'goodvibes', 'quote', 'igdaily', 'ilovemydog', 'morningvibes', 'quoteoftheday', # 'lol', 'word', 'friends', 'bestfriend', 'beautiful', 'igaddict', 'instadaily', 'pets', 'indiea', # 'instamood', 'sun', 'swag', 'life', 'mornings', 'instagood', 'allezlesbleus', 'throwbackthursday', # 'sunrise', 'me', 'parismonamour', 'poetry', 'funny', 'instagramdogs', 'harrystyles', 'baby', 'happy', # 'igfrance', 'all_shots', 'fashion', 'ilovedogs', 'ig', 'follow', 'bordeaux', 'smile', 'tagblender', # 'creativity', 'allezlesbleues', 'lifestyle', 'sunset', 'photooftheday', 'followback', 'photography', # 'pink', 'inspirationalquotes', 'instahub', 'jj', 'picstitch', 'like', 'dog', 'comments', 'followme', # 'doggy', 'instalove', 'eyes', 'motivation', 'impatience', 'hot', 'picoftheday', 'tail', 'tea', 'my', # 'yummy', 'fucklove', 'fitfrenchies', 'tbt', 'instago', 'naturel', 'quotes', 'morning', 'beach', 'art', # 'jj_forum', 'paris', 'sky', 'pup', 'dogstagram', 'fun', 'bhfyp', ], tag_blacklist=[], user_blacklist={}, max_like_for_one_tag=100, follow_per_day=0, #follow_per_day = 500 follow_time=0, #follow_time=1 * 60 * 60, unfollow_per_day=0, #unfollow_per_day=300 unfollow_break_min=0, #unfollow_break_min=15 * 60, unfollow_break_max=0, #unfollow_break_max=30 * 60 log_mod=0, proxy='', # List of list of words, each of which will be used to generate comment # For example: "This shot feels wow!" comment_list=[['👆', '👌', '💪'], ['😎', '😍', '😉'], ['🤙', '👍']], # Use unwanted_username_list to block usernames containing a string ## Will do partial matches; i.e. 'mozart' will block 'legend_mozart' ### 'free_followers' will be blocked because it contains 'free' unwanted_username_list=[ 'second', 'stuff', 'art', 'project', 'love', 'life', 'food', 'blog', 'free', 'keren', 'photo', 'graphy', 'indo', 'travel', 'art', 'shop', 'store', 'sex', 'toko', 'jual', 'online', 'murah', 'jam', 'kaos', 'case', 'baju', 'fashion', 'corp', 'tas', 'butik', 'grosir', 'karpet', 'sosis', 'salon', 'skin', 'care', 'cloth', 'tech', 'rental', 'kamera', 'beauty', 'express', 'kredit', 'collection', 'impor', 'preloved', 'follow', 'follower', 'gain', '.id', '_id', 'bags' ], unfollow_whitelist=[]) bot.mainloop()
en
0.096848
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Los Angeles #Paris #Algers #Warsaw #London # 'change', 'lavieestbelle', 'doglover', 'tweegram', 'nature', 'cool', 'cat', 'cutie', 'onedirection', 'black', # 'igparis', 'igersparis', 'fuckology', 'red', 'music', 'inspiration', 'dogsofinstagram', 'bestoftheday', # 'white', 'goodmorning', 'instagramhub', 'school', 'green', 'nofilter', 'iphonesia', 'petsagram', # 'celibataire', 'doglovers', 'girl', 'pretty', 'travel', 'halloween', 'bored', 'adorable', 'precious', # 'motivationalquotes', 'equipedefrance', 'clouds', 'puppies', 'ilovedog', 'hair', 'summer', 'blue', # 'awesome', 'petstagram', 'night', 'versagram', 'dogoftheday', 'quotestoliveby', 'picpets', 'instagramers', # 'party', 'animals', 'yum', 'dogs', 'igers', 'iphoneonly', 'positivevibes', 'lyon', 'amazing', 'photo', # 'cute', 'love', 'puppy', 'parisienne', 'pet', 'parisien', 'food', 'bleublancrouge', 'sweet', 'lifequotes', # 'comment', 'girls', 'repost', 'fuckologyquotes', 'animal', 'parisjetaime', 'family', 'naturephotography', # 'morningmotivation', 'goodvibes', 'quote', 'igdaily', 'ilovemydog', 'morningvibes', 'quoteoftheday', # 'lol', 'word', 'friends', 'bestfriend', 'beautiful', 'igaddict', 'instadaily', 'pets', 'indiea', # 'instamood', 'sun', 'swag', 'life', 'mornings', 'instagood', 'allezlesbleus', 'throwbackthursday', # 'sunrise', 'me', 'parismonamour', 'poetry', 'funny', 'instagramdogs', 'harrystyles', 'baby', 'happy', # 'igfrance', 'all_shots', 'fashion', 'ilovedogs', 'ig', 'follow', 'bordeaux', 'smile', 'tagblender', # 'creativity', 'allezlesbleues', 'lifestyle', 'sunset', 'photooftheday', 'followback', 'photography', # 'pink', 'inspirationalquotes', 'instahub', 'jj', 'picstitch', 'like', 'dog', 'comments', 'followme', # 'doggy', 'instalove', 'eyes', 'motivation', 'impatience', 'hot', 'picoftheday', 'tail', 'tea', 'my', # 'yummy', 'fucklove', 'fitfrenchies', 'tbt', 'instago', 'naturel', 'quotes', 'morning', 'beach', 'art', # 'jj_forum', 'paris', 'sky', 'pup', 'dogstagram', 'fun', 'bhfyp', #follow_per_day = 500 #follow_time=1 * 60 * 60, #unfollow_per_day=300 #unfollow_break_min=15 * 60, #unfollow_break_max=30 * 60 # List of list of words, each of which will be used to generate comment # For example: "This shot feels wow!" # Use unwanted_username_list to block usernames containing a string ## Will do partial matches; i.e. 'mozart' will block 'legend_mozart' ### 'free_followers' will be blocked because it contains 'free'
1.960834
2
attendance.py
LaudateCorpus1/aws-mv-object-detection
0
6613697
<reponame>LaudateCorpus1/aws-mv-object-detection # Based off of https://aws.amazon.com/blogs/machine-learning/build-your-own-face-recognition-service-using-amazon-rekognition/ # Using Meraki Python SDK at https://github.com/meraki/dashboard-api-python import time from datetime import date import boto3 import io import credentials import meraki import snapshot import student_list from PIL import Image, ImageDraw, ImageFont from webexteamssdk import WebexTeamsAPI def attendance(rekognition_api_client, dynamodb_api_client, filename): # Open stored image and send to Rekognition image = Image.open(filename) stream = io.BytesIO() image.save(stream,format="JPEG") image_binary = stream.getvalue() response = rekognition_api_client.detect_faces( Image={'Bytes':image_binary} ) all_faces=response['FaceDetails'] draw = ImageDraw.Draw(image) print('Avengers Assembling...') attendees = [] for face in all_faces: box = face['BoundingBox'] x1 = int(box['Left'] * image.size[0]) * 0.9 y1 = int(box['Top'] * image.size[1]) * 0.9 x2 = int(box['Left'] * image.size[0] + box['Width'] * image.size[0]) * 1.10 y2 = int(box['Top'] * image.size[1] + box['Height'] * image.size[1]) * 1.10 image_crop = image.crop((x1,y1,x2,y2)) stream = io.BytesIO() image_crop.save(stream,format="JPEG") image_crop_binary = stream.getvalue() #print('Detecting faces...') #image_crop.show() try: response = rekognition_api_client.search_faces_by_image( CollectionId='faces', Image={'Bytes':image_crop_binary} ) # Initialize averages confidence_avg = 0 if response['FaceMatches'] == []: print ("Someone unknown Assembled.") name = '<NAME>' imgfont = ImageFont.truetype(font='Arial Unicode.ttf', size=20) points, left, top = snapshot.draw_bounding_box(image=image, box=box) draw.line(points, fill='#00d400', width=5) draw.text(xy=(left,top), text=name, fill='#00d400', font=imgfont) else: for match in response['FaceMatches']: confidence_avg = confidence_avg + match['Face']['Confidence'] face = dynamodb_api_client.get_item( TableName='faces', Key={'RekognitionId': {'S': match['Face']['FaceId']}} ) if len(face) == 2: name = face['Item']['FullName']['S'] imgfont = ImageFont.truetype(font='Arial Unicode.ttf', size=20) points, left, top = snapshot.draw_bounding_box(image=image, box=box) draw.line(points, fill='#00d400', width=5) draw.text(xy=(left,top), text=name, fill='#00d400', font=imgfont) confidence_avg = confidence_avg/len(response['FaceMatches']) attendees += [str(name)] if name=='Thanos': print('Thanos is here.') else: print('{} Assembled with {} percent confidence.'.format(name,confidence_avg)) except: print("Something went wrong!") print('There are {} total Avengers Assembled against Thanos.'.format(len(all_faces)-1)) image.save(filename, "JPEG") image.show() return attendees, filename if __name__ == "__main__": # Importing variables api_key = credentials.api_key baseurl = credentials.base_url org_id = credentials.organization_id networks = credentials.networks cams = credentials.cams students = student_list.student_list webex_email = credentials.webex_email webex_token = credentials.webex_token # Instantiate Meraki Python SDK Client dashboard = meraki.DashboardAPI( api_key=api_key, base_url=baseurl, log_file_prefix='./logs/attendance/', print_console=False) # Instantiate AWS Python SDK Clients # Must configure AWS CLI for this to work # See https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html rekognition = boto3.client('rekognition', region_name='us-east-2') dynamodb = boto3.client('dynamodb', region_name='us-east-2') webex = WebexTeamsAPI(access_token=webex_token) # Record timestamp for snapshot name timestr = time.strftime("%Y%m%d-%H%M%S") file_name = snapshot.snap( dashboard_api_client=dashboard, time_string=timestr, networkIds=networks, organizationId=org_id, cameras=cams, base_url=baseurl, folder='attendance') attendees, filename = attendance( rekognition_api_client=rekognition, dynamodb_api_client=dynamodb, filename = file_name) x = set(attendees) y = set(students) z = y.difference(x) # Generate Attendance Report filename = file_name body = "These are the Avengers who Assembled on {}.".format(date.today().isoformat()) body = body + "\n\nAssembled:\n{}".format(x) body = body + "\n\nDidn't Assemble:\n{}".format(z) print("Assembled: \n{}".format(x)) print("Didn't Assemble: \n{}".format(z)) webex.messages.create(toPersonEmail=webex_email, text=body, files=[filename])
# Based off of https://aws.amazon.com/blogs/machine-learning/build-your-own-face-recognition-service-using-amazon-rekognition/ # Using Meraki Python SDK at https://github.com/meraki/dashboard-api-python import time from datetime import date import boto3 import io import credentials import meraki import snapshot import student_list from PIL import Image, ImageDraw, ImageFont from webexteamssdk import WebexTeamsAPI def attendance(rekognition_api_client, dynamodb_api_client, filename): # Open stored image and send to Rekognition image = Image.open(filename) stream = io.BytesIO() image.save(stream,format="JPEG") image_binary = stream.getvalue() response = rekognition_api_client.detect_faces( Image={'Bytes':image_binary} ) all_faces=response['FaceDetails'] draw = ImageDraw.Draw(image) print('Avengers Assembling...') attendees = [] for face in all_faces: box = face['BoundingBox'] x1 = int(box['Left'] * image.size[0]) * 0.9 y1 = int(box['Top'] * image.size[1]) * 0.9 x2 = int(box['Left'] * image.size[0] + box['Width'] * image.size[0]) * 1.10 y2 = int(box['Top'] * image.size[1] + box['Height'] * image.size[1]) * 1.10 image_crop = image.crop((x1,y1,x2,y2)) stream = io.BytesIO() image_crop.save(stream,format="JPEG") image_crop_binary = stream.getvalue() #print('Detecting faces...') #image_crop.show() try: response = rekognition_api_client.search_faces_by_image( CollectionId='faces', Image={'Bytes':image_crop_binary} ) # Initialize averages confidence_avg = 0 if response['FaceMatches'] == []: print ("Someone unknown Assembled.") name = '<NAME>' imgfont = ImageFont.truetype(font='Arial Unicode.ttf', size=20) points, left, top = snapshot.draw_bounding_box(image=image, box=box) draw.line(points, fill='#00d400', width=5) draw.text(xy=(left,top), text=name, fill='#00d400', font=imgfont) else: for match in response['FaceMatches']: confidence_avg = confidence_avg + match['Face']['Confidence'] face = dynamodb_api_client.get_item( TableName='faces', Key={'RekognitionId': {'S': match['Face']['FaceId']}} ) if len(face) == 2: name = face['Item']['FullName']['S'] imgfont = ImageFont.truetype(font='Arial Unicode.ttf', size=20) points, left, top = snapshot.draw_bounding_box(image=image, box=box) draw.line(points, fill='#00d400', width=5) draw.text(xy=(left,top), text=name, fill='#00d400', font=imgfont) confidence_avg = confidence_avg/len(response['FaceMatches']) attendees += [str(name)] if name=='Thanos': print('Thanos is here.') else: print('{} Assembled with {} percent confidence.'.format(name,confidence_avg)) except: print("Something went wrong!") print('There are {} total Avengers Assembled against Thanos.'.format(len(all_faces)-1)) image.save(filename, "JPEG") image.show() return attendees, filename if __name__ == "__main__": # Importing variables api_key = credentials.api_key baseurl = credentials.base_url org_id = credentials.organization_id networks = credentials.networks cams = credentials.cams students = student_list.student_list webex_email = credentials.webex_email webex_token = credentials.webex_token # Instantiate Meraki Python SDK Client dashboard = meraki.DashboardAPI( api_key=api_key, base_url=baseurl, log_file_prefix='./logs/attendance/', print_console=False) # Instantiate AWS Python SDK Clients # Must configure AWS CLI for this to work # See https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html rekognition = boto3.client('rekognition', region_name='us-east-2') dynamodb = boto3.client('dynamodb', region_name='us-east-2') webex = WebexTeamsAPI(access_token=webex_token) # Record timestamp for snapshot name timestr = time.strftime("%Y%m%d-%H%M%S") file_name = snapshot.snap( dashboard_api_client=dashboard, time_string=timestr, networkIds=networks, organizationId=org_id, cameras=cams, base_url=baseurl, folder='attendance') attendees, filename = attendance( rekognition_api_client=rekognition, dynamodb_api_client=dynamodb, filename = file_name) x = set(attendees) y = set(students) z = y.difference(x) # Generate Attendance Report filename = file_name body = "These are the Avengers who Assembled on {}.".format(date.today().isoformat()) body = body + "\n\nAssembled:\n{}".format(x) body = body + "\n\nDidn't Assemble:\n{}".format(z) print("Assembled: \n{}".format(x)) print("Didn't Assemble: \n{}".format(z)) webex.messages.create(toPersonEmail=webex_email, text=body, files=[filename])
en
0.692673
# Based off of https://aws.amazon.com/blogs/machine-learning/build-your-own-face-recognition-service-using-amazon-rekognition/ # Using Meraki Python SDK at https://github.com/meraki/dashboard-api-python # Open stored image and send to Rekognition #print('Detecting faces...') #image_crop.show() # Initialize averages # Importing variables # Instantiate Meraki Python SDK Client # Instantiate AWS Python SDK Clients # Must configure AWS CLI for this to work # See https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html # Record timestamp for snapshot name # Generate Attendance Report
2.929939
3
Python-Fundamentals/Functions/repeat_string.py
Xamaneone/SoftUni-Intro
0
6613698
<gh_stars>0 def output (): print(f"{string}", end="") string = input() n = int(input()) for i in range(0, n): output()
def output (): print(f"{string}", end="") string = input() n = int(input()) for i in range(0, n): output()
none
1
3.689647
4
HW4/AndriiBabii/2.py
kolyasalubov/Lv-677.PythonCore
0
6613699
element = [1, 234, 662, 19, 1213, 73, 77] number_of_elements = len(element) # Варіант ручного заповнення списку # number_of_elements = int(input("Input number of elements: ")) # for i in range(number_of_elements): # element.append(int(input(f"inpute {i} element: "))) for i in range(number_of_elements): element[i] = float(element[i]) print(element)
element = [1, 234, 662, 19, 1213, 73, 77] number_of_elements = len(element) # Варіант ручного заповнення списку # number_of_elements = int(input("Input number of elements: ")) # for i in range(number_of_elements): # element.append(int(input(f"inpute {i} element: "))) for i in range(number_of_elements): element[i] = float(element[i]) print(element)
uk
0.545378
# Варіант ручного заповнення списку # number_of_elements = int(input("Input number of elements: ")) # for i in range(number_of_elements): # element.append(int(input(f"inpute {i} element: ")))
3.995475
4
computer_network_real/9/dhcp.py
mtjin/University_and_AndroidProjects
1
6613700
<filename>computer_network_real/9/dhcp.py import socket import struct import subprocess import time from phue import Bridge def main(): raw_socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) my_macip = "d0b128275cf9" #hue bridge connect bridge = Bridge('192.168.0.218') bridge.connect() lights = bridge.lights #sniffing while True: recv_packet = raw_socket.recvfrom(5000) ethernet_protocol = struct.unpack('!6s6sH', (recv_packet[0])[:14])[2] if ethernet_protocol == 0x800: ip_protocol = struct.unpack('!BBHHHBBH4s4s', recv_packet[0][14:34])[6] if ip_protocol == 17: udp_src_port = struct.unpack('!H', (recv_packet[0])[34:34+2])[0] if udp_src_port == 68: packet_data = recv_packet[0][42:] #parsing phone mac ip come_macip = packet_data.hex()[56:68] print("Come MAC Ip => ", come_macip) if my_macip == come_macip: print("My MAC IP !!!!!!!!!!!") print(recv_packet[0][0:]) print("HEX DATA : ", recv_packet[0][0:].hex()[0:]) phone_ip = struct.unpack('!BBBB', (recv_packet[0])[296:300]) phone_ip = str(phone_ip[0])+ '.'+ str(phone_ip[1]) + '.' + str(phone_ip[2]) +'.' +str(phone_ip[3]) print("PHONE => " , phone_ip) while True: # 1 second sleep time.sleep(1) # ping to my phone ip that I parsed in packet status, result = subprocess.getstatusoutput("ping -c1 -w2 " + phone_ip) if status == 0: print('respone OK') lights[0].on = True lights[0].brightness = int(250) lights[0].xy = [float(0.9), float(0.9)] lights[1].on = True lights[1].brightness = int(250) lights[1].xy = [float(0.9), float(0.9)] lights[2].on = True lights[2].brightness = int(250) lights[2].xy = [float(0.9), float(0.9)] else : print("NOT respond") lights[0].on = False lights[0].brightness = int(0) lights[0].xy = [float(0.0), float(0.0)] lights[1].on = False lights[1].brightness = int(0) lights[1].xy = [float(0.0), float(0.0)] lights[2].on = False lights[2].brightness = int(0) lights[2].xy = [float(0.0), float(0.0)] break if __name__ == "__main__": main()
<filename>computer_network_real/9/dhcp.py import socket import struct import subprocess import time from phue import Bridge def main(): raw_socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003)) my_macip = "d0b128275cf9" #hue bridge connect bridge = Bridge('192.168.0.218') bridge.connect() lights = bridge.lights #sniffing while True: recv_packet = raw_socket.recvfrom(5000) ethernet_protocol = struct.unpack('!6s6sH', (recv_packet[0])[:14])[2] if ethernet_protocol == 0x800: ip_protocol = struct.unpack('!BBHHHBBH4s4s', recv_packet[0][14:34])[6] if ip_protocol == 17: udp_src_port = struct.unpack('!H', (recv_packet[0])[34:34+2])[0] if udp_src_port == 68: packet_data = recv_packet[0][42:] #parsing phone mac ip come_macip = packet_data.hex()[56:68] print("Come MAC Ip => ", come_macip) if my_macip == come_macip: print("My MAC IP !!!!!!!!!!!") print(recv_packet[0][0:]) print("HEX DATA : ", recv_packet[0][0:].hex()[0:]) phone_ip = struct.unpack('!BBBB', (recv_packet[0])[296:300]) phone_ip = str(phone_ip[0])+ '.'+ str(phone_ip[1]) + '.' + str(phone_ip[2]) +'.' +str(phone_ip[3]) print("PHONE => " , phone_ip) while True: # 1 second sleep time.sleep(1) # ping to my phone ip that I parsed in packet status, result = subprocess.getstatusoutput("ping -c1 -w2 " + phone_ip) if status == 0: print('respone OK') lights[0].on = True lights[0].brightness = int(250) lights[0].xy = [float(0.9), float(0.9)] lights[1].on = True lights[1].brightness = int(250) lights[1].xy = [float(0.9), float(0.9)] lights[2].on = True lights[2].brightness = int(250) lights[2].xy = [float(0.9), float(0.9)] else : print("NOT respond") lights[0].on = False lights[0].brightness = int(0) lights[0].xy = [float(0.0), float(0.0)] lights[1].on = False lights[1].brightness = int(0) lights[1].xy = [float(0.0), float(0.0)] lights[2].on = False lights[2].brightness = int(0) lights[2].xy = [float(0.0), float(0.0)] break if __name__ == "__main__": main()
en
0.85908
#hue bridge connect #sniffing #parsing phone mac ip # 1 second sleep # ping to my phone ip that I parsed in packet
2.773831
3
src/HABApp/core/lib/handler.py
DerOetzi/HABApp
44
6613701
from datetime import date, datetime from logging.handlers import RotatingFileHandler class MidnightRotatingFileHandler(RotatingFileHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.last_check: date = datetime.now().date() def shouldRollover(self, record): date = datetime.now().date() if date == self.last_check: return 0 self.last_check = date return super().shouldRollover(record)
from datetime import date, datetime from logging.handlers import RotatingFileHandler class MidnightRotatingFileHandler(RotatingFileHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.last_check: date = datetime.now().date() def shouldRollover(self, record): date = datetime.now().date() if date == self.last_check: return 0 self.last_check = date return super().shouldRollover(record)
none
1
3.053758
3
sales/tests/__init__.py
marcelomoraes28/real-state-marketplace
1
6613702
from django.test import TestCase from sales.models import AreaUnitModel, CityModel, HomeTypeModel, \ PriceHistoryModel, TaxModel, ResidenceModel, ZRentInformationModel, \ ZSaleInformationModel, ZillowModel, AnnouncementModel class BaseTestCase(TestCase): def setUp(self): self.import_data_payload = {'area_unit': 'SqFt', 'bathrooms': '2.0', 'bedrooms': '4', 'home_size': '1372', 'home_type': 'SingleFamily', 'last_sold_date': '', 'last_sold_price': '', 'link': 'https://www.zillow.com/homedetails/7417-Quimby-Ave-West-Hills-CA-91307/19866015_zpid/', 'price': '$739K', 'property_size': '10611', 'rent_price': '', 'rentzestimate_amount': '2850', 'rentzestimate_last_updated': '08/07/2018', 'tax_value': '215083.0', 'tax_year': '2017', 'year_built': '1956', 'zestimate_amount': '709630', 'zestimate_last_updated': '08/07/2018', 'zillow_id': '19866015', 'address': '7417 Quimby Ave', 'city': 'West Hills', 'state': 'CA', 'zipcode': '91307'} self.area_unit = AreaUnitModel.objects.create(name='Area 51') self.city = CityModel.objects.create(name='Curitiba', state='Parana') self.home_type = HomeTypeModel.objects.create(type='Apartment') self.price_history = PriceHistoryModel.objects.create(sell_price=1000000.00, rent_price=1000.00) self.tax = TaxModel.objects.create(tax_value=1240.00, tax_year=1992) self.residene = ResidenceModel.objects.create(city=self.city, area_unit=self.area_unit, address='R. Lothario Boutin 220', bathrooms=2.5, bedrooms=2, home_size=124, home_type=self.home_type, property_size=200, year_built=1994) self.z_rent_information = ZRentInformationModel.objects.create(rentzestimate_amount=100012.00) self.z_sale_information = ZSaleInformationModel.objects.create(zestimate_amount=99123.31) self.zillow = ZillowModel.objects.create(zillow_id=123, z_rent_information=self.z_rent_information, z_sale_information=self.z_sale_information) self.announcement = AnnouncementModel.objects.create( zillow=self.zillow, link='localhost:8000', residence=self.residene, tax=self.tax ) self.announcement.price_history.add(self.price_history)
from django.test import TestCase from sales.models import AreaUnitModel, CityModel, HomeTypeModel, \ PriceHistoryModel, TaxModel, ResidenceModel, ZRentInformationModel, \ ZSaleInformationModel, ZillowModel, AnnouncementModel class BaseTestCase(TestCase): def setUp(self): self.import_data_payload = {'area_unit': 'SqFt', 'bathrooms': '2.0', 'bedrooms': '4', 'home_size': '1372', 'home_type': 'SingleFamily', 'last_sold_date': '', 'last_sold_price': '', 'link': 'https://www.zillow.com/homedetails/7417-Quimby-Ave-West-Hills-CA-91307/19866015_zpid/', 'price': '$739K', 'property_size': '10611', 'rent_price': '', 'rentzestimate_amount': '2850', 'rentzestimate_last_updated': '08/07/2018', 'tax_value': '215083.0', 'tax_year': '2017', 'year_built': '1956', 'zestimate_amount': '709630', 'zestimate_last_updated': '08/07/2018', 'zillow_id': '19866015', 'address': '7417 Quimby Ave', 'city': 'West Hills', 'state': 'CA', 'zipcode': '91307'} self.area_unit = AreaUnitModel.objects.create(name='Area 51') self.city = CityModel.objects.create(name='Curitiba', state='Parana') self.home_type = HomeTypeModel.objects.create(type='Apartment') self.price_history = PriceHistoryModel.objects.create(sell_price=1000000.00, rent_price=1000.00) self.tax = TaxModel.objects.create(tax_value=1240.00, tax_year=1992) self.residene = ResidenceModel.objects.create(city=self.city, area_unit=self.area_unit, address='R. Lothario Boutin 220', bathrooms=2.5, bedrooms=2, home_size=124, home_type=self.home_type, property_size=200, year_built=1994) self.z_rent_information = ZRentInformationModel.objects.create(rentzestimate_amount=100012.00) self.z_sale_information = ZSaleInformationModel.objects.create(zestimate_amount=99123.31) self.zillow = ZillowModel.objects.create(zillow_id=123, z_rent_information=self.z_rent_information, z_sale_information=self.z_sale_information) self.announcement = AnnouncementModel.objects.create( zillow=self.zillow, link='localhost:8000', residence=self.residene, tax=self.tax ) self.announcement.price_history.add(self.price_history)
none
1
2.20943
2
lib/jnpr/healthbot/exception.py
minefuto/healthbot-py-client
10
6613703
class SchemaError(Exception): """ Generated in response to a invalid Schema type """ def __init__(self, schema): self._schema = schema def __repr__(self): return "Schema provided is not of {} type".format(self._schema) __str__ = __repr__ class NotFoundError(Exception): """ Generated in response to a invalid Schema type """ def __init__(self, detail): self.detail = detail.get('detail') self.status = detail.get('status') def __repr__(self): return "{}, {}".format(self.status, self.detail) __str__ = __repr__ class ConnectAuthError(Exception): """ Generated if the user-name, password is invalid """ def __init__(self, hbot, msg=None): self.hbot = hbot self._orig = msg def __repr__(self): if self._orig: return "{}(host: {}, msg: {})".format(self.__class__.__name__, self.hbot.server, self._orig) else: return "{}({})".format(self.__class__.__name__, self.hbot.server) __str__ = __repr__
class SchemaError(Exception): """ Generated in response to a invalid Schema type """ def __init__(self, schema): self._schema = schema def __repr__(self): return "Schema provided is not of {} type".format(self._schema) __str__ = __repr__ class NotFoundError(Exception): """ Generated in response to a invalid Schema type """ def __init__(self, detail): self.detail = detail.get('detail') self.status = detail.get('status') def __repr__(self): return "{}, {}".format(self.status, self.detail) __str__ = __repr__ class ConnectAuthError(Exception): """ Generated if the user-name, password is invalid """ def __init__(self, hbot, msg=None): self.hbot = hbot self._orig = msg def __repr__(self): if self._orig: return "{}(host: {}, msg: {})".format(self.__class__.__name__, self.hbot.server, self._orig) else: return "{}({})".format(self.__class__.__name__, self.hbot.server) __str__ = __repr__
en
0.788001
Generated in response to a invalid Schema type Generated in response to a invalid Schema type Generated if the user-name, password is invalid
3.084051
3
intentions/admin.py
gabecm/oit-project
0
6613704
from django.contrib import admin # Register your models here. from intentions.models import Prompt, Entry class PromptAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['prompt_text']}), ('Date Information', {'fields': ['date'], 'classes': ['collapse']}), ] list_display = ('prompt_text', 'date') list_filter = ['date'] search_fields = ['prompt_text'] class EntryAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['user', 'prompt', 'mood', 'headspace', 'prompt_response', 'public']}), ('Date Information', {'fields': ['date'], 'classes': ['collapse']}), ] list_display = ('user', 'prompt', 'mood', 'headspace', 'prompt_response', 'public') list_filter = ['date'] search_fields = ['user'] admin.site.register(Prompt, PromptAdmin) admin.site.register(Entry, EntryAdmin)
from django.contrib import admin # Register your models here. from intentions.models import Prompt, Entry class PromptAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['prompt_text']}), ('Date Information', {'fields': ['date'], 'classes': ['collapse']}), ] list_display = ('prompt_text', 'date') list_filter = ['date'] search_fields = ['prompt_text'] class EntryAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['user', 'prompt', 'mood', 'headspace', 'prompt_response', 'public']}), ('Date Information', {'fields': ['date'], 'classes': ['collapse']}), ] list_display = ('user', 'prompt', 'mood', 'headspace', 'prompt_response', 'public') list_filter = ['date'] search_fields = ['user'] admin.site.register(Prompt, PromptAdmin) admin.site.register(Entry, EntryAdmin)
en
0.968259
# Register your models here.
1.87547
2
script_final/train_ext.py
zhaoxueyan1/2018DSB
97
6613705
# -*- coding: utf-8 -*- """ Created on Tue Jan 30 09:45:21 2018 @author: Jackie """ import numpy as np import pandas as pd from load import load_from_cache, save_to_cache, makefolder from model_ms1 import generator_1s_v11 as generator_1s from model_rcnn_weight import UnetRCNN from params import DsbConfig from generator import data_generator_multi def train_generator(config, shuffle = False, augment=False): isbi = load_from_cache('2009isbi_256') weebly = load_from_cache('weebly_256') tnbc = load_from_cache('TNBC_256') train = load_from_cache('train_final_df') gen_isbi = data_generator_multi(np.stack(isbi['image'],0), np.stack(isbi['mask'], 0), config, shuffle=shuffle, augment=augment, batch_size=1, tp_value=7) gen_weebly = data_generator_multi(np.stack(weebly['image'],0), np.stack(weebly['mask'], 0), config, shuffle=shuffle, augment=augment, batch_size=1) gen_tnbc = data_generator_multi(np.stack(tnbc['image'],0), np.stack(tnbc['mask'], 0), config, shuffle=shuffle, augment=augment, batch_size=1) gen_train = data_generator_multi(np.stack(train['image'],0), np.stack(train['mask'], 0), config, shuffle=shuffle, augment=augment, batch_size=1) images = np.zeros((config.BATCH_SIZE,)+tuple(config.IMAGE_SHAPE), dtype='float32') masks = np.zeros((config.BATCH_SIZE,)+tuple(config.IMAGE_SHAPE[:2]), dtype='int32') while True: for nb, gen in enumerate([gen_isbi, gen_weebly, gen_tnbc, gen_train]): image, mask = next(gen) images[nb] = image[0] masks[nb] = mask[0] yield images, masks def train_1s(): config = DsbConfig() tp, unet_ratio, opt = 'all', 1, 'sgd' save_dir = makefolder('..//cache//UnetRCNN',tosecond=True) weight_fl = '../cache/mask_rcnn_coco.h5' valid_df = load_from_cache('valid_df') valid_images = np.stack(valid_df['image'], 0) valid_masks = np.stack(valid_df['mask'], 0) #print(len(valid_masks)) model = UnetRCNN(tp, unet_ratio, opt, config, save_dir) model.load_weights(weight_fl, by_name =True) train_gen = train_generator(config, shuffle = True, augment= True) tr_ms1 = generator_1s(train_gen,config, tp) val_generator = data_generator_multi(valid_images, valid_masks, config, shuffle = False, augment= False) val_ms1= generator_1s(val_generator,config, tp) #model.train_generator(tr_ms1, val_ms1, 1e-2, 1, 'head') model.train_generator(tr_ms1, val_ms1, 1e-3, 100, 'all') if __name__ == "__main__": train_1s()
# -*- coding: utf-8 -*- """ Created on Tue Jan 30 09:45:21 2018 @author: Jackie """ import numpy as np import pandas as pd from load import load_from_cache, save_to_cache, makefolder from model_ms1 import generator_1s_v11 as generator_1s from model_rcnn_weight import UnetRCNN from params import DsbConfig from generator import data_generator_multi def train_generator(config, shuffle = False, augment=False): isbi = load_from_cache('2009isbi_256') weebly = load_from_cache('weebly_256') tnbc = load_from_cache('TNBC_256') train = load_from_cache('train_final_df') gen_isbi = data_generator_multi(np.stack(isbi['image'],0), np.stack(isbi['mask'], 0), config, shuffle=shuffle, augment=augment, batch_size=1, tp_value=7) gen_weebly = data_generator_multi(np.stack(weebly['image'],0), np.stack(weebly['mask'], 0), config, shuffle=shuffle, augment=augment, batch_size=1) gen_tnbc = data_generator_multi(np.stack(tnbc['image'],0), np.stack(tnbc['mask'], 0), config, shuffle=shuffle, augment=augment, batch_size=1) gen_train = data_generator_multi(np.stack(train['image'],0), np.stack(train['mask'], 0), config, shuffle=shuffle, augment=augment, batch_size=1) images = np.zeros((config.BATCH_SIZE,)+tuple(config.IMAGE_SHAPE), dtype='float32') masks = np.zeros((config.BATCH_SIZE,)+tuple(config.IMAGE_SHAPE[:2]), dtype='int32') while True: for nb, gen in enumerate([gen_isbi, gen_weebly, gen_tnbc, gen_train]): image, mask = next(gen) images[nb] = image[0] masks[nb] = mask[0] yield images, masks def train_1s(): config = DsbConfig() tp, unet_ratio, opt = 'all', 1, 'sgd' save_dir = makefolder('..//cache//UnetRCNN',tosecond=True) weight_fl = '../cache/mask_rcnn_coco.h5' valid_df = load_from_cache('valid_df') valid_images = np.stack(valid_df['image'], 0) valid_masks = np.stack(valid_df['mask'], 0) #print(len(valid_masks)) model = UnetRCNN(tp, unet_ratio, opt, config, save_dir) model.load_weights(weight_fl, by_name =True) train_gen = train_generator(config, shuffle = True, augment= True) tr_ms1 = generator_1s(train_gen,config, tp) val_generator = data_generator_multi(valid_images, valid_masks, config, shuffle = False, augment= False) val_ms1= generator_1s(val_generator,config, tp) #model.train_generator(tr_ms1, val_ms1, 1e-2, 1, 'head') model.train_generator(tr_ms1, val_ms1, 1e-3, 100, 'all') if __name__ == "__main__": train_1s()
en
0.323118
# -*- coding: utf-8 -*- Created on Tue Jan 30 09:45:21 2018 @author: Jackie #print(len(valid_masks)) #model.train_generator(tr_ms1, val_ms1, 1e-2, 1, 'head')
2.014943
2
simple_curses/window.py
robertblackwell/simple_curses
0
6613706
import curses from simple_curses.kurses_ex import * def newwin_inside(hostwin, h, w, y, x): """ Create a new curses window that is fully inside the host window :param hostwin : curses.win :param h : non neg int Height of new window :param w : non neg int Width of new window :param y : starting row of new window within host window (relative) :param x : starting column of new window within host (relative) """ ybeg, xbeg = hostwin.getbegyx() ymax, xmax = hostwin.getmaxyx() win = curses.newwin(h, w, ybeg + y, xbeg + x) return win def newwin_after(prev_win, h, w, xstart, y_skip=1): """ Create a new curses window starting: - on the y_skip rows after the prev_win, - starting at absolute column xstart :param prev_win : curses.win :param h : non neg int Height of new window :param w : non neg int Width of new window :param y : starting row of new window within host window (relative) :param x : starting column of new window within host (relative) """ ybeg, xbeg = prev_win.getbegyx() ymax, xmax = prev_win.getmaxyx() win = curses.newwin(h, w, ybeg + ymax + y_skip - 1, xstart) return win def hline_after(prev_win, xstart=0): """ Create a new window on the next row after prev_win. The new window will be for a horizontal line and hence only needs to be 1 line high. To underline the previous window it is 2 cols wider than the pre_win :param prev_win: curses.win :param xstart : non neg int The starting absolute column for the hline, usually 1 less than prev_win.xbeg """ ybeg, xbeg = prev_win.getbegyx() ymax, xmax = prev_win.getmaxyx() win = curses.newwin(1, xmax+2, ybeg + ymax, xstart) return win def draw_hline(win): """ Draw a horizontal line startiing at position 0,0 in win and as wide as win """ win.border(0, 0, curses.ACS_HLINE, curses.ACS_HLINE, curses.ACS_LTEE, curses.ACS_RTEE, curses.ACS_LTEE, curses.ACS_RTEE) class Window: @staticmethod def mainwin(): pass def newwin(nbr_rows, nbr_cols, ybeg_abs, xbeg_abs): ymax, xmax = curses.stdscr.getbegyx() if nbr_rows > ymax or nbr_cols > xmax: raise ValueError("Window is bigger than stdscr") cwin = curses.newwin(nbr_rows, nbr_cols, ybeg_abs, xbeg_abs) w = Window(cwin) w.parent = curses.stdscr return w """Wrapper for curses.win in order to provide more diagnostics and a single bug fix""" def __init__(self, cwin, nbr_rows, nbr_cols, ybeg_abs, xbeg_abs): ymax, xmax = curses.stdscr.getbegyx() if nbr_rows > ymax or nbr_cols > xmax: raise ValueError("Window is bigger than stdscr") self.xbeg = xbeg_abs self.ybeg = ybeg_abs self.ymax = nbr_rows self.xmax = nbr_cols self.parent = None self.children = [] self.cwin = cwin def subwin(self, nbr_lines, nbr_cols, ybeg_rel, xbeg_rel): neww = make_subwin(self.cwin, nbr_lines, nbr_cols, ybeg_rel, xbeg_rel) csubwin = Window(csubwin, nbr_lines, nbr_cols, ybeg_rel, xbeg_rel) csubwin.parent = self return csubwin
import curses from simple_curses.kurses_ex import * def newwin_inside(hostwin, h, w, y, x): """ Create a new curses window that is fully inside the host window :param hostwin : curses.win :param h : non neg int Height of new window :param w : non neg int Width of new window :param y : starting row of new window within host window (relative) :param x : starting column of new window within host (relative) """ ybeg, xbeg = hostwin.getbegyx() ymax, xmax = hostwin.getmaxyx() win = curses.newwin(h, w, ybeg + y, xbeg + x) return win def newwin_after(prev_win, h, w, xstart, y_skip=1): """ Create a new curses window starting: - on the y_skip rows after the prev_win, - starting at absolute column xstart :param prev_win : curses.win :param h : non neg int Height of new window :param w : non neg int Width of new window :param y : starting row of new window within host window (relative) :param x : starting column of new window within host (relative) """ ybeg, xbeg = prev_win.getbegyx() ymax, xmax = prev_win.getmaxyx() win = curses.newwin(h, w, ybeg + ymax + y_skip - 1, xstart) return win def hline_after(prev_win, xstart=0): """ Create a new window on the next row after prev_win. The new window will be for a horizontal line and hence only needs to be 1 line high. To underline the previous window it is 2 cols wider than the pre_win :param prev_win: curses.win :param xstart : non neg int The starting absolute column for the hline, usually 1 less than prev_win.xbeg """ ybeg, xbeg = prev_win.getbegyx() ymax, xmax = prev_win.getmaxyx() win = curses.newwin(1, xmax+2, ybeg + ymax, xstart) return win def draw_hline(win): """ Draw a horizontal line startiing at position 0,0 in win and as wide as win """ win.border(0, 0, curses.ACS_HLINE, curses.ACS_HLINE, curses.ACS_LTEE, curses.ACS_RTEE, curses.ACS_LTEE, curses.ACS_RTEE) class Window: @staticmethod def mainwin(): pass def newwin(nbr_rows, nbr_cols, ybeg_abs, xbeg_abs): ymax, xmax = curses.stdscr.getbegyx() if nbr_rows > ymax or nbr_cols > xmax: raise ValueError("Window is bigger than stdscr") cwin = curses.newwin(nbr_rows, nbr_cols, ybeg_abs, xbeg_abs) w = Window(cwin) w.parent = curses.stdscr return w """Wrapper for curses.win in order to provide more diagnostics and a single bug fix""" def __init__(self, cwin, nbr_rows, nbr_cols, ybeg_abs, xbeg_abs): ymax, xmax = curses.stdscr.getbegyx() if nbr_rows > ymax or nbr_cols > xmax: raise ValueError("Window is bigger than stdscr") self.xbeg = xbeg_abs self.ybeg = ybeg_abs self.ymax = nbr_rows self.xmax = nbr_cols self.parent = None self.children = [] self.cwin = cwin def subwin(self, nbr_lines, nbr_cols, ybeg_rel, xbeg_rel): neww = make_subwin(self.cwin, nbr_lines, nbr_cols, ybeg_rel, xbeg_rel) csubwin = Window(csubwin, nbr_lines, nbr_cols, ybeg_rel, xbeg_rel) csubwin.parent = self return csubwin
en
0.837963
Create a new curses window that is fully inside the host window :param hostwin : curses.win :param h : non neg int Height of new window :param w : non neg int Width of new window :param y : starting row of new window within host window (relative) :param x : starting column of new window within host (relative) Create a new curses window starting: - on the y_skip rows after the prev_win, - starting at absolute column xstart :param prev_win : curses.win :param h : non neg int Height of new window :param w : non neg int Width of new window :param y : starting row of new window within host window (relative) :param x : starting column of new window within host (relative) Create a new window on the next row after prev_win. The new window will be for a horizontal line and hence only needs to be 1 line high. To underline the previous window it is 2 cols wider than the pre_win :param prev_win: curses.win :param xstart : non neg int The starting absolute column for the hline, usually 1 less than prev_win.xbeg Draw a horizontal line startiing at position 0,0 in win and as wide as win Wrapper for curses.win in order to provide more diagnostics and a single bug fix
3.857323
4
pca.py
scooter-dangle/MStream
69
6613707
<gh_stars>10-100 from sklearn.decomposition import PCA import numpy as np import time import argparse np.random.seed(0) # For reproducibility np.seterr(divide="ignore", invalid="ignore") parser = argparse.ArgumentParser(description="Training for MSTREAM-PCA") parser.add_argument("--dim", type=int, help="number of dimensions", default=12) parser.add_argument("--input", help="input file", required=True) parser.add_argument("--output", help="output file", default="pca.txt") parser.add_argument( "--numRecords", type=int, help="number of records for training", default=256 ) args = parser.parse_args() pca = PCA(n_components=args.dim) data = np.loadtxt(args.input, delimiter=",") mean, std = data.mean(0), data.std(0) new = (data - mean) / std new[:, std == 0] = 0 t = time.time() pca.fit(new[: args.numRecords]) new = pca.transform(new) print("Time for Training PCA is: ", time.time() - t) np.savetxt(args.output, new, delimiter=",", fmt="%.2f")
from sklearn.decomposition import PCA import numpy as np import time import argparse np.random.seed(0) # For reproducibility np.seterr(divide="ignore", invalid="ignore") parser = argparse.ArgumentParser(description="Training for MSTREAM-PCA") parser.add_argument("--dim", type=int, help="number of dimensions", default=12) parser.add_argument("--input", help="input file", required=True) parser.add_argument("--output", help="output file", default="pca.txt") parser.add_argument( "--numRecords", type=int, help="number of records for training", default=256 ) args = parser.parse_args() pca = PCA(n_components=args.dim) data = np.loadtxt(args.input, delimiter=",") mean, std = data.mean(0), data.std(0) new = (data - mean) / std new[:, std == 0] = 0 t = time.time() pca.fit(new[: args.numRecords]) new = pca.transform(new) print("Time for Training PCA is: ", time.time() - t) np.savetxt(args.output, new, delimiter=",", fmt="%.2f")
en
0.324069
# For reproducibility
3.067987
3
test/time/test_dateUtils.py
liangjz92/zeroinger-utils-python
0
6613708
<reponame>liangjz92/zeroinger-utils-python<filename>test/time/test_dateUtils.py<gh_stars>0 from unittest import TestCase from logzero import logger from zeroinger.time.dateutils import DateUtils from datetime import datetime class TestDateUtils(TestCase): def test_now(self): now_act = DateUtils.now() now_gold = datetime.now() str_act = now_act.strftime('%Y-%m-%d %H:%M:%S') str_gold = now_gold.strftime('%Y-%m-%d %H:%M:%S') self.assertEqual(str_act, str_gold, "获取当前时间错误") def test_date2str(self): now = datetime.now().replace(2019, 12, 2, 3, 4, 5, 678000) self.assertEqual('2019-12-02 03:04:05.678', DateUtils.date2str(now)) self.assertEqual('20191202 03:04:05 678', DateUtils.date2str(now, "YYYYMMDD HH:mm:ss SSS")) def test_str2date(self): self.assertEqual('2019-12-02 03:04:05.678', DateUtils.date2str(DateUtils.str2date('2019-12-02 03:04:05.678'))) pass # self.fail() def test_of(self): a = DateUtils.of(2019, 1, 2, 3, 4, 5, 6, 7) self.assertEqual('2019-01-02 03:04:05.006', DateUtils.date2str(a)) b = DateUtils.of(None, None, None, None, 4, None, 6, 7) c = datetime.now().replace(minute=4, microsecond=6000) self.assertEqual(DateUtils.date2str(c), DateUtils.date2str(b)) logger.info('{}-{}'.format(DateUtils.date2str(c), DateUtils.date2str(b))) # self.fail() def test_set(self): pass # self.fail() def test_add_time(self): a = DateUtils.of(2019, 1, 2, 3, 4, 5, 6, 7) b = DateUtils.add_time(a, -1, 1, 1, 1, 1, 1, 1, 1) logger.info('test_add_time|{}|{}'.format(DateUtils.date2str(a), DateUtils.date2str(b))) self.assertEqual('2018-02-03 04:05:06.007', DateUtils.date2str(b)) def test_time_delta_with_diff_unit(self): start = DateUtils.of(2019, 1, 2, 3, 4, 5, 6, 7) end = DateUtils.of(2020, 2, 2, 4, 4, 6, 7, 8) logger.info('时间差{}'.format(DateUtils.time_delta_with_diff_unit(end, start))) # self.fail() # def test_time_diff_by(self): # self.fail()
from unittest import TestCase from logzero import logger from zeroinger.time.dateutils import DateUtils from datetime import datetime class TestDateUtils(TestCase): def test_now(self): now_act = DateUtils.now() now_gold = datetime.now() str_act = now_act.strftime('%Y-%m-%d %H:%M:%S') str_gold = now_gold.strftime('%Y-%m-%d %H:%M:%S') self.assertEqual(str_act, str_gold, "获取当前时间错误") def test_date2str(self): now = datetime.now().replace(2019, 12, 2, 3, 4, 5, 678000) self.assertEqual('2019-12-02 03:04:05.678', DateUtils.date2str(now)) self.assertEqual('20191202 03:04:05 678', DateUtils.date2str(now, "YYYYMMDD HH:mm:ss SSS")) def test_str2date(self): self.assertEqual('2019-12-02 03:04:05.678', DateUtils.date2str(DateUtils.str2date('2019-12-02 03:04:05.678'))) pass # self.fail() def test_of(self): a = DateUtils.of(2019, 1, 2, 3, 4, 5, 6, 7) self.assertEqual('2019-01-02 03:04:05.006', DateUtils.date2str(a)) b = DateUtils.of(None, None, None, None, 4, None, 6, 7) c = datetime.now().replace(minute=4, microsecond=6000) self.assertEqual(DateUtils.date2str(c), DateUtils.date2str(b)) logger.info('{}-{}'.format(DateUtils.date2str(c), DateUtils.date2str(b))) # self.fail() def test_set(self): pass # self.fail() def test_add_time(self): a = DateUtils.of(2019, 1, 2, 3, 4, 5, 6, 7) b = DateUtils.add_time(a, -1, 1, 1, 1, 1, 1, 1, 1) logger.info('test_add_time|{}|{}'.format(DateUtils.date2str(a), DateUtils.date2str(b))) self.assertEqual('2018-02-03 04:05:06.007', DateUtils.date2str(b)) def test_time_delta_with_diff_unit(self): start = DateUtils.of(2019, 1, 2, 3, 4, 5, 6, 7) end = DateUtils.of(2020, 2, 2, 4, 4, 6, 7, 8) logger.info('时间差{}'.format(DateUtils.time_delta_with_diff_unit(end, start))) # self.fail() # def test_time_diff_by(self): # self.fail()
en
0.325057
# self.fail() # self.fail() # self.fail() # self.fail() # def test_time_diff_by(self): # self.fail()
2.967917
3
rule_engine/rule_executor.py
CUrW-SL/DSS-Framework
0
6613709
import sys sys.path.insert(0, '/home/curw/git/DSS-Framework/gen_util') from controller_util import is_matched def get_next_pump_configurations(dss_adapter, routines): dag_info = [] success_routines = evaluate_configuration_logics(dss_adapter, routines) if len(success_routines) > 0: for success_routine in success_routines: dag_name = success_routine['dag_name'] payload = success_routine dag_info.append({'dag_name': dag_name, 'payload': payload}) else: print('No triggering_pump_dags found.') return dag_info # ((location_name='Yakbedda') and (variable_type='WaterLevel') and ((current_water_level>=alert_water_level) or (current_water_level>=warning_water_level))) # or # ((location_name='Kohuwala') and (variable_type='Precipitation') and ((rainfall_intensity>=65.4) or ((last_1_day_rainfall>=150) and (last_3_day_rainfall>=420)))) def evaluate_configuration_logics(dss_adapter, routines): print('evaluate_configuration_logics|routines : ', routines) passed_routines = [] for routine in routines: rule_logic = routine['rule_logic'] if is_matched(rule_logic): print('evaluate_configuration_logics|rule_logic : ', rule_logic) location_names = dss_adapter.evaluate_variable_rule_logic(rule_logic) if location_names is not None and len(location_names) > 0: passed_routines.append(routine) print('evaluate_configuration_logics|passed_routines : ', passed_routines) return passed_routines
import sys sys.path.insert(0, '/home/curw/git/DSS-Framework/gen_util') from controller_util import is_matched def get_next_pump_configurations(dss_adapter, routines): dag_info = [] success_routines = evaluate_configuration_logics(dss_adapter, routines) if len(success_routines) > 0: for success_routine in success_routines: dag_name = success_routine['dag_name'] payload = success_routine dag_info.append({'dag_name': dag_name, 'payload': payload}) else: print('No triggering_pump_dags found.') return dag_info # ((location_name='Yakbedda') and (variable_type='WaterLevel') and ((current_water_level>=alert_water_level) or (current_water_level>=warning_water_level))) # or # ((location_name='Kohuwala') and (variable_type='Precipitation') and ((rainfall_intensity>=65.4) or ((last_1_day_rainfall>=150) and (last_3_day_rainfall>=420)))) def evaluate_configuration_logics(dss_adapter, routines): print('evaluate_configuration_logics|routines : ', routines) passed_routines = [] for routine in routines: rule_logic = routine['rule_logic'] if is_matched(rule_logic): print('evaluate_configuration_logics|rule_logic : ', rule_logic) location_names = dss_adapter.evaluate_variable_rule_logic(rule_logic) if location_names is not None and len(location_names) > 0: passed_routines.append(routine) print('evaluate_configuration_logics|passed_routines : ', passed_routines) return passed_routines
en
0.477423
# ((location_name='Yakbedda') and (variable_type='WaterLevel') and ((current_water_level>=alert_water_level) or (current_water_level>=warning_water_level))) # or # ((location_name='Kohuwala') and (variable_type='Precipitation') and ((rainfall_intensity>=65.4) or ((last_1_day_rainfall>=150) and (last_3_day_rainfall>=420))))
2.285129
2
TexturaPedra.py
rodrigomb13/CG
0
6613710
<filename>TexturaPedra.py import OpenGL.GLUT as GLUT import OpenGL.GLU as GLU import OpenGL.GL as GL import png from sys import argv from math import sin, cos, pi a = 90.0 b = 0 da = 0.5 background_color = (0.184, 0.211, 0.250, 1) # variaveis altura = 3 vertices = 3 raio = 2 modificador = 0.5 #texture = [] def loadtextures(): global texture texture = GL.glGenTextures(2) reader = png.Reader(filename='textura.png') w, h, pixels, metadata = reader.read_flat() if(metadata['alpha']): modo = GL.GL_RGBA else: modo = GL.GL_RGB GL.glBindTexture(GL.GL_TEXTURE_2D, texture[0]) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL.GL_UNSIGNED_BYTE, pixels.tolist()) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL) def figura(): polygon_points = [] faces_angle = (2*pi)/vertices GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glLoadIdentity() GL.glPushMatrix() GL.glTranslatef(0.0, 1.5, -10) GL.glRotatef(90,1.0,0.0,0.0) # Rotation # X axis GL.glRotatef(a, 0.0, 0.0, 1.0) # Y axis GL.glRotatef(b, 0.0, 1.0, 0.0) # Figura GL.glBindTexture(GL.GL_TEXTURE_2D, texture[0]) # base GL.glBegin(GL.GL_POLYGON) for i in range(vertices): x = raio * cos(i*faces_angle) y = raio * sin(i*faces_angle) polygon_points += [ (x,y) ] GL.glTexCoord2f(x, y); GL.glVertex3f(x,y,0.0) GL.glEnd() # topo GL.glBegin(GL.GL_POLYGON) for x,y in polygon_points: GL.glTexCoord2f(x, y); GL.glVertex3f(modificador*x,modificador*y, altura) GL.glEnd() # GL.glBegin(GL.GL_QUADS) for i in range(vertices): GL.glTexCoord2f(0.0, 0.0); GL.glVertex3f(polygon_points[i][0],polygon_points[i][1],0) GL.glTexCoord2f(0.0, 1.0); GL.glVertex3f(modificador*polygon_points[i][0],modificador*polygon_points[i][1],altura) GL.glTexCoord2f(1.0, 1.0); GL.glVertex3f(modificador*polygon_points[(i+1)%vertices][0],modificador*polygon_points[(i+1)%vertices][1],altura) GL.glTexCoord2f(1.0, 0.0); GL.glVertex3f(polygon_points[(i+1)%vertices][0],polygon_points[(i+1)%vertices][1],0) GL.glEnd() GL.glPopMatrix() GLUT.glutSwapBuffers() def draw(): global a GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) figura() # Auto-Rotation a = a + da GLUT.glutSwapBuffers() def timer(i): GLUT.glutPostRedisplay() GLUT.glutTimerFunc(10, timer, 1) def main(): GLUT.glutInit(argv) GLUT.glutInitDisplayMode(GLUT.GLUT_DOUBLE | GLUT.GLUT_RGBA | GLUT.GLUT_DEPTH | GLUT.GLUT_MULTISAMPLE) screen_width = GLUT.glutGet(GLUT.GLUT_SCREEN_WIDTH) screen_height = GLUT.glutGet(GLUT.GLUT_SCREEN_HEIGHT) window_width = round(2 * screen_width / 3) window_height = round(2 * screen_height / 3) GLUT.glutInitWindowSize(window_width, window_height) GLUT.glutInitWindowPosition(round((screen_width - window_width) / 2), round((screen_height - window_height) / 2)) GLUT.glutCreateWindow("Tronco texturizado") GLUT.glutDisplayFunc(draw) loadtextures() GL.glEnable(GL.GL_MULTISAMPLE) GL.glEnable(GL.GL_DEPTH_TEST) GL.glEnable(GL.GL_TEXTURE_2D) GL.glClearColor(*background_color) GL.glClearDepth(1.0) GL.glDepthFunc(GL.GL_LESS) GL.glShadeModel(GL.GL_SMOOTH) GL.glMatrixMode(GL.GL_PROJECTION) # Pre-render camera positioning GLU.gluPerspective(-45, window_width / window_height, 0.1, 100.0) GL.glTranslatef(0.0, 0.0, -10) GL.glMatrixMode(GL.GL_MODELVIEW) GLUT.glutTimerFunc(10, timer, 1) GLUT.glutMainLoop() if(__name__ == '__main__'): main()
<filename>TexturaPedra.py import OpenGL.GLUT as GLUT import OpenGL.GLU as GLU import OpenGL.GL as GL import png from sys import argv from math import sin, cos, pi a = 90.0 b = 0 da = 0.5 background_color = (0.184, 0.211, 0.250, 1) # variaveis altura = 3 vertices = 3 raio = 2 modificador = 0.5 #texture = [] def loadtextures(): global texture texture = GL.glGenTextures(2) reader = png.Reader(filename='textura.png') w, h, pixels, metadata = reader.read_flat() if(metadata['alpha']): modo = GL.GL_RGBA else: modo = GL.GL_RGB GL.glBindTexture(GL.GL_TEXTURE_2D, texture[0]) GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, modo, w, h, 0, modo, GL.GL_UNSIGNED_BYTE, pixels.tolist()) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST) GL.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL) def figura(): polygon_points = [] faces_angle = (2*pi)/vertices GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glLoadIdentity() GL.glPushMatrix() GL.glTranslatef(0.0, 1.5, -10) GL.glRotatef(90,1.0,0.0,0.0) # Rotation # X axis GL.glRotatef(a, 0.0, 0.0, 1.0) # Y axis GL.glRotatef(b, 0.0, 1.0, 0.0) # Figura GL.glBindTexture(GL.GL_TEXTURE_2D, texture[0]) # base GL.glBegin(GL.GL_POLYGON) for i in range(vertices): x = raio * cos(i*faces_angle) y = raio * sin(i*faces_angle) polygon_points += [ (x,y) ] GL.glTexCoord2f(x, y); GL.glVertex3f(x,y,0.0) GL.glEnd() # topo GL.glBegin(GL.GL_POLYGON) for x,y in polygon_points: GL.glTexCoord2f(x, y); GL.glVertex3f(modificador*x,modificador*y, altura) GL.glEnd() # GL.glBegin(GL.GL_QUADS) for i in range(vertices): GL.glTexCoord2f(0.0, 0.0); GL.glVertex3f(polygon_points[i][0],polygon_points[i][1],0) GL.glTexCoord2f(0.0, 1.0); GL.glVertex3f(modificador*polygon_points[i][0],modificador*polygon_points[i][1],altura) GL.glTexCoord2f(1.0, 1.0); GL.glVertex3f(modificador*polygon_points[(i+1)%vertices][0],modificador*polygon_points[(i+1)%vertices][1],altura) GL.glTexCoord2f(1.0, 0.0); GL.glVertex3f(polygon_points[(i+1)%vertices][0],polygon_points[(i+1)%vertices][1],0) GL.glEnd() GL.glPopMatrix() GLUT.glutSwapBuffers() def draw(): global a GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) figura() # Auto-Rotation a = a + da GLUT.glutSwapBuffers() def timer(i): GLUT.glutPostRedisplay() GLUT.glutTimerFunc(10, timer, 1) def main(): GLUT.glutInit(argv) GLUT.glutInitDisplayMode(GLUT.GLUT_DOUBLE | GLUT.GLUT_RGBA | GLUT.GLUT_DEPTH | GLUT.GLUT_MULTISAMPLE) screen_width = GLUT.glutGet(GLUT.GLUT_SCREEN_WIDTH) screen_height = GLUT.glutGet(GLUT.GLUT_SCREEN_HEIGHT) window_width = round(2 * screen_width / 3) window_height = round(2 * screen_height / 3) GLUT.glutInitWindowSize(window_width, window_height) GLUT.glutInitWindowPosition(round((screen_width - window_width) / 2), round((screen_height - window_height) / 2)) GLUT.glutCreateWindow("Tronco texturizado") GLUT.glutDisplayFunc(draw) loadtextures() GL.glEnable(GL.GL_MULTISAMPLE) GL.glEnable(GL.GL_DEPTH_TEST) GL.glEnable(GL.GL_TEXTURE_2D) GL.glClearColor(*background_color) GL.glClearDepth(1.0) GL.glDepthFunc(GL.GL_LESS) GL.glShadeModel(GL.GL_SMOOTH) GL.glMatrixMode(GL.GL_PROJECTION) # Pre-render camera positioning GLU.gluPerspective(-45, window_width / window_height, 0.1, 100.0) GL.glTranslatef(0.0, 0.0, -10) GL.glMatrixMode(GL.GL_MODELVIEW) GLUT.glutTimerFunc(10, timer, 1) GLUT.glutMainLoop() if(__name__ == '__main__'): main()
en
0.64151
# variaveis #texture = [] # Rotation # X axis # Y axis # Figura # base # topo # # Auto-Rotation # Pre-render camera positioning
2.621208
3
example_script.py
piccolo-orm/targ
12
6613711
import asyncio import decimal import typing as t from targ import CLI def echo(message: str): """ Echo back the message. :param message: What will be printed out. """ print(message) def add(a: int, b: int): """ Add the two numbers. :param a: The first number. :param b: The second number. """ print(a + b) def say_hello(name: str, greeting: str = "hello"): """ Greet someone. Example usage on the command line: say_hello daniel --greeting='bonjour' >>> bonjour daniel :param name: The person to greet. :param greeting: What to say to the person. """ print(f"{greeting} {name}") # print_address --number=1 --street="Royal Avenue" --postcode="XYZ 123" # --city=London def print_address( number: int, street: str, postcode: str, city: t.Optional[str] = None ): """ Print out the full address. :param number: House number, e.g. 8 :street: Street name, e.g. "Royal Avenue" :postcode: e.g. "XYZ 123" :city: e.g. London """ address = f"{number} {street}" if city is not None: address += f", {city}" address += f", {postcode}" print(address) def print_pi(precise: bool = False): """ Print out the digits of Pi. :param precise: If set, then more digits are printed out. """ if precise: print("3.14159265") else: print("3.14") def compound_interest(interest_rate: float, years: int): """ Work out the compound interest over the given number of years. :param interest_rate: The annual interest rate e.g. 0.05 :param years: The number of years over which to compound. """ print(((interest_rate + 1) ** years) - 1) def compound_interest_decimal(interest_rate: decimal.Decimal, years: int): """ Work out the compound interest over the given number of years. :param interest_rate: The annual interest rate e.g. 0.05 :param years: The number of years over which to compound. """ print(((interest_rate + 1) ** years) - 1) def create(username: str): """ Create a new user. :param username: The new user's username. """ print(f"Creating {username}") async def timer(seconds: int): """ Countdown for a number of seconds. :param seconds: The number of seconds to countdown. """ print(f"Sleeping for {seconds}") await asyncio.sleep(seconds) print("Finished") if __name__ == "__main__": cli = CLI() cli.register(say_hello) cli.register(echo) cli.register(add, aliases=["+"]) cli.register(print_pi) cli.register(compound_interest) cli.register(compound_interest_decimal) cli.register(create, group_name="user") cli.register(timer) cli.register(add, command_name="sum") cli.register(print_address) cli.run()
import asyncio import decimal import typing as t from targ import CLI def echo(message: str): """ Echo back the message. :param message: What will be printed out. """ print(message) def add(a: int, b: int): """ Add the two numbers. :param a: The first number. :param b: The second number. """ print(a + b) def say_hello(name: str, greeting: str = "hello"): """ Greet someone. Example usage on the command line: say_hello daniel --greeting='bonjour' >>> bonjour daniel :param name: The person to greet. :param greeting: What to say to the person. """ print(f"{greeting} {name}") # print_address --number=1 --street="Royal Avenue" --postcode="XYZ 123" # --city=London def print_address( number: int, street: str, postcode: str, city: t.Optional[str] = None ): """ Print out the full address. :param number: House number, e.g. 8 :street: Street name, e.g. "Royal Avenue" :postcode: e.g. "XYZ 123" :city: e.g. London """ address = f"{number} {street}" if city is not None: address += f", {city}" address += f", {postcode}" print(address) def print_pi(precise: bool = False): """ Print out the digits of Pi. :param precise: If set, then more digits are printed out. """ if precise: print("3.14159265") else: print("3.14") def compound_interest(interest_rate: float, years: int): """ Work out the compound interest over the given number of years. :param interest_rate: The annual interest rate e.g. 0.05 :param years: The number of years over which to compound. """ print(((interest_rate + 1) ** years) - 1) def compound_interest_decimal(interest_rate: decimal.Decimal, years: int): """ Work out the compound interest over the given number of years. :param interest_rate: The annual interest rate e.g. 0.05 :param years: The number of years over which to compound. """ print(((interest_rate + 1) ** years) - 1) def create(username: str): """ Create a new user. :param username: The new user's username. """ print(f"Creating {username}") async def timer(seconds: int): """ Countdown for a number of seconds. :param seconds: The number of seconds to countdown. """ print(f"Sleeping for {seconds}") await asyncio.sleep(seconds) print("Finished") if __name__ == "__main__": cli = CLI() cli.register(say_hello) cli.register(echo) cli.register(add, aliases=["+"]) cli.register(print_pi) cli.register(compound_interest) cli.register(compound_interest_decimal) cli.register(create, group_name="user") cli.register(timer) cli.register(add, command_name="sum") cli.register(print_address) cli.run()
en
0.756556
Echo back the message. :param message: What will be printed out. Add the two numbers. :param a: The first number. :param b: The second number. Greet someone. Example usage on the command line: say_hello daniel --greeting='bonjour' >>> bonjour daniel :param name: The person to greet. :param greeting: What to say to the person. # print_address --number=1 --street="Royal Avenue" --postcode="XYZ 123" # --city=London Print out the full address. :param number: House number, e.g. 8 :street: Street name, e.g. "Royal Avenue" :postcode: e.g. "XYZ 123" :city: e.g. London Print out the digits of Pi. :param precise: If set, then more digits are printed out. Work out the compound interest over the given number of years. :param interest_rate: The annual interest rate e.g. 0.05 :param years: The number of years over which to compound. Work out the compound interest over the given number of years. :param interest_rate: The annual interest rate e.g. 0.05 :param years: The number of years over which to compound. Create a new user. :param username: The new user's username. Countdown for a number of seconds. :param seconds: The number of seconds to countdown.
3.973352
4
multissh/utils.py
JaanPorkon/MultiSSH
0
6613712
from tldextract import tldextract def get_hostname(hostname): h_data = tldextract.extract(hostname) if h_data.subdomain: hostname = h_data.subdomain else: if h_data.registered_domain: hostname = h_data.registered_domain return hostname def print_str(message, str_type='info', hostname=None): if str_type == 'info': color = ConsoleColor.WHITE elif str_type == 'success': color = ConsoleColor.GREEN elif str_type == 'error': color = ConsoleColor.RED else: color = ConsoleColor.WHITE if hostname: print('%s[%s]: %s%s%s' % (ConsoleColor.HEADER, hostname, color, message, ConsoleColor.END)) else: print('%s%s%s' % (color, message, ConsoleColor.END)) def print_error(message, hostname=None): print_str(message, 'error', hostname) def print_success(message, hostname=None): print_str(message, 'success', hostname) def parse_credentials(data): data = data.split(',') if len(data) != 4: print_error('Invalid credential line: %s' % ','.join(data)) return False return { 'host': data[0], 'port': data[1], 'username': data[2], 'password': data[3] } def parse_response(response): lines = [] for line in response: line = line.strip() if line != '': lines.append(line) return '\n'.join(lines) def get_input(): return input('%s%s%s' % (ConsoleColor.GREEN, 'multissh$: ', ConsoleColor.END)).strip() class ConsoleColor: GREEN = '\033[92m' RED = '\033[91m' HEADER = '\033[95m' END = '\033[0m' WHITE = '\33[37m'
from tldextract import tldextract def get_hostname(hostname): h_data = tldextract.extract(hostname) if h_data.subdomain: hostname = h_data.subdomain else: if h_data.registered_domain: hostname = h_data.registered_domain return hostname def print_str(message, str_type='info', hostname=None): if str_type == 'info': color = ConsoleColor.WHITE elif str_type == 'success': color = ConsoleColor.GREEN elif str_type == 'error': color = ConsoleColor.RED else: color = ConsoleColor.WHITE if hostname: print('%s[%s]: %s%s%s' % (ConsoleColor.HEADER, hostname, color, message, ConsoleColor.END)) else: print('%s%s%s' % (color, message, ConsoleColor.END)) def print_error(message, hostname=None): print_str(message, 'error', hostname) def print_success(message, hostname=None): print_str(message, 'success', hostname) def parse_credentials(data): data = data.split(',') if len(data) != 4: print_error('Invalid credential line: %s' % ','.join(data)) return False return { 'host': data[0], 'port': data[1], 'username': data[2], 'password': data[3] } def parse_response(response): lines = [] for line in response: line = line.strip() if line != '': lines.append(line) return '\n'.join(lines) def get_input(): return input('%s%s%s' % (ConsoleColor.GREEN, 'multissh$: ', ConsoleColor.END)).strip() class ConsoleColor: GREEN = '\033[92m' RED = '\033[91m' HEADER = '\033[95m' END = '\033[0m' WHITE = '\33[37m'
none
1
2.770997
3
scripts/utils/camera.py
tmralmeida/tensorrt-yolov4
7
6613713
"""camera.py This code is a tiny and custom version of https://github.com/jkjung-avt/tensorrt_demos#yolov4 """ import cv2 import numpy as np import threading USB_GSTREAMER = True def add_camera_args(parser): """Add parser augment for camera options.""" parser.add_argument("--video_path", type = str, default = None, help = "use a video file as input") parser.add_argument("--image_path", type = str, default = None, help = "use an image file as input", required = False) parser.add_argument("--video_dev", type = int, default = None, help = "device number e.g.: 0", required = False) parser.add_argument("--width", dest="image_width", help = "image width value", default = 640, type = int) parser.add_argument("--height", dest="image_height", help = "image height value", default = 480, type = int) return parser def open_cam_usb(dev, width, height): """Open a USB webcam""" if USB_GSTREAMER: gst_str = ("v4l2src device=/dev/video{} ! " "video/x-raw, width=(int){}, height=(int){} ! " "videoconvert ! appsink").format(dev, width, height) return cv2.VideoCapture(gst_str, cv2.CAP_GSTREAMER) else: return cv2.VideoCapture(dev) def open_cam_onboard(width, height): """Open the Jetson onboard camera.""" gst_elements = str(subprocess.check_output('gst-inspect-1.0')) if 'nvcamerasrc' in gst_elements: # On versions of L4T prior to 28.1, you might need to add # 'flip-method=2' into gst_str below. gst_str = ('nvcamerasrc ! ' 'video/x-raw(memory:NVMM), ' 'width=(int)2592, height=(int)1458, ' 'format=(string)I420, framerate=(fraction)30/1 ! ' 'nvvidconv ! ' 'video/x-raw, width=(int){}, height=(int){}, ' 'format=(string)BGRx ! ' 'videoconvert ! appsink').format(width, height) elif 'nvarguscamerasrc' in gst_elements: gst_str = ('nvarguscamerasrc ! ' 'video/x-raw(memory:NVMM), ' 'width=(int)1920, height=(int)1080, ' 'format=(string)NV12, framerate=(fraction)30/1 ! ' 'nvvidconv flip-method=2 ! ' 'video/x-raw, width=(int){}, height=(int){}, ' 'format=(string)BGRx ! ' 'videoconvert ! appsink').format(width, height) else: raise RuntimeError('onboard camera source not found!') return cv2.VideoCapture(gst_str, cv2.CAP_GSTREAMER) def grab_img(cam): """This 'grab_img' function is designed to be run in the sub-thread. Once started, this thread continues to grab a new image and put it into the global 'img_handle', until 'thread_running' is set to False. """ while cam.thread_running: _, cam.img_handle = cam.cap.read() if cam.img_handle is None: logging.warning('grab_img(): cap.read() returns None...') break cam.thread_running = False class Camera(): """Camera class which supports reading images from theses video sources: 1. Video file 2. Image (jpg, png, etc.) file, repeating indefinitely 3. USB webcam 4. Jetson onboard camera """ def __init__(self, args): self.args = args self.is_opened = False self.use_thread = False self.thread_running = False self.img_handle = None self.img_width = 0 self.img_height = 0 self.cap = None self.thread = None def open(self): """Open camera based on command line arguments.""" assert self.cap is None, 'Camera is already opened!' args = self.args if args.video_path is not None: self.cap = cv2.VideoCapture(args.video_path) self.use_thread = False elif args.image_path is not None: self.cap = "OK" self.img_handle = cv2.imread(args.image_path) if self.img_handle is not None: self.is_opened = True self.img_height, self.img_width, _ = self.img_handle.shape self.use_thread = False elif args.video_dev is not None: self.cap = open_cam_usb( args.video_dev, args.image_width, args.image_height ) self.use_thread = True else: # by default, use the jetson onboard camera self.cap = open_cam_onboard( args.image_width, args.image_height ) self.use_thread = True if self.cap != "OK": if self.cap.isOpened(): _, img = self.cap.read() if img is not None: self.img_height, self.img_width, _ = img.shape self.is_opened = True def start(self): assert not self.thread_running if self.use_thread: self.thread_running = True self.thread = threading.Thread(target=grab_img, args=(self,)) self.thread.start() def stop(self): self.thread_running = False if self.use_thread: self.thread.join() def read(self): if self.args.video_path is not None: _, img = self.cap.read() if img is None: #logging.warning('grab_img(): cap.read() returns None...') # looping around self.cap.release() self.cap = cv2.VideoCapture(self.args.video_path) _, img = self.cap.read() return img elif self.args.image_path is not None: return np.copy(self.img_handle) else: return self.img_handle def release(self): assert not self.thread_running if self.cap != 'OK': self.cap.release()
"""camera.py This code is a tiny and custom version of https://github.com/jkjung-avt/tensorrt_demos#yolov4 """ import cv2 import numpy as np import threading USB_GSTREAMER = True def add_camera_args(parser): """Add parser augment for camera options.""" parser.add_argument("--video_path", type = str, default = None, help = "use a video file as input") parser.add_argument("--image_path", type = str, default = None, help = "use an image file as input", required = False) parser.add_argument("--video_dev", type = int, default = None, help = "device number e.g.: 0", required = False) parser.add_argument("--width", dest="image_width", help = "image width value", default = 640, type = int) parser.add_argument("--height", dest="image_height", help = "image height value", default = 480, type = int) return parser def open_cam_usb(dev, width, height): """Open a USB webcam""" if USB_GSTREAMER: gst_str = ("v4l2src device=/dev/video{} ! " "video/x-raw, width=(int){}, height=(int){} ! " "videoconvert ! appsink").format(dev, width, height) return cv2.VideoCapture(gst_str, cv2.CAP_GSTREAMER) else: return cv2.VideoCapture(dev) def open_cam_onboard(width, height): """Open the Jetson onboard camera.""" gst_elements = str(subprocess.check_output('gst-inspect-1.0')) if 'nvcamerasrc' in gst_elements: # On versions of L4T prior to 28.1, you might need to add # 'flip-method=2' into gst_str below. gst_str = ('nvcamerasrc ! ' 'video/x-raw(memory:NVMM), ' 'width=(int)2592, height=(int)1458, ' 'format=(string)I420, framerate=(fraction)30/1 ! ' 'nvvidconv ! ' 'video/x-raw, width=(int){}, height=(int){}, ' 'format=(string)BGRx ! ' 'videoconvert ! appsink').format(width, height) elif 'nvarguscamerasrc' in gst_elements: gst_str = ('nvarguscamerasrc ! ' 'video/x-raw(memory:NVMM), ' 'width=(int)1920, height=(int)1080, ' 'format=(string)NV12, framerate=(fraction)30/1 ! ' 'nvvidconv flip-method=2 ! ' 'video/x-raw, width=(int){}, height=(int){}, ' 'format=(string)BGRx ! ' 'videoconvert ! appsink').format(width, height) else: raise RuntimeError('onboard camera source not found!') return cv2.VideoCapture(gst_str, cv2.CAP_GSTREAMER) def grab_img(cam): """This 'grab_img' function is designed to be run in the sub-thread. Once started, this thread continues to grab a new image and put it into the global 'img_handle', until 'thread_running' is set to False. """ while cam.thread_running: _, cam.img_handle = cam.cap.read() if cam.img_handle is None: logging.warning('grab_img(): cap.read() returns None...') break cam.thread_running = False class Camera(): """Camera class which supports reading images from theses video sources: 1. Video file 2. Image (jpg, png, etc.) file, repeating indefinitely 3. USB webcam 4. Jetson onboard camera """ def __init__(self, args): self.args = args self.is_opened = False self.use_thread = False self.thread_running = False self.img_handle = None self.img_width = 0 self.img_height = 0 self.cap = None self.thread = None def open(self): """Open camera based on command line arguments.""" assert self.cap is None, 'Camera is already opened!' args = self.args if args.video_path is not None: self.cap = cv2.VideoCapture(args.video_path) self.use_thread = False elif args.image_path is not None: self.cap = "OK" self.img_handle = cv2.imread(args.image_path) if self.img_handle is not None: self.is_opened = True self.img_height, self.img_width, _ = self.img_handle.shape self.use_thread = False elif args.video_dev is not None: self.cap = open_cam_usb( args.video_dev, args.image_width, args.image_height ) self.use_thread = True else: # by default, use the jetson onboard camera self.cap = open_cam_onboard( args.image_width, args.image_height ) self.use_thread = True if self.cap != "OK": if self.cap.isOpened(): _, img = self.cap.read() if img is not None: self.img_height, self.img_width, _ = img.shape self.is_opened = True def start(self): assert not self.thread_running if self.use_thread: self.thread_running = True self.thread = threading.Thread(target=grab_img, args=(self,)) self.thread.start() def stop(self): self.thread_running = False if self.use_thread: self.thread.join() def read(self): if self.args.video_path is not None: _, img = self.cap.read() if img is None: #logging.warning('grab_img(): cap.read() returns None...') # looping around self.cap.release() self.cap = cv2.VideoCapture(self.args.video_path) _, img = self.cap.read() return img elif self.args.image_path is not None: return np.copy(self.img_handle) else: return self.img_handle def release(self): assert not self.thread_running if self.cap != 'OK': self.cap.release()
en
0.797078
camera.py This code is a tiny and custom version of https://github.com/jkjung-avt/tensorrt_demos#yolov4 Add parser augment for camera options. Open a USB webcam Open the Jetson onboard camera. # On versions of L4T prior to 28.1, you might need to add # 'flip-method=2' into gst_str below. This 'grab_img' function is designed to be run in the sub-thread. Once started, this thread continues to grab a new image and put it into the global 'img_handle', until 'thread_running' is set to False. Camera class which supports reading images from theses video sources: 1. Video file 2. Image (jpg, png, etc.) file, repeating indefinitely 3. USB webcam 4. Jetson onboard camera Open camera based on command line arguments. # by default, use the jetson onboard camera #logging.warning('grab_img(): cap.read() returns None...') # looping around
2.818461
3
forms.py
Abdulaziz-Hassan/todolist-website
0
6613714
<filename>forms.py from flask_wtf import FlaskForm, RecaptchaField from wtforms import StringField, SubmitField, PasswordField from wtforms.validators import DataRequired, Email, Length from flask_ckeditor import CKEditorField class RegisterForm(FlaskForm): name = StringField("Name", validators=[DataRequired()]) email = StringField("Email", validators=[DataRequired(), Email(message=f"Enter a valid email.")]) password = PasswordField("Password", validators=[DataRequired(), Length(min=6, max=35)]) recaptcha = RecaptchaField() submit = SubmitField("Register") class LoginForm(FlaskForm): email = StringField("Email", validators=[DataRequired()]) password = PasswordField("Password", validators=[DataRequired()]) submit = SubmitField("Log In") class TODOItemForm(FlaskForm): title = StringField("Title", validators=[DataRequired()]) description = CKEditorField("Todo item description") submit = SubmitField("Add") cancel = SubmitField("Cancel")
<filename>forms.py from flask_wtf import FlaskForm, RecaptchaField from wtforms import StringField, SubmitField, PasswordField from wtforms.validators import DataRequired, Email, Length from flask_ckeditor import CKEditorField class RegisterForm(FlaskForm): name = StringField("Name", validators=[DataRequired()]) email = StringField("Email", validators=[DataRequired(), Email(message=f"Enter a valid email.")]) password = PasswordField("Password", validators=[DataRequired(), Length(min=6, max=35)]) recaptcha = RecaptchaField() submit = SubmitField("Register") class LoginForm(FlaskForm): email = StringField("Email", validators=[DataRequired()]) password = PasswordField("Password", validators=[DataRequired()]) submit = SubmitField("Log In") class TODOItemForm(FlaskForm): title = StringField("Title", validators=[DataRequired()]) description = CKEditorField("Todo item description") submit = SubmitField("Add") cancel = SubmitField("Cancel")
none
1
2.71832
3
DLM.py
pbretz99/Slip-Detection
0
6613715
''' DLM Models and Relevant Functionality ''' # Libraries import numpy as np import matplotlib.pyplot as plt from numpy import pi, sin, cos from scipy.linalg import block_diag # Local Code from Utilities import load_data, check_shape, check_square from Matrix_Utilities import poly_mats, trig_mats, trig_inits class Results: def __init__(self): self.m = None self.C = None self.forecast = [] self.filter = [] self.innovation = [] self.obs_var = [] def append(self, ret): self.m = ret['m'] self.C = ret['C'] self.forecast.append(ret['forecast'][0,0]) self.filter.append(ret['filter'][0,0]) self.innovation.append(ret['innovation'][0,0]) self.obs_var.append(ret['obs_var'][0,0]) def point_estimate(self): return np.array(self.filter) def standardized_error(self): innovation = np.array(self.innovation) obs_var = np.array(self.obs_var) return innovation / np.sqrt(obs_var) class ResultsDiscount(Results): def __init__(self): super().__init__() self.alpha = [] self.beta = [] def append(self, ret): self.forecast.append(ret['forecast'][0,0]) self.filter.append(ret['filter'][0,0]) self.innovation.append(ret['innovation'][0,0]) self.obs_var.append(ret['obs_var'][0,0]) self.alpha.append(ret['alpha']) self.beta.append(ret['beta']) def var_point_estimate(self): alpha = np.array(self.alpha) beta = np.array(self.beta) return beta / (alpha - 1) # Filter a sample def filter_sample(Model, Data, init, final, set_init=True, discount_model=True, reset_to_zero=False): Temp_Model = Model.copy() if set_init: Temp_Model.m[0,0] = Data[init] if reset_to_zero: Temp_Model.m[0,0] = 0 if discount_model: results = ResultsDiscount() else: results = Results() for t in range(init, final): ret = Temp_Model.filter(Data[t], return_results=True) results.append(ret) return results # DLM parent class class DLM: def __init__(self, m, C, G, F, W, V): # State self.m = check_shape(m) self.C = check_square(C) # Forecast matrix self.G = check_square(G) self.G_T = np.transpose(check_shape(G)) # Observation matrix self.F = check_shape(F, column=False) self.F_T = np.transpose(check_shape(F, column=False)) # Forecast covariance self.W = check_square(W) # Observation covariance self.V = check_square(V) def copy(self): return DLM(self.m, self.C, self.G, self.F, self.W, self.V) def to_discount(self, df, alpha, beta): return DLMDiscount(self.m, self.C, self.G, self.F, df, alpha, beta) def add_model(self, M): # State self.m = np.concatenate((self.m, M.m)) self.C = block_diag(self.C, M.C) # Forecast matrix self.G = block_diag(self.G, M.G) self.G_T = block_diag(self.G_T, M.G_T) # Observation matrix self.F = np.concatenate((self.F, M.F), axis=1) self.F_T = np.concatenate((self.F_T, M.F_T)) # Forecast covariance self.W = block_diag(self.W, M.W) # Observation covariance self.V = self.V + M.V def set_inits(self, results): self.m = results.m self.C = results.C def filter(self, z, return_results=False): # Forecast step self.m, self.C = self.forecast() # Data assimilation step ret = self.data_assimilation(z) self.m, self.C = ret['m'], ret['C'] if return_results: return ret def forecast(self): # Forecast distribution parameters m_forecast = np.dot(self.G, self.m) C_forecast = np.dot(self.G, np.dot(self.C, self.G_T)) + self.W return m_forecast, C_forecast def data_assimilation(self, obs): # Predictive distribution parameters f = np.dot(self.F, self.m) Q = np.dot(self.F, np.dot(self.C, self.F_T)) + self.V # Forecast error innovation = obs - f # Kalman gain K = self.K_gain(Q) # Assimilate data m_analysis = self.m + np.dot(K, innovation) C_analysis = np.dot((np.identity(self.C.shape[0]) - np.dot(K, self.F)), self.C) ret = {'m': m_analysis, 'C': C_analysis} # Optional returns ret['forecast'] = f ret['filter'] = m_analysis ret['innovation'] = innovation ret['obs_var'] = Q return ret # Get Kalman Gain, given Q def K_gain(self, Q): Q_inv = np.linalg.inv(Q) K = np.dot(self.C, np.dot(self.F_T, Q_inv)) return K # Print attributes def print_model(self): text_G = '\nForecast Matrix G = \n' text_F = '\nObservation Matrix F = \n' text_W = '\nForecast Covariance W = \n' text_V = '\nObservation Covariance V = \n' print(text_G, self.G, text_F, self.F, text_W, self.W, text_V, self.V) # Polynomial model class DLMPoly(DLM): def __init__(self, m, C, W_list, V): G, F, W, V = poly_mats(W_list, V) super().__init__(m, C, G, F, W, V) # Periodic model class DLMTrig(DLM): def __init__(self, init_var, omega, q, trig_var, V): G, F, W, V = trig_mats(omega, q, trig_var, V) m, C = trig_inits(q, init_var) super().__init__(m, C, G, F, W, V) # Discount model class DLMDiscount(DLM): def __init__(self, m, C, G, F, df, alpha, beta): W = np.identity(C.shape[0]) V = np.array([[1]]) super().__init__(m, C, G, F, W, V) self.df = df self.alpha = alpha self.beta = beta def copy(self): return DLMDiscount(self.m, self.C, self.G, self.F, self.df, self.alpha, self.beta) def filter(self, z, return_results=False): # Forecast step self.m, self.C, self.alpha, self.beta = self.forecast() # Data assimilation step ret = self.data_assimilation(z) self.m, self.C, self.alpha, self.beta = ret['m'], ret['C'], ret['alpha'], ret['beta'] if return_results: return ret def forecast(self): # Forecast distribution parameters m_forecast = np.dot(self.G, self.m) C_forecast = (1 / self.df) * np.dot(self.G, np.dot(self.C, self.G_T)) return m_forecast, C_forecast, self.alpha, self.beta def data_assimilation(self, obs): # Predictive distribution parameters f = np.dot(self.F, self.m) Q = np.dot(self.F, np.dot(self.C, self.F_T)) + self.V Q_inv = np.linalg.inv(Q) # Forecast error innovation = obs - f # Kalman gain K = self.K_gain(Q) # Assimilate data m_analysis = self.m + np.dot(K, innovation) C_analysis = np.dot((np.identity(self.C.shape[0]) - np.dot(K, self.F)), self.C) alpha_analysis = self.alpha + 0.5 beta_analysis = self.beta + 0.5 * np.dot(np.transpose(innovation), np.dot(Q_inv, innovation)) ret = {'m': m_analysis, 'C': C_analysis, 'alpha': alpha_analysis, 'beta': beta_analysis[0,0]} # Optional returns ret['forecast'] = f ret['filter'] = m_analysis ret['innovation'] = innovation ret['obs_var'] = Q * self.beta / (self.alpha - 1) return ret
''' DLM Models and Relevant Functionality ''' # Libraries import numpy as np import matplotlib.pyplot as plt from numpy import pi, sin, cos from scipy.linalg import block_diag # Local Code from Utilities import load_data, check_shape, check_square from Matrix_Utilities import poly_mats, trig_mats, trig_inits class Results: def __init__(self): self.m = None self.C = None self.forecast = [] self.filter = [] self.innovation = [] self.obs_var = [] def append(self, ret): self.m = ret['m'] self.C = ret['C'] self.forecast.append(ret['forecast'][0,0]) self.filter.append(ret['filter'][0,0]) self.innovation.append(ret['innovation'][0,0]) self.obs_var.append(ret['obs_var'][0,0]) def point_estimate(self): return np.array(self.filter) def standardized_error(self): innovation = np.array(self.innovation) obs_var = np.array(self.obs_var) return innovation / np.sqrt(obs_var) class ResultsDiscount(Results): def __init__(self): super().__init__() self.alpha = [] self.beta = [] def append(self, ret): self.forecast.append(ret['forecast'][0,0]) self.filter.append(ret['filter'][0,0]) self.innovation.append(ret['innovation'][0,0]) self.obs_var.append(ret['obs_var'][0,0]) self.alpha.append(ret['alpha']) self.beta.append(ret['beta']) def var_point_estimate(self): alpha = np.array(self.alpha) beta = np.array(self.beta) return beta / (alpha - 1) # Filter a sample def filter_sample(Model, Data, init, final, set_init=True, discount_model=True, reset_to_zero=False): Temp_Model = Model.copy() if set_init: Temp_Model.m[0,0] = Data[init] if reset_to_zero: Temp_Model.m[0,0] = 0 if discount_model: results = ResultsDiscount() else: results = Results() for t in range(init, final): ret = Temp_Model.filter(Data[t], return_results=True) results.append(ret) return results # DLM parent class class DLM: def __init__(self, m, C, G, F, W, V): # State self.m = check_shape(m) self.C = check_square(C) # Forecast matrix self.G = check_square(G) self.G_T = np.transpose(check_shape(G)) # Observation matrix self.F = check_shape(F, column=False) self.F_T = np.transpose(check_shape(F, column=False)) # Forecast covariance self.W = check_square(W) # Observation covariance self.V = check_square(V) def copy(self): return DLM(self.m, self.C, self.G, self.F, self.W, self.V) def to_discount(self, df, alpha, beta): return DLMDiscount(self.m, self.C, self.G, self.F, df, alpha, beta) def add_model(self, M): # State self.m = np.concatenate((self.m, M.m)) self.C = block_diag(self.C, M.C) # Forecast matrix self.G = block_diag(self.G, M.G) self.G_T = block_diag(self.G_T, M.G_T) # Observation matrix self.F = np.concatenate((self.F, M.F), axis=1) self.F_T = np.concatenate((self.F_T, M.F_T)) # Forecast covariance self.W = block_diag(self.W, M.W) # Observation covariance self.V = self.V + M.V def set_inits(self, results): self.m = results.m self.C = results.C def filter(self, z, return_results=False): # Forecast step self.m, self.C = self.forecast() # Data assimilation step ret = self.data_assimilation(z) self.m, self.C = ret['m'], ret['C'] if return_results: return ret def forecast(self): # Forecast distribution parameters m_forecast = np.dot(self.G, self.m) C_forecast = np.dot(self.G, np.dot(self.C, self.G_T)) + self.W return m_forecast, C_forecast def data_assimilation(self, obs): # Predictive distribution parameters f = np.dot(self.F, self.m) Q = np.dot(self.F, np.dot(self.C, self.F_T)) + self.V # Forecast error innovation = obs - f # Kalman gain K = self.K_gain(Q) # Assimilate data m_analysis = self.m + np.dot(K, innovation) C_analysis = np.dot((np.identity(self.C.shape[0]) - np.dot(K, self.F)), self.C) ret = {'m': m_analysis, 'C': C_analysis} # Optional returns ret['forecast'] = f ret['filter'] = m_analysis ret['innovation'] = innovation ret['obs_var'] = Q return ret # Get Kalman Gain, given Q def K_gain(self, Q): Q_inv = np.linalg.inv(Q) K = np.dot(self.C, np.dot(self.F_T, Q_inv)) return K # Print attributes def print_model(self): text_G = '\nForecast Matrix G = \n' text_F = '\nObservation Matrix F = \n' text_W = '\nForecast Covariance W = \n' text_V = '\nObservation Covariance V = \n' print(text_G, self.G, text_F, self.F, text_W, self.W, text_V, self.V) # Polynomial model class DLMPoly(DLM): def __init__(self, m, C, W_list, V): G, F, W, V = poly_mats(W_list, V) super().__init__(m, C, G, F, W, V) # Periodic model class DLMTrig(DLM): def __init__(self, init_var, omega, q, trig_var, V): G, F, W, V = trig_mats(omega, q, trig_var, V) m, C = trig_inits(q, init_var) super().__init__(m, C, G, F, W, V) # Discount model class DLMDiscount(DLM): def __init__(self, m, C, G, F, df, alpha, beta): W = np.identity(C.shape[0]) V = np.array([[1]]) super().__init__(m, C, G, F, W, V) self.df = df self.alpha = alpha self.beta = beta def copy(self): return DLMDiscount(self.m, self.C, self.G, self.F, self.df, self.alpha, self.beta) def filter(self, z, return_results=False): # Forecast step self.m, self.C, self.alpha, self.beta = self.forecast() # Data assimilation step ret = self.data_assimilation(z) self.m, self.C, self.alpha, self.beta = ret['m'], ret['C'], ret['alpha'], ret['beta'] if return_results: return ret def forecast(self): # Forecast distribution parameters m_forecast = np.dot(self.G, self.m) C_forecast = (1 / self.df) * np.dot(self.G, np.dot(self.C, self.G_T)) return m_forecast, C_forecast, self.alpha, self.beta def data_assimilation(self, obs): # Predictive distribution parameters f = np.dot(self.F, self.m) Q = np.dot(self.F, np.dot(self.C, self.F_T)) + self.V Q_inv = np.linalg.inv(Q) # Forecast error innovation = obs - f # Kalman gain K = self.K_gain(Q) # Assimilate data m_analysis = self.m + np.dot(K, innovation) C_analysis = np.dot((np.identity(self.C.shape[0]) - np.dot(K, self.F)), self.C) alpha_analysis = self.alpha + 0.5 beta_analysis = self.beta + 0.5 * np.dot(np.transpose(innovation), np.dot(Q_inv, innovation)) ret = {'m': m_analysis, 'C': C_analysis, 'alpha': alpha_analysis, 'beta': beta_analysis[0,0]} # Optional returns ret['forecast'] = f ret['filter'] = m_analysis ret['innovation'] = innovation ret['obs_var'] = Q * self.beta / (self.alpha - 1) return ret
en
0.491085
DLM Models and Relevant Functionality # Libraries # Local Code # Filter a sample # DLM parent class # State # Forecast matrix # Observation matrix # Forecast covariance # Observation covariance # State # Forecast matrix # Observation matrix # Forecast covariance # Observation covariance # Forecast step # Data assimilation step # Forecast distribution parameters # Predictive distribution parameters # Forecast error # Kalman gain # Assimilate data # Optional returns # Get Kalman Gain, given Q # Print attributes # Polynomial model # Periodic model # Discount model # Forecast step # Data assimilation step # Forecast distribution parameters # Predictive distribution parameters # Forecast error # Kalman gain # Assimilate data # Optional returns
2.65647
3
scGNNsp_space/plot_results.py
CyanStarNight/single_cell_spatial_image
5
6613716
<filename>scGNNsp_space/plot_results.py #plot directly import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt def plotResults(dataName, dirName='S',para='_8_euclidean_Grid_dummy_add_0.5'): arr = np.load('/storage/htc/joshilab/wangjue/scGNNsp/'+dataName+'/coords_array.npy') df = pd.read_csv('/storage/htc/joshilab/wangjue/scGNNsp/outputdir'+dirName+'-'+dataName+'_0.3/'+dataName+para+'_results.txt') # sns.lmplot('population', 'Area', data=df, hue='continent', fit_reg=False) # sns.lmplot(data=df, fit_reg=False) color_labels = df['Celltype'].unique() print(color_labels) # List of colors in the color palettes rgb_values = sns.color_palette("Set2", len(color_labels)) # Map continents to the colors color_map = dict(zip(color_labels, rgb_values)) # Finally use the mapped values plt.scatter(arr[:,0], arr[:,1], c=df['Celltype'].map(color_map), s=10) plt.show() plt.savefig(str(dataName)+'-'+dirName+'-'+para+'.png') plt.close() # Basic Spatial print('Basic Spatial') plotResults('151507_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151508_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151509_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151510_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151669_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151670_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151671_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151672_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151673_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151674_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151675_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151676_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('18-64_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('2-5_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('2-8_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('T4857_cpm', para='_8_euclidean_Grid_dummy_add_0.5') # Best Spatial print('Best Spatial') plotResults('151507_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151508_cpm', para='_40_euclidean_GridEx4_dummy_add_0.5_intersect') plotResults('151509_cpm', para='_40_euclidean_GridEx4_dummy_add_0.5_intersect') plotResults('151510_cpm', para='_64_euclidean_GridEx7_dummy_add_0.5_intersect') plotResults('151669_cpm', para='_104_euclidean_GridEx12_dummy_add_0.5_intersect') plotResults('151670_cpm', para='_32_euclidean_GridEx3_dummy_add_0.5_intersect') plotResults('151671_cpm', para='_96_euclidean_GridEx11_dummy_add_0.5_intersect') plotResults('151672_cpm', para='_48_euclidean_GridEx5_dummy_add_0.5_intersect') plotResults('151673_cpm', para='_16_euclidean_GridEx_dummy_add_0.5_intersect') plotResults('151674_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151675_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151676_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('18-64_cpm', para='_32_euclidean_GridEx3_dummy_add_0.5_intersect') plotResults('2-5_cpm', para='_32_euclidean_GridEx3_dummy_add_0.5_intersect') plotResults('2-8_cpm', para='_16_euclidean_GridEx_dummy_add_0.5_intersect') plotResults('T4857_cpm', para='_16_euclidean_GridEx_dummy_add_0.5_intersect') # Best Hybrid print('Best Hybrid') plotResults('151507_cpm', dirName='H', para='_200_euclidean_NA_dummy_add_0.5_intersect_16_GridEx') plotResults('151508_cpm', dirName='H', para='_2000_euclidean_NA_dummy_add_0.5_intersect_160_GridEx19') plotResults('151509_cpm', dirName='H', para='_500_euclidean_NA_dummy_add_0.5_intersect_200_GridEx24') plotResults('151510_cpm', dirName='H', para='_50_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') plotResults('151669_cpm', dirName='H', para='_1000_euclidean_NA_dummy_add_0.5_intersect_200_GridEx24') plotResults('151670_cpm', dirName='H', para='_1000_euclidean_NA_dummy_add_0.5_intersect_160_GridEx19') plotResults('151671_cpm', dirName='H', para='_100_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') plotResults('151672_cpm', dirName='H', para='_2000_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') plotResults('151673_cpm', dirName='H', para='_2000_euclidean_NA_dummy_add_0.5_intersect_40_GridEx4') plotResults('151674_cpm', dirName='H', para='_10_euclidean_NA_dummy_add_0.5_intersect_16_GridEx') plotResults('151675_cpm', dirName='H', para='_10_euclidean_NA_dummy_add_0.5_intersect_40_GridEx4') plotResults('151676_cpm', dirName='H', para='_200_euclidean_NA_dummy_add_0.5_intersect_16_GridEx') plotResults('18-64_cpm', dirName='H', para='_1000_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') plotResults('2-5_cpm', dirName='H', para='_200_euclidean_NA_dummy_add_0.5_intersect_120_GridEx14') plotResults('2-8_cpm', dirName='H', para='_2000_euclidean_NA_dummy_add_0.5_intersect_16_GridEx') plotResults('T4857_cpm', dirName='H', para='_50_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') # Best Hybrid geom print('Best Hybrid') plotResults('151507_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_80_GridEx9') plotResults('151508_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_120_GridEx14') plotResults('151509_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_200_GridEx24') plotResults('151510_cpm', dirName='H', para='_1000_euclidean_NA_geom_lowf_add_0.5_intersect_120_GridEx14') plotResults('151669_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_240_GridEx29') plotResults('151670_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_240_GridEx29') plotResults('151671_cpm', dirName='H', para='_200_euclidean_NA_geom_lowf_add_0.5_intersect_80_GridEx9') plotResults('151672_cpm', dirName='H', para='_100_euclidean_NA_geom_lowf_add_0.5_intersect_160_GridEx19') plotResults('151673_cpm', dirName='H', para='_1000_euclidean_NA_geom_lowf_add_0.5_intersect_16_GridEx') plotResults('151674_cpm', dirName='H', para='_10_euclidean_NA_geom_lowf_add_0.5_intersect_8_Grid') plotResults('151675_cpm', dirName='H', para='_10_euclidean_NA_geom_lowf_add_0.5_intersect_40_GridEx4') plotResults('151676_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_40_GridEx4') plotResults('18-64_cpm', dirName='H', para='_10_euclidean_NA_geom_lowf_add_0.5_intersect_240_GridEx29') plotResults('2-5_cpm', dirName='H', para='_100_euclidean_NA_geom_lowf_add_0.5_intersect_120_GridEx14') plotResults('2-8_cpm', dirName='H', para='_500_euclidean_NA_geom_lowf_add_0.5_intersect_80_GridEx9') plotResults('T4857_cpm', dirName='H', para='_10_euclidean_NA_geom_lowf_add_0.5_intersect_200_GridEx24') # plotResults('151507_sctransform') # plotResults('151508_sctransform') # plotResults('151509_sctransform') # plotResults('151510_sctransform') # plotResults('151669_sctransform') # plotResults('151670_sctransform') # plotResults('151671_sctransform') # plotResults('151672_sctransform') # plotResults('151673_sctransform') # plotResults('151674_sctransform') # plotResults('151675_sctransform') # plotResults('151676_sctransform') # plotResults('18-64_sctransform') # plotResults('2-5_sctransform') # plotResults('2-8_sctransform') # plotResults('T4857_sctransform') ########## # #plot # t=np.load('defaultPE.npy') # tmp=[] # i=0 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'y.') # tmp=[] # i=2 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'b.') # tmp=[] # i=20 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'r.') # plt.show() # ########## # tmp=[] # i=0 # for j in range(10): # tmp.append(t[i,j]) # plt.plot(tmp,'y.') # tmp1=[] # i=2 # for j in range(10): # tmp1.append(t[i,j]) # plt.plot(tmp1,'b.') # tmp2=[] # i=10 # for j in range(10): # tmp2.append(t[i,j]) # plt.plot(tmp2,'r.') # plt.show()
<filename>scGNNsp_space/plot_results.py #plot directly import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt def plotResults(dataName, dirName='S',para='_8_euclidean_Grid_dummy_add_0.5'): arr = np.load('/storage/htc/joshilab/wangjue/scGNNsp/'+dataName+'/coords_array.npy') df = pd.read_csv('/storage/htc/joshilab/wangjue/scGNNsp/outputdir'+dirName+'-'+dataName+'_0.3/'+dataName+para+'_results.txt') # sns.lmplot('population', 'Area', data=df, hue='continent', fit_reg=False) # sns.lmplot(data=df, fit_reg=False) color_labels = df['Celltype'].unique() print(color_labels) # List of colors in the color palettes rgb_values = sns.color_palette("Set2", len(color_labels)) # Map continents to the colors color_map = dict(zip(color_labels, rgb_values)) # Finally use the mapped values plt.scatter(arr[:,0], arr[:,1], c=df['Celltype'].map(color_map), s=10) plt.show() plt.savefig(str(dataName)+'-'+dirName+'-'+para+'.png') plt.close() # Basic Spatial print('Basic Spatial') plotResults('151507_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151508_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151509_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151510_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151669_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151670_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151671_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151672_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151673_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151674_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151675_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151676_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('18-64_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('2-5_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('2-8_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('T4857_cpm', para='_8_euclidean_Grid_dummy_add_0.5') # Best Spatial print('Best Spatial') plotResults('151507_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151508_cpm', para='_40_euclidean_GridEx4_dummy_add_0.5_intersect') plotResults('151509_cpm', para='_40_euclidean_GridEx4_dummy_add_0.5_intersect') plotResults('151510_cpm', para='_64_euclidean_GridEx7_dummy_add_0.5_intersect') plotResults('151669_cpm', para='_104_euclidean_GridEx12_dummy_add_0.5_intersect') plotResults('151670_cpm', para='_32_euclidean_GridEx3_dummy_add_0.5_intersect') plotResults('151671_cpm', para='_96_euclidean_GridEx11_dummy_add_0.5_intersect') plotResults('151672_cpm', para='_48_euclidean_GridEx5_dummy_add_0.5_intersect') plotResults('151673_cpm', para='_16_euclidean_GridEx_dummy_add_0.5_intersect') plotResults('151674_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151675_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('151676_cpm', para='_8_euclidean_Grid_dummy_add_0.5') plotResults('18-64_cpm', para='_32_euclidean_GridEx3_dummy_add_0.5_intersect') plotResults('2-5_cpm', para='_32_euclidean_GridEx3_dummy_add_0.5_intersect') plotResults('2-8_cpm', para='_16_euclidean_GridEx_dummy_add_0.5_intersect') plotResults('T4857_cpm', para='_16_euclidean_GridEx_dummy_add_0.5_intersect') # Best Hybrid print('Best Hybrid') plotResults('151507_cpm', dirName='H', para='_200_euclidean_NA_dummy_add_0.5_intersect_16_GridEx') plotResults('151508_cpm', dirName='H', para='_2000_euclidean_NA_dummy_add_0.5_intersect_160_GridEx19') plotResults('151509_cpm', dirName='H', para='_500_euclidean_NA_dummy_add_0.5_intersect_200_GridEx24') plotResults('151510_cpm', dirName='H', para='_50_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') plotResults('151669_cpm', dirName='H', para='_1000_euclidean_NA_dummy_add_0.5_intersect_200_GridEx24') plotResults('151670_cpm', dirName='H', para='_1000_euclidean_NA_dummy_add_0.5_intersect_160_GridEx19') plotResults('151671_cpm', dirName='H', para='_100_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') plotResults('151672_cpm', dirName='H', para='_2000_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') plotResults('151673_cpm', dirName='H', para='_2000_euclidean_NA_dummy_add_0.5_intersect_40_GridEx4') plotResults('151674_cpm', dirName='H', para='_10_euclidean_NA_dummy_add_0.5_intersect_16_GridEx') plotResults('151675_cpm', dirName='H', para='_10_euclidean_NA_dummy_add_0.5_intersect_40_GridEx4') plotResults('151676_cpm', dirName='H', para='_200_euclidean_NA_dummy_add_0.5_intersect_16_GridEx') plotResults('18-64_cpm', dirName='H', para='_1000_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') plotResults('2-5_cpm', dirName='H', para='_200_euclidean_NA_dummy_add_0.5_intersect_120_GridEx14') plotResults('2-8_cpm', dirName='H', para='_2000_euclidean_NA_dummy_add_0.5_intersect_16_GridEx') plotResults('T4857_cpm', dirName='H', para='_50_euclidean_NA_dummy_add_0.5_intersect_80_GridEx9') # Best Hybrid geom print('Best Hybrid') plotResults('151507_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_80_GridEx9') plotResults('151508_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_120_GridEx14') plotResults('151509_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_200_GridEx24') plotResults('151510_cpm', dirName='H', para='_1000_euclidean_NA_geom_lowf_add_0.5_intersect_120_GridEx14') plotResults('151669_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_240_GridEx29') plotResults('151670_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_240_GridEx29') plotResults('151671_cpm', dirName='H', para='_200_euclidean_NA_geom_lowf_add_0.5_intersect_80_GridEx9') plotResults('151672_cpm', dirName='H', para='_100_euclidean_NA_geom_lowf_add_0.5_intersect_160_GridEx19') plotResults('151673_cpm', dirName='H', para='_1000_euclidean_NA_geom_lowf_add_0.5_intersect_16_GridEx') plotResults('151674_cpm', dirName='H', para='_10_euclidean_NA_geom_lowf_add_0.5_intersect_8_Grid') plotResults('151675_cpm', dirName='H', para='_10_euclidean_NA_geom_lowf_add_0.5_intersect_40_GridEx4') plotResults('151676_cpm', dirName='H', para='_2000_euclidean_NA_geom_lowf_add_0.5_intersect_40_GridEx4') plotResults('18-64_cpm', dirName='H', para='_10_euclidean_NA_geom_lowf_add_0.5_intersect_240_GridEx29') plotResults('2-5_cpm', dirName='H', para='_100_euclidean_NA_geom_lowf_add_0.5_intersect_120_GridEx14') plotResults('2-8_cpm', dirName='H', para='_500_euclidean_NA_geom_lowf_add_0.5_intersect_80_GridEx9') plotResults('T4857_cpm', dirName='H', para='_10_euclidean_NA_geom_lowf_add_0.5_intersect_200_GridEx24') # plotResults('151507_sctransform') # plotResults('151508_sctransform') # plotResults('151509_sctransform') # plotResults('151510_sctransform') # plotResults('151669_sctransform') # plotResults('151670_sctransform') # plotResults('151671_sctransform') # plotResults('151672_sctransform') # plotResults('151673_sctransform') # plotResults('151674_sctransform') # plotResults('151675_sctransform') # plotResults('151676_sctransform') # plotResults('18-64_sctransform') # plotResults('2-5_sctransform') # plotResults('2-8_sctransform') # plotResults('T4857_sctransform') ########## # #plot # t=np.load('defaultPE.npy') # tmp=[] # i=0 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'y.') # tmp=[] # i=2 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'b.') # tmp=[] # i=20 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'r.') # plt.show() # ########## # tmp=[] # i=0 # for j in range(10): # tmp.append(t[i,j]) # plt.plot(tmp,'y.') # tmp1=[] # i=2 # for j in range(10): # tmp1.append(t[i,j]) # plt.plot(tmp1,'b.') # tmp2=[] # i=10 # for j in range(10): # tmp2.append(t[i,j]) # plt.plot(tmp2,'r.') # plt.show()
en
0.143765
#plot directly # sns.lmplot('population', 'Area', data=df, hue='continent', fit_reg=False) # sns.lmplot(data=df, fit_reg=False) # List of colors in the color palettes # Map continents to the colors # Finally use the mapped values # Basic Spatial # Best Spatial # Best Hybrid # Best Hybrid geom # plotResults('151507_sctransform') # plotResults('151508_sctransform') # plotResults('151509_sctransform') # plotResults('151510_sctransform') # plotResults('151669_sctransform') # plotResults('151670_sctransform') # plotResults('151671_sctransform') # plotResults('151672_sctransform') # plotResults('151673_sctransform') # plotResults('151674_sctransform') # plotResults('151675_sctransform') # plotResults('151676_sctransform') # plotResults('18-64_sctransform') # plotResults('2-5_sctransform') # plotResults('2-8_sctransform') # plotResults('T4857_sctransform') ########## # #plot # t=np.load('defaultPE.npy') # tmp=[] # i=0 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'y.') # tmp=[] # i=2 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'b.') # tmp=[] # i=20 # for j in range(10): # tmp.append(t[i,j]+t[i,j+10]) # plt.plot(tmp,'r.') # plt.show() # ########## # tmp=[] # i=0 # for j in range(10): # tmp.append(t[i,j]) # plt.plot(tmp,'y.') # tmp1=[] # i=2 # for j in range(10): # tmp1.append(t[i,j]) # plt.plot(tmp1,'b.') # tmp2=[] # i=10 # for j in range(10): # tmp2.append(t[i,j]) # plt.plot(tmp2,'r.') # plt.show()
2.6961
3
docker/generate.py
qooba/feast-benchmark
0
6613717
<gh_stars>0 import pandas as pd import numpy as np from datetime import datetime, timezone from sklearn.datasets import make_hastie_10_2 import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) def generate_entities(size): return np.random.choice(size, size=size, replace=False) def generate_data(entities, year=2021, month=10, day=1) -> pd.DataFrame: n_samples=len(entities) X, y = make_hastie_10_2(n_samples=n_samples, random_state=0) df = pd.DataFrame(X, columns=["f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9"]) df["y"]=y df['entity_id'] = entities df['datetime'] = pd.to_datetime( np.random.randint( datetime(year, month, day, 0,tzinfo=timezone.utc).timestamp(), datetime(year, month, day, 22,tzinfo=timezone.utc).timestamp(), size=n_samples), unit="s", #utc=True ) df['created'] = pd.to_datetime( datetime.now(), #utc=True ) return df entities=generate_entities(1000000) entity_df = pd.DataFrame(data=entities, columns=['entity_id']) entity_df["event_timestamp"]=datetime(2021, 1, 14, 23, 59, 42, tzinfo=timezone.utc) entity_df=entity_df[entity_df.entity_id == 100] #entity_df=entity_df[entity_df.entity_id < 500] entity_df.to_parquet('./dataset/entity_df.parquet') all_data=[] for d in range(1,15): data=generate_data(entities,month=1, day=d) all_data.append(data) all_dd=pd.concat(all_data) all_dd.set_index('datetime') all_dd.to_parquet("./dataset/all_data.parquet")
import pandas as pd import numpy as np from datetime import datetime, timezone from sklearn.datasets import make_hastie_10_2 import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) def generate_entities(size): return np.random.choice(size, size=size, replace=False) def generate_data(entities, year=2021, month=10, day=1) -> pd.DataFrame: n_samples=len(entities) X, y = make_hastie_10_2(n_samples=n_samples, random_state=0) df = pd.DataFrame(X, columns=["f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9"]) df["y"]=y df['entity_id'] = entities df['datetime'] = pd.to_datetime( np.random.randint( datetime(year, month, day, 0,tzinfo=timezone.utc).timestamp(), datetime(year, month, day, 22,tzinfo=timezone.utc).timestamp(), size=n_samples), unit="s", #utc=True ) df['created'] = pd.to_datetime( datetime.now(), #utc=True ) return df entities=generate_entities(1000000) entity_df = pd.DataFrame(data=entities, columns=['entity_id']) entity_df["event_timestamp"]=datetime(2021, 1, 14, 23, 59, 42, tzinfo=timezone.utc) entity_df=entity_df[entity_df.entity_id == 100] #entity_df=entity_df[entity_df.entity_id < 500] entity_df.to_parquet('./dataset/entity_df.parquet') all_data=[] for d in range(1,15): data=generate_data(entities,month=1, day=d) all_data.append(data) all_dd=pd.concat(all_data) all_dd.set_index('datetime') all_dd.to_parquet("./dataset/all_data.parquet")
en
0.647864
#utc=True #utc=True #entity_df=entity_df[entity_df.entity_id < 500]
2.640442
3
dali/test/python/test_dali_tf_dataset_pipelines.py
lvtengda/DALI
0
6613718
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali as dali import nvidia.dali.fn as fn import nvidia.dali.plugin.tf as dali_tf from nvidia.dali import pipeline_def import tensorflow as tf from test_utils import RandomlyShapedDataIterator import numpy as np from nose.tools import nottest class RandomSampleIterator: def __init__(self, max_shape=(10, 600, 800, 3), dtype_sample=np.uint8(0), start=0, stop=1e100, min_shape=None, seed=42): self.start = start self.stop = stop self.min_shape = min_shape self.max_shape = max_shape # As tf passes only tensors to the iterator, we pass a dummy value of which we take the type self.dtype = dtype_sample.dtype self.seed = seed def __iter__(self): self.n = self.start self.random_iter = iter(RandomlyShapedDataIterator(batch_size=1, min_shape=self.min_shape, max_shape=self.max_shape, seed=self.seed, dtype=self.dtype)) return self def __next__(self): if self.n <= self.stop: result = self.n self.n += 1 ret = self.random_iter.next()[0] return ret else: raise StopIteration class FixedSampleIterator: def __init__(self, value): self.value = value def __iter__(self): return self def __next__(self): return self.value class InfiniteSampleIterator: def __init__(self, start_value): self.value = start_value def __iter__(self): return self def __next__(self): result = self.value self.value = self.value + np.array(1, dtype=self.value.dtype) return result @pipeline_def def one_input_pipeline(def_for_dataset, device, source, external_source_device): """Pipeline accepting single input via external source Parameters ---------- def_for_dataset : bool True if this pipeline will be converted to TF Dataset device : str device that the Dataset will be placed ("cpu" or "gpu") source : callable callback for the external source in baseline pipeline otherwise None external_source_device : str Device that we want the external source in TF dataset to be placed """ if def_for_dataset: # We use no copy when the input memory is matching the external source placement, # so the Dataset's placement is the same as external source's device input = fn.external_source(name="input_placeholder", no_copy=(device == external_source_device), device=external_source_device) else: input = fn.external_source(name="actual_input", source=source, batch=False, device=external_source_device) input = input if device == 'cpu' else input.gpu() processed = fn.cast(input + 10, dtype=dali.types.INT32) input_padded, processed_padded = fn.pad([input, processed]) return input_padded, processed_padded # Test that uses Tensor and Repeat (infinite) datasets as inputs to DALI pipeline def external_source_converter_with_fixed_value(shape, dtype, tensor): def to_dataset(pipeline_desc, device_str): with tf.device('/cpu:0'): input_dataset = tf.data.Dataset.from_tensors(tensor).repeat() # If we place DALIDataset on GPU we need the remote call + manual data transfer if "gpu" in device_str: input_dataset = input_dataset.apply(tf.data.experimental.copy_to_device('/gpu:0')) dataset_pipeline, shapes, dtypes = pipeline_desc with tf.device(device_str): dali_dataset = dali_tf.experimental.DALIDatasetWithInputs( input_datasets=input_dataset, input_names="input_placeholder", pipeline=dataset_pipeline, batch_size=dataset_pipeline.batch_size, output_shapes=shapes, output_dtypes=dtypes, num_threads=dataset_pipeline.num_threads, device_id=dataset_pipeline.device_id) return dali_dataset return to_dataset # Test that uses Generator dataset as inputs to DALI pipeline def external_source_converter_with_callback(input_iterator, shape, dtype, *args): def to_dataset(pipeline_desc, device_str): with tf.device('/cpu:0'): _args = (shape, dtype(0)) + tuple(args) out_shape = tuple(None for _ in shape) tf_type = tf.dtypes.as_dtype(dtype) input_dataset = tf.data.Dataset.from_generator( input_iterator, output_types=tf_type, output_shapes=out_shape, args=_args) # If we place DALIDataset on GPU we need the remote call + manual data transfer if "gpu" in device_str: input_dataset = input_dataset.apply(tf.data.experimental.copy_to_device('/gpu:0')) dataset_pipeline, shapes, dtypes = pipeline_desc with tf.device(device_str): dali_dataset = dali_tf.experimental.DALIDatasetWithInputs( input_datasets=input_dataset, input_names="input_placeholder", pipeline=dataset_pipeline, batch_size=dataset_pipeline.batch_size, output_shapes=shapes, output_dtypes=dtypes, num_threads=dataset_pipeline.num_threads, device_id=dataset_pipeline.device_id) return dali_dataset return to_dataset @nottest def external_source_tester(shape, dtype, source=None, external_source_device="cpu"): def get_external_source_pipeline_getter(batch_size, num_threads, device, device_id=0, shard_id=0, num_shards=1, def_for_dataset=False): pipe = one_input_pipeline(def_for_dataset, device, source, external_source_device, batch_size=batch_size, num_threads=num_threads, device_id=device_id) batch_shape = (batch_size,) + tuple(None for _ in shape) return pipe, (batch_shape, batch_shape), (tf.dtypes.as_dtype(dtype), tf.int32) return get_external_source_pipeline_getter @pipeline_def def many_input_pipeline(def_for_dataset, device, sources, input_names): """ Pipeline accepting multiple inputs via external source Parameters ---------- def_for_dataset : bool True if this pipeline will be converted to TF Dataset device : str device that the Dataset will be placed ("cpu" or "gpu") sources : list of callables callbacks for the external sources in baseline pipeline otherwise None input_names : list of str Names of inputs placeholder for TF """ inputs = [] if def_for_dataset: for input_name in input_names: input = fn.external_source(name=input_name) input = input if device == 'cpu' else input.gpu() inputs.append(input) else: for source in sources: input = fn.external_source(source=source, batch=False) input = input if device == 'cpu' else input.gpu() inputs.append(input) processed = [] for input in inputs: processed.append(fn.cast(input + 10, dtype=dali.types.INT32)) results = fn.pad(inputs + processed) return tuple(results) # Test that uses multiple Generator dataset as inputs to DALI pipeline def external_source_converter_multiple(start_values, input_names): def to_dataset(pipeline_desc, device_str): with tf.device('/cpu:0'): input_datasets = [] for value, name in zip(start_values, input_names): tf_type = tf.dtypes.as_dtype(value.dtype) shape = value.shape input_dataset = tf.data.Dataset.from_generator( InfiniteSampleIterator, output_types=tf_type, output_shapes=shape, args=(value,)) # If we place DALIDataset on GPU we need the remote call + manual data transfer if "gpu" in device_str: input_dataset = input_dataset.apply(tf.data.experimental.copy_to_device('/gpu:0')) input_datasets.append(input_dataset) dataset_pipeline, shapes, dtypes = pipeline_desc with tf.device(device_str): dali_dataset = dali_tf.experimental.DALIDatasetWithInputs( input_datasets=tuple(input_datasets), input_names=tuple(input_names), pipeline=dataset_pipeline, batch_size=dataset_pipeline.batch_size, output_shapes=shapes, output_dtypes=dtypes, num_threads=dataset_pipeline.num_threads, device_id=dataset_pipeline.device_id) return dali_dataset return to_dataset @nottest def external_source_tester_multiple(start_values, input_names): def get_external_source_pipeline_getter(batch_size, num_threads, device, device_id=0, shard_id=0, num_shards=1, def_for_dataset=False): sources = [InfiniteSampleIterator(start_value) for start_value in start_values] output_shapes = [((batch_size, ) + tuple(None for _ in start_value.shape)) for start_value in start_values] output_shapes = tuple(output_shapes + output_shapes) output_dtypes = tuple( [tf.dtypes.as_dtype(start_value.dtype) for start_value in start_values] + [tf.int32] * len(start_values)) pipe = many_input_pipeline(def_for_dataset, device, sources, input_names, batch_size=batch_size, num_threads=num_threads, device_id=device_id) return pipe, output_shapes, output_dtypes return get_external_source_pipeline_getter
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 nvidia.dali as dali import nvidia.dali.fn as fn import nvidia.dali.plugin.tf as dali_tf from nvidia.dali import pipeline_def import tensorflow as tf from test_utils import RandomlyShapedDataIterator import numpy as np from nose.tools import nottest class RandomSampleIterator: def __init__(self, max_shape=(10, 600, 800, 3), dtype_sample=np.uint8(0), start=0, stop=1e100, min_shape=None, seed=42): self.start = start self.stop = stop self.min_shape = min_shape self.max_shape = max_shape # As tf passes only tensors to the iterator, we pass a dummy value of which we take the type self.dtype = dtype_sample.dtype self.seed = seed def __iter__(self): self.n = self.start self.random_iter = iter(RandomlyShapedDataIterator(batch_size=1, min_shape=self.min_shape, max_shape=self.max_shape, seed=self.seed, dtype=self.dtype)) return self def __next__(self): if self.n <= self.stop: result = self.n self.n += 1 ret = self.random_iter.next()[0] return ret else: raise StopIteration class FixedSampleIterator: def __init__(self, value): self.value = value def __iter__(self): return self def __next__(self): return self.value class InfiniteSampleIterator: def __init__(self, start_value): self.value = start_value def __iter__(self): return self def __next__(self): result = self.value self.value = self.value + np.array(1, dtype=self.value.dtype) return result @pipeline_def def one_input_pipeline(def_for_dataset, device, source, external_source_device): """Pipeline accepting single input via external source Parameters ---------- def_for_dataset : bool True if this pipeline will be converted to TF Dataset device : str device that the Dataset will be placed ("cpu" or "gpu") source : callable callback for the external source in baseline pipeline otherwise None external_source_device : str Device that we want the external source in TF dataset to be placed """ if def_for_dataset: # We use no copy when the input memory is matching the external source placement, # so the Dataset's placement is the same as external source's device input = fn.external_source(name="input_placeholder", no_copy=(device == external_source_device), device=external_source_device) else: input = fn.external_source(name="actual_input", source=source, batch=False, device=external_source_device) input = input if device == 'cpu' else input.gpu() processed = fn.cast(input + 10, dtype=dali.types.INT32) input_padded, processed_padded = fn.pad([input, processed]) return input_padded, processed_padded # Test that uses Tensor and Repeat (infinite) datasets as inputs to DALI pipeline def external_source_converter_with_fixed_value(shape, dtype, tensor): def to_dataset(pipeline_desc, device_str): with tf.device('/cpu:0'): input_dataset = tf.data.Dataset.from_tensors(tensor).repeat() # If we place DALIDataset on GPU we need the remote call + manual data transfer if "gpu" in device_str: input_dataset = input_dataset.apply(tf.data.experimental.copy_to_device('/gpu:0')) dataset_pipeline, shapes, dtypes = pipeline_desc with tf.device(device_str): dali_dataset = dali_tf.experimental.DALIDatasetWithInputs( input_datasets=input_dataset, input_names="input_placeholder", pipeline=dataset_pipeline, batch_size=dataset_pipeline.batch_size, output_shapes=shapes, output_dtypes=dtypes, num_threads=dataset_pipeline.num_threads, device_id=dataset_pipeline.device_id) return dali_dataset return to_dataset # Test that uses Generator dataset as inputs to DALI pipeline def external_source_converter_with_callback(input_iterator, shape, dtype, *args): def to_dataset(pipeline_desc, device_str): with tf.device('/cpu:0'): _args = (shape, dtype(0)) + tuple(args) out_shape = tuple(None for _ in shape) tf_type = tf.dtypes.as_dtype(dtype) input_dataset = tf.data.Dataset.from_generator( input_iterator, output_types=tf_type, output_shapes=out_shape, args=_args) # If we place DALIDataset on GPU we need the remote call + manual data transfer if "gpu" in device_str: input_dataset = input_dataset.apply(tf.data.experimental.copy_to_device('/gpu:0')) dataset_pipeline, shapes, dtypes = pipeline_desc with tf.device(device_str): dali_dataset = dali_tf.experimental.DALIDatasetWithInputs( input_datasets=input_dataset, input_names="input_placeholder", pipeline=dataset_pipeline, batch_size=dataset_pipeline.batch_size, output_shapes=shapes, output_dtypes=dtypes, num_threads=dataset_pipeline.num_threads, device_id=dataset_pipeline.device_id) return dali_dataset return to_dataset @nottest def external_source_tester(shape, dtype, source=None, external_source_device="cpu"): def get_external_source_pipeline_getter(batch_size, num_threads, device, device_id=0, shard_id=0, num_shards=1, def_for_dataset=False): pipe = one_input_pipeline(def_for_dataset, device, source, external_source_device, batch_size=batch_size, num_threads=num_threads, device_id=device_id) batch_shape = (batch_size,) + tuple(None for _ in shape) return pipe, (batch_shape, batch_shape), (tf.dtypes.as_dtype(dtype), tf.int32) return get_external_source_pipeline_getter @pipeline_def def many_input_pipeline(def_for_dataset, device, sources, input_names): """ Pipeline accepting multiple inputs via external source Parameters ---------- def_for_dataset : bool True if this pipeline will be converted to TF Dataset device : str device that the Dataset will be placed ("cpu" or "gpu") sources : list of callables callbacks for the external sources in baseline pipeline otherwise None input_names : list of str Names of inputs placeholder for TF """ inputs = [] if def_for_dataset: for input_name in input_names: input = fn.external_source(name=input_name) input = input if device == 'cpu' else input.gpu() inputs.append(input) else: for source in sources: input = fn.external_source(source=source, batch=False) input = input if device == 'cpu' else input.gpu() inputs.append(input) processed = [] for input in inputs: processed.append(fn.cast(input + 10, dtype=dali.types.INT32)) results = fn.pad(inputs + processed) return tuple(results) # Test that uses multiple Generator dataset as inputs to DALI pipeline def external_source_converter_multiple(start_values, input_names): def to_dataset(pipeline_desc, device_str): with tf.device('/cpu:0'): input_datasets = [] for value, name in zip(start_values, input_names): tf_type = tf.dtypes.as_dtype(value.dtype) shape = value.shape input_dataset = tf.data.Dataset.from_generator( InfiniteSampleIterator, output_types=tf_type, output_shapes=shape, args=(value,)) # If we place DALIDataset on GPU we need the remote call + manual data transfer if "gpu" in device_str: input_dataset = input_dataset.apply(tf.data.experimental.copy_to_device('/gpu:0')) input_datasets.append(input_dataset) dataset_pipeline, shapes, dtypes = pipeline_desc with tf.device(device_str): dali_dataset = dali_tf.experimental.DALIDatasetWithInputs( input_datasets=tuple(input_datasets), input_names=tuple(input_names), pipeline=dataset_pipeline, batch_size=dataset_pipeline.batch_size, output_shapes=shapes, output_dtypes=dtypes, num_threads=dataset_pipeline.num_threads, device_id=dataset_pipeline.device_id) return dali_dataset return to_dataset @nottest def external_source_tester_multiple(start_values, input_names): def get_external_source_pipeline_getter(batch_size, num_threads, device, device_id=0, shard_id=0, num_shards=1, def_for_dataset=False): sources = [InfiniteSampleIterator(start_value) for start_value in start_values] output_shapes = [((batch_size, ) + tuple(None for _ in start_value.shape)) for start_value in start_values] output_shapes = tuple(output_shapes + output_shapes) output_dtypes = tuple( [tf.dtypes.as_dtype(start_value.dtype) for start_value in start_values] + [tf.int32] * len(start_values)) pipe = many_input_pipeline(def_for_dataset, device, sources, input_names, batch_size=batch_size, num_threads=num_threads, device_id=device_id) return pipe, output_shapes, output_dtypes return get_external_source_pipeline_getter
en
0.76997
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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. # As tf passes only tensors to the iterator, we pass a dummy value of which we take the type Pipeline accepting single input via external source Parameters ---------- def_for_dataset : bool True if this pipeline will be converted to TF Dataset device : str device that the Dataset will be placed ("cpu" or "gpu") source : callable callback for the external source in baseline pipeline otherwise None external_source_device : str Device that we want the external source in TF dataset to be placed # We use no copy when the input memory is matching the external source placement, # so the Dataset's placement is the same as external source's device # Test that uses Tensor and Repeat (infinite) datasets as inputs to DALI pipeline # If we place DALIDataset on GPU we need the remote call + manual data transfer # Test that uses Generator dataset as inputs to DALI pipeline # If we place DALIDataset on GPU we need the remote call + manual data transfer Pipeline accepting multiple inputs via external source Parameters ---------- def_for_dataset : bool True if this pipeline will be converted to TF Dataset device : str device that the Dataset will be placed ("cpu" or "gpu") sources : list of callables callbacks for the external sources in baseline pipeline otherwise None input_names : list of str Names of inputs placeholder for TF # Test that uses multiple Generator dataset as inputs to DALI pipeline # If we place DALIDataset on GPU we need the remote call + manual data transfer
2.3176
2
utils/iqc_report.py
uees/happyWork
0
6613719
import random import re from datetime import datetime from openpyxl import load_workbook from common import module_path from database import IQCMaterial def generate(filename, end_row=None): wb = load_workbook(filename) ws = wb.get_sheet_by_name('供应商来料质量统计表') if not end_row: end_row = ws.max_row for row in ws.iter_rows('B7:G{}'.format(end_row)): template_wb = load_workbook('%s/templates/iqc.xlsx' % module_path()) template_ws = template_wb.get_sheet_by_name('Sheet1') material_name, incoming_date, supplier, qc_result, substandard_items, amount = [ cell.value for cell in row] _material_name = '' if isinstance(material_name, str): _material_name = re.sub(r'[\u4e00-\u9fa5]+', '', material_name) # 去掉中文 if not _material_name: continue material = IQCMaterial.query.filter(IQCMaterial.name.ilike('%' + _material_name + '%')).first() if not material or material.qc_items == '免检': continue if isinstance(incoming_date, datetime): incoming_date = datetime.strftime(incoming_date, '%Y-%m-%d') # 转为字符串 if _material_name.upper() in ['0.25L', '0.3L', '1L', '5L', '6L', '20L', '0.25KG', '0.3KG', '1KG', '5KG', '6KG', '20KG']: unit = '套' else: unit = 'kg' template_ws.cell('B5').value = incoming_date template_ws.cell('B6').value = material_name template_ws.cell('D6').value = supplier template_ws.cell('D7').value = '%s%s' % (amount, unit) template_ws.cell('D8').value = material.qc_method qc_items = material.qc_items.split('、') row = 11 for item in qc_items: template_ws.cell('A{}'.format(row)).value = item if item == '细度': if _material_name.find('A0084') >= 0: template_ws.cell('C{}'.format(row)).value = '<25μm' elif _material_name.find('A0085') >= 0 or \ _material_name.find('A0088') >= 0: template_ws.cell('C{}'.format(row)).value = '<17.5μm' else: template_ws.cell('C{}'.format(row)).value = '<20μm' elif item == '软化点': if _material_name == 'A0016' or _material_name == 'A0016A'\ or _material_name == 'A0016B': template_ws.cell('C{}'.format(row)).value = \ '%s℃' % round(random.uniform(27, 30), 1) elif _material_name == 'A0016F': template_ws.cell('C{}'.format(row)).value = \ '%s℃' % round(random.uniform(32, 35), 1) else: template_ws.cell('C{}'.format(row)).value = '√' elif item == '环氧值': if _material_name == 'A0016' or _material_name == 'A0016A'\ or _material_name == 'A0016B': template_ws.cell('C{}'.format(row)).value = \ '%s mol/100g' % round(random.uniform(0.515, 0.535), 3) elif _material_name == 'A0016F': template_ws.cell('C{}'.format(row)).value = \ '%s mol/100g' % round(random.uniform(0.56, 0.59), 3) else: template_ws.cell('C{}'.format(row)).value = '√' elif item == '馏程': if _material_name.find('A0055') >= 0 or \ _material_name.find('A0063') >= 0: template_ws.cell('C{}'.format(row)).value = \ '%s~%s℃' % (str(180 + random.randint(1, 9)), str(220 - random.randint(1, 9))) elif _material_name.find('A0058') >= 0: template_ws.cell('C{}'.format(row)).value = \ '%s~%s℃' % (str(135 + random.randint(1, 5)), str(150 - random.randint(1, 5))) else: template_ws.cell('C{}'.format(row)).value = '√' else: template_ws.cell('C{}'.format(row)).value = '√' row += 1 template_ws.merge_cells('B11:B{}'.format(10 + len(qc_items))) template_ws.cell('B11').value = material.spec new_filename = '%s-%s-%s-%s.xlsx' % (incoming_date, random.randint(1, 99), material_name, supplier) template_wb.save('%s/reports/IQC/%s' % (module_path(), new_filename))
import random import re from datetime import datetime from openpyxl import load_workbook from common import module_path from database import IQCMaterial def generate(filename, end_row=None): wb = load_workbook(filename) ws = wb.get_sheet_by_name('供应商来料质量统计表') if not end_row: end_row = ws.max_row for row in ws.iter_rows('B7:G{}'.format(end_row)): template_wb = load_workbook('%s/templates/iqc.xlsx' % module_path()) template_ws = template_wb.get_sheet_by_name('Sheet1') material_name, incoming_date, supplier, qc_result, substandard_items, amount = [ cell.value for cell in row] _material_name = '' if isinstance(material_name, str): _material_name = re.sub(r'[\u4e00-\u9fa5]+', '', material_name) # 去掉中文 if not _material_name: continue material = IQCMaterial.query.filter(IQCMaterial.name.ilike('%' + _material_name + '%')).first() if not material or material.qc_items == '免检': continue if isinstance(incoming_date, datetime): incoming_date = datetime.strftime(incoming_date, '%Y-%m-%d') # 转为字符串 if _material_name.upper() in ['0.25L', '0.3L', '1L', '5L', '6L', '20L', '0.25KG', '0.3KG', '1KG', '5KG', '6KG', '20KG']: unit = '套' else: unit = 'kg' template_ws.cell('B5').value = incoming_date template_ws.cell('B6').value = material_name template_ws.cell('D6').value = supplier template_ws.cell('D7').value = '%s%s' % (amount, unit) template_ws.cell('D8').value = material.qc_method qc_items = material.qc_items.split('、') row = 11 for item in qc_items: template_ws.cell('A{}'.format(row)).value = item if item == '细度': if _material_name.find('A0084') >= 0: template_ws.cell('C{}'.format(row)).value = '<25μm' elif _material_name.find('A0085') >= 0 or \ _material_name.find('A0088') >= 0: template_ws.cell('C{}'.format(row)).value = '<17.5μm' else: template_ws.cell('C{}'.format(row)).value = '<20μm' elif item == '软化点': if _material_name == 'A0016' or _material_name == 'A0016A'\ or _material_name == 'A0016B': template_ws.cell('C{}'.format(row)).value = \ '%s℃' % round(random.uniform(27, 30), 1) elif _material_name == 'A0016F': template_ws.cell('C{}'.format(row)).value = \ '%s℃' % round(random.uniform(32, 35), 1) else: template_ws.cell('C{}'.format(row)).value = '√' elif item == '环氧值': if _material_name == 'A0016' or _material_name == 'A0016A'\ or _material_name == 'A0016B': template_ws.cell('C{}'.format(row)).value = \ '%s mol/100g' % round(random.uniform(0.515, 0.535), 3) elif _material_name == 'A0016F': template_ws.cell('C{}'.format(row)).value = \ '%s mol/100g' % round(random.uniform(0.56, 0.59), 3) else: template_ws.cell('C{}'.format(row)).value = '√' elif item == '馏程': if _material_name.find('A0055') >= 0 or \ _material_name.find('A0063') >= 0: template_ws.cell('C{}'.format(row)).value = \ '%s~%s℃' % (str(180 + random.randint(1, 9)), str(220 - random.randint(1, 9))) elif _material_name.find('A0058') >= 0: template_ws.cell('C{}'.format(row)).value = \ '%s~%s℃' % (str(135 + random.randint(1, 5)), str(150 - random.randint(1, 5))) else: template_ws.cell('C{}'.format(row)).value = '√' else: template_ws.cell('C{}'.format(row)).value = '√' row += 1 template_ws.merge_cells('B11:B{}'.format(10 + len(qc_items))) template_ws.cell('B11').value = material.spec new_filename = '%s-%s-%s-%s.xlsx' % (incoming_date, random.randint(1, 99), material_name, supplier) template_wb.save('%s/reports/IQC/%s' % (module_path(), new_filename))
zh
0.973493
# 去掉中文 # 转为字符串
2.321203
2
engines/flow/extensions/send_email.py
NunoEdgarGFlowHub/rhizome
8
6613720
<reponame>NunoEdgarGFlowHub/rhizome<gh_stars>1-10 """Send emails.""" import smtplib from email.message import EmailMessage from jinja2 import Template from flow.chatbot_engine import Extension class SendEmail(Extension): """SendEmail plugin - defined .flow function sendEmail to send emails.""" def __init__(self, flow): super().__init__(flow) class_name = self.__class__.__module__ + '.' + self.__class__.__name__ flow.register_dot_flow_function('sendEmail', { 'class': class_name, 'method': 'sendEmail'}) def sendEmail(self, args): """Send email.""" node = args[0] params = dict() smtp_config = self.flow.dotbot['bot']['smtp'] flow_vars = self.flow.session.get_var(self.flow.user_id) msg = EmailMessage() msg['Subject'] = self.flow.template_engine.render(self.flow, node['info']['subject'], flow_vars) msg['From'] = smtp_config['email'] msg['To'] = node['info']['recipient'] body = self.flow.template_engine.render(self.flow, node['info']['body'], flow_vars) body = body.replace('\n', '<br />') if node['info'].get('formId', None): # if there is a form defined, build form and add it to the message body flow_form = self.flow.session.get(self.flow.user_id, f"formVars.{node['info']['formId']}") form_template = "{% for form, qa_pair in form_xxxxx.items() %}{{qa_pair.question}}: {{qa_pair.answer}}<br />{% endfor %}" body += "<br /><br />" + Template(form_template).render({'form_xxxxx': flow_form}) msg.set_content("Please see this email with an html compatible email client\n") msg.add_alternative(f"""\ <html> <head></head> <body> {body} </body> </html> """, subtype='html') self.flow.logger.debug(f"Sending email through {smtp_config['server']['host']}:{smtp_config['server']['port']} to {node['info']['recipient']}") smtp = smtplib.SMTP(smtp_config['server']['host'], smtp_config['server']['port']) smtp.set_debuglevel(1) if smtp_config['server'].get('username', "") and smtp_config['server'].get('password', ""): smtp.login(smtp_config['server']['username'], smtp_config['server']['password']) smtp.send_message(msg) smtp.quit()
"""Send emails.""" import smtplib from email.message import EmailMessage from jinja2 import Template from flow.chatbot_engine import Extension class SendEmail(Extension): """SendEmail plugin - defined .flow function sendEmail to send emails.""" def __init__(self, flow): super().__init__(flow) class_name = self.__class__.__module__ + '.' + self.__class__.__name__ flow.register_dot_flow_function('sendEmail', { 'class': class_name, 'method': 'sendEmail'}) def sendEmail(self, args): """Send email.""" node = args[0] params = dict() smtp_config = self.flow.dotbot['bot']['smtp'] flow_vars = self.flow.session.get_var(self.flow.user_id) msg = EmailMessage() msg['Subject'] = self.flow.template_engine.render(self.flow, node['info']['subject'], flow_vars) msg['From'] = smtp_config['email'] msg['To'] = node['info']['recipient'] body = self.flow.template_engine.render(self.flow, node['info']['body'], flow_vars) body = body.replace('\n', '<br />') if node['info'].get('formId', None): # if there is a form defined, build form and add it to the message body flow_form = self.flow.session.get(self.flow.user_id, f"formVars.{node['info']['formId']}") form_template = "{% for form, qa_pair in form_xxxxx.items() %}{{qa_pair.question}}: {{qa_pair.answer}}<br />{% endfor %}" body += "<br /><br />" + Template(form_template).render({'form_xxxxx': flow_form}) msg.set_content("Please see this email with an html compatible email client\n") msg.add_alternative(f"""\ <html> <head></head> <body> {body} </body> </html> """, subtype='html') self.flow.logger.debug(f"Sending email through {smtp_config['server']['host']}:{smtp_config['server']['port']} to {node['info']['recipient']}") smtp = smtplib.SMTP(smtp_config['server']['host'], smtp_config['server']['port']) smtp.set_debuglevel(1) if smtp_config['server'].get('username', "") and smtp_config['server'].get('password', ""): smtp.login(smtp_config['server']['username'], smtp_config['server']['password']) smtp.send_message(msg) smtp.quit()
en
0.629237
Send emails. SendEmail plugin - defined .flow function sendEmail to send emails. Send email. # if there is a form defined, build form and add it to the message body \ <html> <head></head> <body> {body} </body> </html>
2.592585
3
python/tvm/relay/qnn/op/canonicalizations.py
XiaoSong9905/tvm
1
6613721
# 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. """Consist of utilities and methods for lowering QNN into mainline relay.""" from typing import Callable import numpy as np import tvm from tvm import relay def run_const_expr(expr: "relay.Expr") -> np.ndarray: """Evaluate a const expression, receiving result as np array.""" mod = tvm.IRModule.from_expr(expr) vm_exe = relay.create_executor("vm", mod=mod) return vm_exe.evaluate()().asnumpy() def create_integer_lookup_table( floating_point_func: Callable[[np.ndarray], np.ndarray], input_scale: "relay.Expr", input_zero_point: "relay.Expr", output_scale: "relay.Expr", output_zero_point: "relay.Expr", in_axis: int = -1, out_axis: int = -1, in_dtype: str = "uint8", out_dtype: str = "uint8", ) -> np.ndarray: """ Return a table where each input indexes to the output quantizing the given function. Note this also supports mapping unsigned and signed integers to each other. Args: floating_point_func: The numpy function which this table is to approximate input_scale: The scale of the quantized input tensor. input_zero_point: The zero point of the quantized input tensor. output_scale: The scale of the quantized output tensor. output_zero_point: The zero point of the quantized output tensor. in_axis: The axis for multi-channel quantization of the input if applicable. out_axis: The axis for multi-channel quantization of the output if applicable. in_dtype: The dtype of the input tensor. out_dtype: The wanted dtype of the output tensor. Returns: A numpy array where values in quantized space will index to the output in quantized space approximating the given function. """ if not np.issubdtype(np.dtype(in_dtype), np.integer) or not np.issubdtype( np.dtype(out_dtype), np.integer ): raise ValueError( f"Only integer dtypes allowed got {in_dtype} and {out_dtype} for in and out dtypes." ) dtype_info = np.iinfo(in_dtype) num_bits = dtype_info.bits # Use TVMs quantization methods via relay to be consistent # inputs_quantized = np.array(range(dtype_info.min, dtype_info.max + 1)).astype(in_dtype) # First generate a list of all num_bit integer patterns inputs_quantized = np.array(range(0, 2 ** num_bits), dtype=f"uint{num_bits}") # Reinterpret bits as the real datatype # Note what we are doing here is a bit tricky, the canonical view of our lookup table # is using the uintX version. When we run the lookup in the relay graph, we cast the # bit pattern back into this form. inputs_quantized = inputs_quantized.view(in_dtype) inputs_quantized = relay.const(inputs_quantized, dtype=in_dtype) inputs_dequantized = run_const_expr( relay.qnn.op.dequantize( inputs_quantized, input_scale=input_scale, input_zero_point=input_zero_point, axis=in_axis, ) ) output_dequantized = relay.const(floating_point_func(inputs_dequantized)) output_quantized = run_const_expr( relay.qnn.op.quantize( output_dequantized, output_scale, output_zero_point, out_axis, out_dtype ) ) return output_quantized def create_integer_lookup_op( input_arg: "relay.Expr", floating_point_func: Callable[[np.array], np.array], in_scale: "relay.Expr", in_zero_point: "relay.Expr", out_scale: "relay.Expr", out_zero_point: "relay.Expr", in_axis: int = -1, out_axis: int = -1, in_dtype: str = "uint8", out_dtype: str = "uint8", ) -> "relay.Expr": """ Create a quantized version of the given floating point unary operation using table lookup. Args: input_arg: The quantized input to the final function. floating_point_func: The numpy function which this table is to approximate in_scale: The scale of the quantized input tensor. in_zero_point: The zero point of the quantized input tensor. out_scale: The scale of the quantized output tensor. out_zero_point: The zero point of the quantized output tensor. in_axis: The axis for multi-channel quantization of the input if applicable. out_axis: The axis for multi-channel quantization of the output if applicable. in_dtype: The dtype of the input tensor. out_dtype: The wanted dtype of the output tensor. Returns: A Relay expression representing a quantized version of the given function. """ # TODO: handle multi-channel q, below will fail with multi-channel q in_scale = in_scale.data.numpy().item() in_zero_point = in_zero_point.data.numpy().item() out_scale = out_scale.data.numpy().item() out_zero_point = out_zero_point.data.numpy().item() lookup_table = create_integer_lookup_table( floating_point_func, relay.const(in_scale), relay.const(in_zero_point, dtype="int32"), relay.const(out_scale), relay.const(out_zero_point, dtype="int32"), in_axis=in_axis, in_dtype=in_dtype, out_axis=out_axis, out_dtype=out_dtype, ) in_dtype_info = np.iinfo(in_dtype) in_dtype_num_bits = in_dtype_info.bits lookup_table = relay.const(lookup_table) index_tensor = relay.reinterpret(input_arg, f"uint{in_dtype_num_bits}") result = relay.take(lookup_table, index_tensor, axis=0, mode="fast") return result
# 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. """Consist of utilities and methods for lowering QNN into mainline relay.""" from typing import Callable import numpy as np import tvm from tvm import relay def run_const_expr(expr: "relay.Expr") -> np.ndarray: """Evaluate a const expression, receiving result as np array.""" mod = tvm.IRModule.from_expr(expr) vm_exe = relay.create_executor("vm", mod=mod) return vm_exe.evaluate()().asnumpy() def create_integer_lookup_table( floating_point_func: Callable[[np.ndarray], np.ndarray], input_scale: "relay.Expr", input_zero_point: "relay.Expr", output_scale: "relay.Expr", output_zero_point: "relay.Expr", in_axis: int = -1, out_axis: int = -1, in_dtype: str = "uint8", out_dtype: str = "uint8", ) -> np.ndarray: """ Return a table where each input indexes to the output quantizing the given function. Note this also supports mapping unsigned and signed integers to each other. Args: floating_point_func: The numpy function which this table is to approximate input_scale: The scale of the quantized input tensor. input_zero_point: The zero point of the quantized input tensor. output_scale: The scale of the quantized output tensor. output_zero_point: The zero point of the quantized output tensor. in_axis: The axis for multi-channel quantization of the input if applicable. out_axis: The axis for multi-channel quantization of the output if applicable. in_dtype: The dtype of the input tensor. out_dtype: The wanted dtype of the output tensor. Returns: A numpy array where values in quantized space will index to the output in quantized space approximating the given function. """ if not np.issubdtype(np.dtype(in_dtype), np.integer) or not np.issubdtype( np.dtype(out_dtype), np.integer ): raise ValueError( f"Only integer dtypes allowed got {in_dtype} and {out_dtype} for in and out dtypes." ) dtype_info = np.iinfo(in_dtype) num_bits = dtype_info.bits # Use TVMs quantization methods via relay to be consistent # inputs_quantized = np.array(range(dtype_info.min, dtype_info.max + 1)).astype(in_dtype) # First generate a list of all num_bit integer patterns inputs_quantized = np.array(range(0, 2 ** num_bits), dtype=f"uint{num_bits}") # Reinterpret bits as the real datatype # Note what we are doing here is a bit tricky, the canonical view of our lookup table # is using the uintX version. When we run the lookup in the relay graph, we cast the # bit pattern back into this form. inputs_quantized = inputs_quantized.view(in_dtype) inputs_quantized = relay.const(inputs_quantized, dtype=in_dtype) inputs_dequantized = run_const_expr( relay.qnn.op.dequantize( inputs_quantized, input_scale=input_scale, input_zero_point=input_zero_point, axis=in_axis, ) ) output_dequantized = relay.const(floating_point_func(inputs_dequantized)) output_quantized = run_const_expr( relay.qnn.op.quantize( output_dequantized, output_scale, output_zero_point, out_axis, out_dtype ) ) return output_quantized def create_integer_lookup_op( input_arg: "relay.Expr", floating_point_func: Callable[[np.array], np.array], in_scale: "relay.Expr", in_zero_point: "relay.Expr", out_scale: "relay.Expr", out_zero_point: "relay.Expr", in_axis: int = -1, out_axis: int = -1, in_dtype: str = "uint8", out_dtype: str = "uint8", ) -> "relay.Expr": """ Create a quantized version of the given floating point unary operation using table lookup. Args: input_arg: The quantized input to the final function. floating_point_func: The numpy function which this table is to approximate in_scale: The scale of the quantized input tensor. in_zero_point: The zero point of the quantized input tensor. out_scale: The scale of the quantized output tensor. out_zero_point: The zero point of the quantized output tensor. in_axis: The axis for multi-channel quantization of the input if applicable. out_axis: The axis for multi-channel quantization of the output if applicable. in_dtype: The dtype of the input tensor. out_dtype: The wanted dtype of the output tensor. Returns: A Relay expression representing a quantized version of the given function. """ # TODO: handle multi-channel q, below will fail with multi-channel q in_scale = in_scale.data.numpy().item() in_zero_point = in_zero_point.data.numpy().item() out_scale = out_scale.data.numpy().item() out_zero_point = out_zero_point.data.numpy().item() lookup_table = create_integer_lookup_table( floating_point_func, relay.const(in_scale), relay.const(in_zero_point, dtype="int32"), relay.const(out_scale), relay.const(out_zero_point, dtype="int32"), in_axis=in_axis, in_dtype=in_dtype, out_axis=out_axis, out_dtype=out_dtype, ) in_dtype_info = np.iinfo(in_dtype) in_dtype_num_bits = in_dtype_info.bits lookup_table = relay.const(lookup_table) index_tensor = relay.reinterpret(input_arg, f"uint{in_dtype_num_bits}") result = relay.take(lookup_table, index_tensor, axis=0, mode="fast") return result
en
0.75485
# 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. Consist of utilities and methods for lowering QNN into mainline relay. Evaluate a const expression, receiving result as np array. Return a table where each input indexes to the output quantizing the given function. Note this also supports mapping unsigned and signed integers to each other. Args: floating_point_func: The numpy function which this table is to approximate input_scale: The scale of the quantized input tensor. input_zero_point: The zero point of the quantized input tensor. output_scale: The scale of the quantized output tensor. output_zero_point: The zero point of the quantized output tensor. in_axis: The axis for multi-channel quantization of the input if applicable. out_axis: The axis for multi-channel quantization of the output if applicable. in_dtype: The dtype of the input tensor. out_dtype: The wanted dtype of the output tensor. Returns: A numpy array where values in quantized space will index to the output in quantized space approximating the given function. # Use TVMs quantization methods via relay to be consistent # inputs_quantized = np.array(range(dtype_info.min, dtype_info.max + 1)).astype(in_dtype) # First generate a list of all num_bit integer patterns # Reinterpret bits as the real datatype # Note what we are doing here is a bit tricky, the canonical view of our lookup table # is using the uintX version. When we run the lookup in the relay graph, we cast the # bit pattern back into this form. Create a quantized version of the given floating point unary operation using table lookup. Args: input_arg: The quantized input to the final function. floating_point_func: The numpy function which this table is to approximate in_scale: The scale of the quantized input tensor. in_zero_point: The zero point of the quantized input tensor. out_scale: The scale of the quantized output tensor. out_zero_point: The zero point of the quantized output tensor. in_axis: The axis for multi-channel quantization of the input if applicable. out_axis: The axis for multi-channel quantization of the output if applicable. in_dtype: The dtype of the input tensor. out_dtype: The wanted dtype of the output tensor. Returns: A Relay expression representing a quantized version of the given function. # TODO: handle multi-channel q, below will fail with multi-channel q
2.022499
2
getThreads.py
tinkerNamedFerro/biz_insights
0
6613722
<filename>getThreads.py import requests import bs4 import sys, getopt, os import re import pprint import json import hashlib import openpyxl import datetime import time from joblib import Parallel, delayed from tqdm import tqdm from selenium import webdriver from CoinDict import * from scrapers.ChanOfficial import * from scrapers.ChanArchieve import * from mongo_db.tickerTable import * import multiprocessing as mp def ThreadIDGet(): try: os.remove('tids.txt') except: print("Did NOT delete tids.txt") url = 'http://boards.4chan.org/biz/catalog' driver = webdriver.Chrome() driver.get(url) res = driver.page_source soup = bs4.BeautifulSoup(res, 'lxml') body = soup.find('body') content = body.find(id="content") thread = content.find(id="threads") ThR = re.compile(r'(thread-)(\d\d\d\d\d\d\d\d)') threadlist = ThR.findall(str(thread)) ThreadIDs = open("tids.txt", 'a') for i in range(1, len(threadlist)): ThreadIDs.write(threadlist[i][1] + '\n') print('IDs Obtained') driver.close() ThreadIDs.close() def TextGet(): ThreadIDGet() try: os.remove('text.txt') except: print("Did NOT delete text.txt") tids = open('tids.txt','r') tlist = tids.readlines() print("Scanning threads") tickerDb = MongoDB_Biz_Ticker_Mentions() for i in tqdm(range(0, len(tlist)-1)): # threadJson = fullThreadScrape(tlist[i][:-2],url) tickerOnlyScrape(tlist[i],tickerDb) print('Scrape Complete') def TextGetArchieve(fromPage, toPage): # page = 7000 for page in range(fromPage,toPage): try: tlist = getTidsOnPage(page) # print("Scanning threads") tickerDb = MongoDB_Biz_Ticker_Mentions() # for i in tqdm(range(0, len(tlist)-1)): for i in range(0, len(tlist)-1): # threadJson = fullThreadScrape(tlist[i][:-2],url) tickerOnlyScrapeArchieve(tlist[i],tickerDb) except Exception as e: print("ERROR:" + e) print("PAGE IS: " + str(page)) def Count(row): file = open('text.txt', 'r') postlist = file.readlines() checklist = [row['aka'][0],row['aka'][0].lower(),(row['name']),(row['name'].lower())] Count = 0 print(checklist) for i in range(0,len(postlist)): for x in checklist: if x in postlist[i].split(): Count += 1 break else: continue file.close() return Count # NewBook('tester') # while True: # while True: # ThreadIDGet() # TextGet() # Update() def main(argv): # Generate list of coins generateCurrenciesList() # Load json file for coin list with open('data.json') as json_file: CD = json.load(json_file) startPage = 0 endPage = 0 parallelCount = 0 try: opts, args = getopt.getopt(argv,'s:e:p:') except getopt.GetoptError: print ('startBrainWallet.py -s <startPage> -e <endPage> -p <parallelCount>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('startBrainWallet.py -s <startPage> -e <endPage> -p <parallelCount>') sys.exit() elif opt in ("-s", "--start"): startPage = int(arg) elif opt in ("-e", "--end"): endPage = int(arg) elif opt in ("-p", "--parallelCount"): parallelCount = int(arg) if parallelCount == 0: print(startPage) TextGetArchieve(startPage,endPage) elif parallelCount == -1: while True: TextGetArchieve(startPage,endPage) else: # Get work load for each worker pageSegmentsDealt = (endPage - startPage)/parallelCount # Init pool pool = mp.Pool(parallelCount) for instance in range(0,int(parallelCount)): instanceStartPage = int(round(startPage+(instance*pageSegmentsDealt))) instanceEndPage = int(round(startPage+((instance+1) *pageSegmentsDealt))) pool.apply_async(TextGetArchieve, args=(instanceStartPage, instanceEndPage)) # print(values) pool.close() # prevent freeze support error for windows https://minerl.io/docs/notes/windows.html if __name__ == '__main__': main(sys.argv[1:])
<filename>getThreads.py import requests import bs4 import sys, getopt, os import re import pprint import json import hashlib import openpyxl import datetime import time from joblib import Parallel, delayed from tqdm import tqdm from selenium import webdriver from CoinDict import * from scrapers.ChanOfficial import * from scrapers.ChanArchieve import * from mongo_db.tickerTable import * import multiprocessing as mp def ThreadIDGet(): try: os.remove('tids.txt') except: print("Did NOT delete tids.txt") url = 'http://boards.4chan.org/biz/catalog' driver = webdriver.Chrome() driver.get(url) res = driver.page_source soup = bs4.BeautifulSoup(res, 'lxml') body = soup.find('body') content = body.find(id="content") thread = content.find(id="threads") ThR = re.compile(r'(thread-)(\d\d\d\d\d\d\d\d)') threadlist = ThR.findall(str(thread)) ThreadIDs = open("tids.txt", 'a') for i in range(1, len(threadlist)): ThreadIDs.write(threadlist[i][1] + '\n') print('IDs Obtained') driver.close() ThreadIDs.close() def TextGet(): ThreadIDGet() try: os.remove('text.txt') except: print("Did NOT delete text.txt") tids = open('tids.txt','r') tlist = tids.readlines() print("Scanning threads") tickerDb = MongoDB_Biz_Ticker_Mentions() for i in tqdm(range(0, len(tlist)-1)): # threadJson = fullThreadScrape(tlist[i][:-2],url) tickerOnlyScrape(tlist[i],tickerDb) print('Scrape Complete') def TextGetArchieve(fromPage, toPage): # page = 7000 for page in range(fromPage,toPage): try: tlist = getTidsOnPage(page) # print("Scanning threads") tickerDb = MongoDB_Biz_Ticker_Mentions() # for i in tqdm(range(0, len(tlist)-1)): for i in range(0, len(tlist)-1): # threadJson = fullThreadScrape(tlist[i][:-2],url) tickerOnlyScrapeArchieve(tlist[i],tickerDb) except Exception as e: print("ERROR:" + e) print("PAGE IS: " + str(page)) def Count(row): file = open('text.txt', 'r') postlist = file.readlines() checklist = [row['aka'][0],row['aka'][0].lower(),(row['name']),(row['name'].lower())] Count = 0 print(checklist) for i in range(0,len(postlist)): for x in checklist: if x in postlist[i].split(): Count += 1 break else: continue file.close() return Count # NewBook('tester') # while True: # while True: # ThreadIDGet() # TextGet() # Update() def main(argv): # Generate list of coins generateCurrenciesList() # Load json file for coin list with open('data.json') as json_file: CD = json.load(json_file) startPage = 0 endPage = 0 parallelCount = 0 try: opts, args = getopt.getopt(argv,'s:e:p:') except getopt.GetoptError: print ('startBrainWallet.py -s <startPage> -e <endPage> -p <parallelCount>') sys.exit(2) for opt, arg in opts: if opt == '-h': print ('startBrainWallet.py -s <startPage> -e <endPage> -p <parallelCount>') sys.exit() elif opt in ("-s", "--start"): startPage = int(arg) elif opt in ("-e", "--end"): endPage = int(arg) elif opt in ("-p", "--parallelCount"): parallelCount = int(arg) if parallelCount == 0: print(startPage) TextGetArchieve(startPage,endPage) elif parallelCount == -1: while True: TextGetArchieve(startPage,endPage) else: # Get work load for each worker pageSegmentsDealt = (endPage - startPage)/parallelCount # Init pool pool = mp.Pool(parallelCount) for instance in range(0,int(parallelCount)): instanceStartPage = int(round(startPage+(instance*pageSegmentsDealt))) instanceEndPage = int(round(startPage+((instance+1) *pageSegmentsDealt))) pool.apply_async(TextGetArchieve, args=(instanceStartPage, instanceEndPage)) # print(values) pool.close() # prevent freeze support error for windows https://minerl.io/docs/notes/windows.html if __name__ == '__main__': main(sys.argv[1:])
en
0.549888
# threadJson = fullThreadScrape(tlist[i][:-2],url) # page = 7000 # print("Scanning threads") # for i in tqdm(range(0, len(tlist)-1)): # threadJson = fullThreadScrape(tlist[i][:-2],url) # NewBook('tester') # while True: # while True: # ThreadIDGet() # TextGet() # Update() # Generate list of coins # Load json file for coin list # Get work load for each worker # Init pool # print(values) # prevent freeze support error for windows https://minerl.io/docs/notes/windows.html
2.577859
3
setup.py
senavs/BitJoy
0
6613723
import setuptools with open('README.md') as file: long_description = file.read() setuptools.setup( name='bitjoy', version='1.1', license='MIT', description='Bit, Bytes and Logical Gates Abstraction.', author='<NAME>', author_email='<EMAIL>', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/senavs/BitJoy', keywords=['bitjoy', 'bit', 'bytes', 'logical-operators', 'int_to_bytes', 'half-adder', 'full-adder', 'boolean', 'gates', 'abstraction'], packages=['bitjoy', 'bitjoy.dtypes', 'bitjoy.utils'], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], python_required='>=3.6' )
import setuptools with open('README.md') as file: long_description = file.read() setuptools.setup( name='bitjoy', version='1.1', license='MIT', description='Bit, Bytes and Logical Gates Abstraction.', author='<NAME>', author_email='<EMAIL>', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/senavs/BitJoy', keywords=['bitjoy', 'bit', 'bytes', 'logical-operators', 'int_to_bytes', 'half-adder', 'full-adder', 'boolean', 'gates', 'abstraction'], packages=['bitjoy', 'bitjoy.dtypes', 'bitjoy.utils'], classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], python_required='>=3.6' )
none
1
1.508226
2
go/py/blah.py
brightpuddle/playground
0
6613724
<reponame>brightpuddle/playground<gh_stars>0 print('w00t')
print('w00t')
none
1
1.1543
1
xautodl/xmodels/transformers_quantum.py
Joey61Liuyi/AutoDL-Projects
817
6613725
<gh_stars>100-1000 ##################################################### # Copyright (c) <NAME> [GitHub D-X-Y], 2021.06 # ##################################################### # Vision Transformer: arxiv.org/pdf/2010.11929.pdf # ##################################################### import copy, math from functools import partial from typing import Optional, Text, List import torch import torch.nn as nn import torch.nn.functional as F from xautodl import spaces from xautodl import xlayers from xautodl.xlayers import weight_init class SuperQuaT(xlayers.SuperModule): """The super transformer for transformer.""" def __init__( self, image_size, patch_size, num_classes, dim, depth, heads, mlp_multiplier=4, channels=3, dropout=0.0, att_dropout=0.0, ): super(SuperQuaT, self).__init__() image_height, image_width = pair(image_size) patch_height, patch_width = pair(patch_size) if image_height % patch_height != 0 or image_width % patch_width != 0: raise ValueError("Image dimensions must be divisible by the patch size.") num_patches = (image_height // patch_height) * (image_width // patch_width) patch_dim = channels * patch_height * patch_width self.to_patch_embedding = xlayers.SuperSequential( xlayers.SuperReArrange( "b c (h p1) (w p2) -> b (h w) (p1 p2 c)", p1=patch_height, p2=patch_width, ), xlayers.SuperLinear(patch_dim, dim), ) self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim)) self.cls_token = nn.Parameter(torch.randn(1, 1, dim)) self.dropout = nn.Dropout(dropout) # build the transformer encode layers layers = [] for ilayer in range(depth): layers.append( xlayers.SuperTransformerEncoderLayer( dim, heads, False, mlp_multiplier, dropout=dropout, att_dropout=att_dropout, ) ) self.backbone = xlayers.SuperSequential(*layers) self.cls_head = xlayers.SuperSequential( xlayers.SuperLayerNorm1D(dim), xlayers.SuperLinear(dim, num_classes) ) weight_init.trunc_normal_(self.cls_token, std=0.02) self.apply(_init_weights) @property def abstract_search_space(self): raise NotImplementedError def apply_candidate(self, abstract_child: spaces.VirtualNode): super(SuperQuaT, self).apply_candidate(abstract_child) raise NotImplementedError def forward_candidate(self, input: torch.Tensor) -> torch.Tensor: raise NotImplementedError def forward_raw(self, input: torch.Tensor) -> torch.Tensor: tensors = self.to_patch_embedding(input) batch, seq, _ = tensors.shape cls_tokens = self.cls_token.expand(batch, -1, -1) feats = torch.cat((cls_tokens, tensors), dim=1) feats = feats + self.pos_embedding[:, : seq + 1, :] feats = self.dropout(feats) feats = self.backbone(feats) x = feats[:, 0] # the features for cls-token return self.cls_head(x) def get_transformer(config): if isinstance(config, str) and config.lower() in name2config: config = name2config[config.lower()] if not isinstance(config, dict): raise ValueError("Invalid Configuration: {:}".format(config)) model_type = config.get("type", "vit").lower() if model_type == "vit": model = SuperQuaT( image_size=config.get("image_size"), patch_size=config.get("patch_size"), num_classes=config.get("num_classes"), dim=config.get("dim"), depth=config.get("depth"), heads=config.get("heads"), dropout=config.get("dropout"), att_dropout=config.get("att_dropout"), ) else: raise ValueError("Unknown model type: {:}".format(model_type)) return model
##################################################### # Copyright (c) <NAME> [GitHub D-X-Y], 2021.06 # ##################################################### # Vision Transformer: arxiv.org/pdf/2010.11929.pdf # ##################################################### import copy, math from functools import partial from typing import Optional, Text, List import torch import torch.nn as nn import torch.nn.functional as F from xautodl import spaces from xautodl import xlayers from xautodl.xlayers import weight_init class SuperQuaT(xlayers.SuperModule): """The super transformer for transformer.""" def __init__( self, image_size, patch_size, num_classes, dim, depth, heads, mlp_multiplier=4, channels=3, dropout=0.0, att_dropout=0.0, ): super(SuperQuaT, self).__init__() image_height, image_width = pair(image_size) patch_height, patch_width = pair(patch_size) if image_height % patch_height != 0 or image_width % patch_width != 0: raise ValueError("Image dimensions must be divisible by the patch size.") num_patches = (image_height // patch_height) * (image_width // patch_width) patch_dim = channels * patch_height * patch_width self.to_patch_embedding = xlayers.SuperSequential( xlayers.SuperReArrange( "b c (h p1) (w p2) -> b (h w) (p1 p2 c)", p1=patch_height, p2=patch_width, ), xlayers.SuperLinear(patch_dim, dim), ) self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim)) self.cls_token = nn.Parameter(torch.randn(1, 1, dim)) self.dropout = nn.Dropout(dropout) # build the transformer encode layers layers = [] for ilayer in range(depth): layers.append( xlayers.SuperTransformerEncoderLayer( dim, heads, False, mlp_multiplier, dropout=dropout, att_dropout=att_dropout, ) ) self.backbone = xlayers.SuperSequential(*layers) self.cls_head = xlayers.SuperSequential( xlayers.SuperLayerNorm1D(dim), xlayers.SuperLinear(dim, num_classes) ) weight_init.trunc_normal_(self.cls_token, std=0.02) self.apply(_init_weights) @property def abstract_search_space(self): raise NotImplementedError def apply_candidate(self, abstract_child: spaces.VirtualNode): super(SuperQuaT, self).apply_candidate(abstract_child) raise NotImplementedError def forward_candidate(self, input: torch.Tensor) -> torch.Tensor: raise NotImplementedError def forward_raw(self, input: torch.Tensor) -> torch.Tensor: tensors = self.to_patch_embedding(input) batch, seq, _ = tensors.shape cls_tokens = self.cls_token.expand(batch, -1, -1) feats = torch.cat((cls_tokens, tensors), dim=1) feats = feats + self.pos_embedding[:, : seq + 1, :] feats = self.dropout(feats) feats = self.backbone(feats) x = feats[:, 0] # the features for cls-token return self.cls_head(x) def get_transformer(config): if isinstance(config, str) and config.lower() in name2config: config = name2config[config.lower()] if not isinstance(config, dict): raise ValueError("Invalid Configuration: {:}".format(config)) model_type = config.get("type", "vit").lower() if model_type == "vit": model = SuperQuaT( image_size=config.get("image_size"), patch_size=config.get("patch_size"), num_classes=config.get("num_classes"), dim=config.get("dim"), depth=config.get("depth"), heads=config.get("heads"), dropout=config.get("dropout"), att_dropout=config.get("att_dropout"), ) else: raise ValueError("Unknown model type: {:}".format(model_type)) return model
de
0.525542
##################################################### # Copyright (c) <NAME> [GitHub D-X-Y], 2021.06 # ##################################################### # Vision Transformer: arxiv.org/pdf/2010.11929.pdf # ##################################################### The super transformer for transformer. # build the transformer encode layers # the features for cls-token
2.189486
2
setup.py
ekta1224/jellyfish
0
6613726
#! /usr/bin/env python from setuptools import setup setup(name='Jellyfish', version='0.1', description='Tools to plot and analyze N-body simulations of hosts and satellites galaxies', author='<NAME> and <NAME>', author_email='<EMAIL>', install_requieres=['numpy', 'scipy', 'matplotlib', 'astropy', 'pygadgetreader'], packages=['jellyfish'], )
#! /usr/bin/env python from setuptools import setup setup(name='Jellyfish', version='0.1', description='Tools to plot and analyze N-body simulations of hosts and satellites galaxies', author='<NAME> and <NAME>', author_email='<EMAIL>', install_requieres=['numpy', 'scipy', 'matplotlib', 'astropy', 'pygadgetreader'], packages=['jellyfish'], )
ru
0.148623
#! /usr/bin/env python
1.034745
1
gestao/contrato/views/equipe_contrato.py
Smartboxweb98/gestao_empresarial
3
6613727
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from gestao.contrato.models.contrato.Contrato import Contrato from gestao.contrato.models.equipe.FuncionarioContrato import FuncionarioContrato from gestao.recursos_humanos.models.funcionario.FuncionarioCargo import FuncionarioCargo from gestao.contrato.forms.FuncionarioContratoForm import FuncionarioContratoForm def equipe_contrato( request, id_contrato): title = u"Equipe do Contrato" contrato = get_object_or_404(Contrato, pk=id_contrato) equipe_dado = FuncionarioContrato.objects.filter(contrato=contrato) funcionario_contrato = FuncionarioContrato(contrato=contrato) if request.method == "POST": form_equipe_contrato = FuncionarioContratoForm(request.POST, instance=funcionario_contrato) if form_equipe_contrato.is_valid(): form_equipe_contrato.save() funcionario_contrato = FuncionarioContrato(contrato=contrato) form_equipe_contrato = FuncionarioContratoForm(instance=funcionario_contrato) else: form_equipe_contrato = FuncionarioContratoForm(instance=funcionario_contrato) equipe = [] for func in equipe_dado: cargos = FuncionarioCargo.objects.filter(funcionario=func).order_by("-data_inicial") if cargos: equipe.append( ( func, cargos[0] ) ) else: equipe.append( ( func, None) ) return render_to_response('equipe_contrato.html',locals(), context_instance=RequestContext(request))
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from gestao.contrato.models.contrato.Contrato import Contrato from gestao.contrato.models.equipe.FuncionarioContrato import FuncionarioContrato from gestao.recursos_humanos.models.funcionario.FuncionarioCargo import FuncionarioCargo from gestao.contrato.forms.FuncionarioContratoForm import FuncionarioContratoForm def equipe_contrato( request, id_contrato): title = u"Equipe do Contrato" contrato = get_object_or_404(Contrato, pk=id_contrato) equipe_dado = FuncionarioContrato.objects.filter(contrato=contrato) funcionario_contrato = FuncionarioContrato(contrato=contrato) if request.method == "POST": form_equipe_contrato = FuncionarioContratoForm(request.POST, instance=funcionario_contrato) if form_equipe_contrato.is_valid(): form_equipe_contrato.save() funcionario_contrato = FuncionarioContrato(contrato=contrato) form_equipe_contrato = FuncionarioContratoForm(instance=funcionario_contrato) else: form_equipe_contrato = FuncionarioContratoForm(instance=funcionario_contrato) equipe = [] for func in equipe_dado: cargos = FuncionarioCargo.objects.filter(funcionario=func).order_by("-data_inicial") if cargos: equipe.append( ( func, cargos[0] ) ) else: equipe.append( ( func, None) ) return render_to_response('equipe_contrato.html',locals(), context_instance=RequestContext(request))
en
0.769321
# -*- coding: utf-8 -*-
2.000074
2
kglib/utils/IMF_utils.py
kgullikson88/gullikson-scripts
4
6613728
<filename>kglib/utils/IMF_utils.py """ Various codes to work with the initial mass function. Stolen shamelessly from <NAME>'s agpy code: https://code.google.com/p/agpy/source/browse/trunk/agpy/imf.py """ from __future__ import print_function, division, absolute_import import types # I use typechecking. Is there a better way to do this? (see inverse_imf below) import numpy as np class MassFunction(object): """ Generic Mass Function class """ def dndm(self, m, **kwargs): """ The differential form of the mass function, d N(M) / dM """ return self(m, integral_form=False, **kwargs) def n_of_m(self, m, **kwargs): """ The integral form of the mass function, N(M) """ return self(m, integral_form=True, **kwargs) def integrate(self, mlow, mhigh, **kwargs): """ Integrate the mass function over some range """ import scipy.integrate return scipy.integrate.quad(self, mlow, mhigh, **kwargs) class Salpeter(MassFunction): def __init__(self, alpha=2.35): """ Create a default Salpeter mass function, i.e. a power-law mass function the Salpeter 1955 IMF: dn/dm ~ m^-2.35 """ self.alpha = alpha def __call__(self, m, integral_form=False): if integral_form: return m**(-(self.alpha - 1)) else: return m**(-self.alpha) # three codes for dn/dlog(m) salpeter = Salpeter() class BrokenPowerLaw(MassFunction): def __init__(self, breaks, mmin, mmax): self.breaks = breaks self.normalization = self.integrate(mmin, mmax)[0] def __call__(self, m, integral_form=False): zeta = 0 b_low = 0 alp_low = 0 for ii,b in enumerate(self.breaks): if integral_form: alp = self.breaks[b] - 1 else: alp = self.breaks[b] if b == 'last': zeta += m**(-alp) * (b_low**(-alp+alp_low)) * (m>b_low) else: mask = ((m<b)*(m>b_low)) zeta += m**(-alp) * (b**(-alp+alp_low)) *mask alp_low = alp b_low = b if hasattr(self,'normalization'): return zeta/self.normalization else: return zeta #kroupa = BrokenPowerLaw(breaks={0.08:-0.3, 0.5:1.3, 'last':2.3},mmin=0.03,mmax=120) class Kroupa(MassFunction): def __init__(self, mmin=0.03): """ """ self.mmin = mmin def __call__(self, m, p1=0.3, p2=1.3, p3=2.3, break1=0.08, break2=0.5, integral_form=False): """ Kroupa 2001 IMF (http://arxiv.org/abs/astro-ph/0009005, http://adsabs.harvard.edu/abs/2001MNRAS.322..231K) """ m = np.array(m) binv = ((break1**(-(p1-1)) - self.mmin**(-(p1-1)))/(1-p1) + (break2**(-(p2-1)) - break1**(-(p2-1))) * (break1**(p2-p1))/(1-p2) + (- break2**(-(p3-1))) * (break1**(p2-p1)) * (break2**(p3-p2))/(1-p3)) b = 1./binv c = b * break1**(p2-p1) d = c * break2**(p3-p2) zeta = (b*(m**(-(p1))) * (m<break1) + c*(m**(-(p2))) * (m>=break1) * (m<break2) + d*(m**(-(p3))) * (m>=break2)) if integral_form: return zeta * m else: return zeta kroupa = Kroupa() def chabrier(m, integral=False): """ Chabrier 2003 IMF http://adsabs.harvard.edu/abs/2003PASP..115..763C (only valid for m < 1 msun) not sure which of these to use... integral is NOT IMPLEMENTED """ if integral: print("Chabrier integral NOT IMPLEMENTED") # This system MF can be parameterized by the same type of lognormal form as # the single MF (eq. [17]), with the same normalization at 1 Msun, with the # coefficients (Chabrier 2003) return 0.86 * np.exp(-1*(np.log10(m)-np.log10(0.22))**2/(2*0.57**2)) # This analytic form for the disk MF for single objects below 1 Msun, within these uncertainties, is given by the following lognormal form (Chabrier 2003): return 0.158 * np.exp(-1*(np.log10(m)-np.log10(0.08))**2/(2*0.69**2)) def schechter(m,A=1,beta=2,m0=100, integral=False): """ A Schechter function with arbitrary defaults (integral may not be correct - exponent hasn't been dealt with at all) $$ A m^{-\\beta} e^{-m/m_0} $$ Parameters ---------- m : np.ndarray List of masses for which to compute the Schechter function A : float Arbitrary amplitude of the Schechter function beta : float Power law exponent m0 : float Characteristic mass (mass at which exponential decay takes over) Returns ------- p(m) - the (unnormalized) probability of an object of a given mass as a function of that object's mass (though you could interpret mass as anything, it's just a number) """ if integral: beta -= 1 return A*m**-beta * np.exp(-m/m0) def modified_schechter(m, m1, **kwargs): """ A Schechter function with a low-level exponential cutoff " Parameters ---------- m : np.ndarray List of masses for which to compute the Schechter function m1 : float Characteristic minimum mass (exponential decay below this mass) ** See schecter for other parameters ** Returns ------- p(m) - the (unnormalized) probability of an object of a given mass as a function of that object's mass (though you could interpret mass as anything, it's just a number) """ return schechter(m, **kwargs) * np.exp(-m1/m) try: import scipy def schechter_cdf(m,A=1,beta=2,m0=100,mmin=10,mmax=None,npts=1e4): """ Return the CDF value of a given mass for a set mmin,mmax mmax will default to 10 m0 if not specified Analytic integral of the Schechter function: http://www.wolframalpha.com/input/?i=integral%28x^-a+exp%28-x%2Fm%29+dx%29 """ if mmax is None: mmax = 10*m0 # integrate the CDF from the minimum to maximum # undefined posint = -m0 * mmax**-beta * (mmax/m0)**beta * scipy.special.gammainc(1-beta, mmax/m0) # undefined negint = -m0 * mmin**-beta * (mmin/m0)**beta * scipy.special.gammainc(1-beta, mmin/m0) posint = -mmax**(1-beta) * scipy.special.expn(beta, mmax/m0) negint = -mmin**(1-beta) * scipy.special.expn(beta, mmin/m0) tot = posint-negint # normalize by the integral # undefined ret = (-m0 * m**-beta * (m/m0)**beta * scipy.special.gammainc(1-beta, m/m0)) / tot ret = (-m**(1-beta) * scipy.special.expn(beta, m/m0) - negint)/ tot return ret def sh_cdf_func(**kwargs): return lambda x: schechter_cdf(x, **kwargs) except ImportError: pass #def schechter_inv(m): # """ # Return p(m) # """ # return scipy.interpolate.interp1d(shfun,arange(.1,20,.01),bounds_error=False,fill_value=20.) def integrate(fn=kroupa, bins=np.logspace(-2,2,500)): xax = (bins[:-1]+bins[1:])/2. integral = (bins[1:]-bins[:-1]) * (fn(bins[:-1])+fn(bins[1:])) / 2. return xax,integral def m_integrate(fn=kroupa, bins=np.logspace(-2,2,500)): xax = (bins[:-1]+bins[1:])/2. integral = xax*(bins[1:]-bins[:-1]) * (fn(bins[:-1])+fn(bins[1:])) / 2. return xax,integral def cumint(fn=kroupa, bins=np.logspace(-2,2,500)): xax,integral = integrate(fn,bins) return integral.cumsum() / integral.sum() def m_cumint(fn=kroupa, bins=np.logspace(-2,2,500)): xax,integral = m_integrate(fn,bins) return integral.cumsum() / integral.sum() massfunctions = {'kroupa':kroupa, 'salpeter':salpeter, 'chabrier':chabrier, 'schechter':schechter,'modified_schechter':modified_schechter} if hasattr(massfunctions, '__iteritems__'): reverse_mf_dict = {v:k for k,v in massfunctions.iteritems()} else: reverse_mf_dict = {v:k for k,v in massfunctions.items()} # salpeter and schechter selections are arbitrary mostcommonmass = {'kroupa':0.08, 'salpeter':0.01, 'chabrier':0.23, 'schecter':0.01,'modified_schechter':0.01} def get_massfunc(massfunc): if type(massfunc) is types.FunctionType or hasattr(massfunc,'__call__'): return massfunc elif type(massfunc) is str: return massfunctions[massfunc] else: raise ValueError("massfunc must either be a string in the set %s or a function" % (",".join(massfunctions.keys()))) def get_massfunc_name(massfunc): if massfunc in reverse_mf_dict: return reverse_mf_dict[massfunc] elif type(massfunc) is str: return massfunc elif hasattr(massfunc,'__name__'): return massfunc.__name__ else: raise ValueError("invalid mass function") def inverse_imf(p, nbins=1000, mmin=0.03, mmax=120, massfunc='kroupa', **kwargs): """ Inverse mass function massfunc can be 'kroupa', 'chabrier', 'salpeter', 'schechter', or a function """ masses = np.logspace(np.log10(mmin),np.log10(mmax),nbins) mf = get_massfunc(massfunc)(masses, integral_form=True, **kwargs) mfcum = mf.cumsum() mfcum /= mfcum.max() # normalize to sum (cdf) return np.interp(p, mfcum, masses)
<filename>kglib/utils/IMF_utils.py """ Various codes to work with the initial mass function. Stolen shamelessly from <NAME>'s agpy code: https://code.google.com/p/agpy/source/browse/trunk/agpy/imf.py """ from __future__ import print_function, division, absolute_import import types # I use typechecking. Is there a better way to do this? (see inverse_imf below) import numpy as np class MassFunction(object): """ Generic Mass Function class """ def dndm(self, m, **kwargs): """ The differential form of the mass function, d N(M) / dM """ return self(m, integral_form=False, **kwargs) def n_of_m(self, m, **kwargs): """ The integral form of the mass function, N(M) """ return self(m, integral_form=True, **kwargs) def integrate(self, mlow, mhigh, **kwargs): """ Integrate the mass function over some range """ import scipy.integrate return scipy.integrate.quad(self, mlow, mhigh, **kwargs) class Salpeter(MassFunction): def __init__(self, alpha=2.35): """ Create a default Salpeter mass function, i.e. a power-law mass function the Salpeter 1955 IMF: dn/dm ~ m^-2.35 """ self.alpha = alpha def __call__(self, m, integral_form=False): if integral_form: return m**(-(self.alpha - 1)) else: return m**(-self.alpha) # three codes for dn/dlog(m) salpeter = Salpeter() class BrokenPowerLaw(MassFunction): def __init__(self, breaks, mmin, mmax): self.breaks = breaks self.normalization = self.integrate(mmin, mmax)[0] def __call__(self, m, integral_form=False): zeta = 0 b_low = 0 alp_low = 0 for ii,b in enumerate(self.breaks): if integral_form: alp = self.breaks[b] - 1 else: alp = self.breaks[b] if b == 'last': zeta += m**(-alp) * (b_low**(-alp+alp_low)) * (m>b_low) else: mask = ((m<b)*(m>b_low)) zeta += m**(-alp) * (b**(-alp+alp_low)) *mask alp_low = alp b_low = b if hasattr(self,'normalization'): return zeta/self.normalization else: return zeta #kroupa = BrokenPowerLaw(breaks={0.08:-0.3, 0.5:1.3, 'last':2.3},mmin=0.03,mmax=120) class Kroupa(MassFunction): def __init__(self, mmin=0.03): """ """ self.mmin = mmin def __call__(self, m, p1=0.3, p2=1.3, p3=2.3, break1=0.08, break2=0.5, integral_form=False): """ Kroupa 2001 IMF (http://arxiv.org/abs/astro-ph/0009005, http://adsabs.harvard.edu/abs/2001MNRAS.322..231K) """ m = np.array(m) binv = ((break1**(-(p1-1)) - self.mmin**(-(p1-1)))/(1-p1) + (break2**(-(p2-1)) - break1**(-(p2-1))) * (break1**(p2-p1))/(1-p2) + (- break2**(-(p3-1))) * (break1**(p2-p1)) * (break2**(p3-p2))/(1-p3)) b = 1./binv c = b * break1**(p2-p1) d = c * break2**(p3-p2) zeta = (b*(m**(-(p1))) * (m<break1) + c*(m**(-(p2))) * (m>=break1) * (m<break2) + d*(m**(-(p3))) * (m>=break2)) if integral_form: return zeta * m else: return zeta kroupa = Kroupa() def chabrier(m, integral=False): """ Chabrier 2003 IMF http://adsabs.harvard.edu/abs/2003PASP..115..763C (only valid for m < 1 msun) not sure which of these to use... integral is NOT IMPLEMENTED """ if integral: print("Chabrier integral NOT IMPLEMENTED") # This system MF can be parameterized by the same type of lognormal form as # the single MF (eq. [17]), with the same normalization at 1 Msun, with the # coefficients (Chabrier 2003) return 0.86 * np.exp(-1*(np.log10(m)-np.log10(0.22))**2/(2*0.57**2)) # This analytic form for the disk MF for single objects below 1 Msun, within these uncertainties, is given by the following lognormal form (Chabrier 2003): return 0.158 * np.exp(-1*(np.log10(m)-np.log10(0.08))**2/(2*0.69**2)) def schechter(m,A=1,beta=2,m0=100, integral=False): """ A Schechter function with arbitrary defaults (integral may not be correct - exponent hasn't been dealt with at all) $$ A m^{-\\beta} e^{-m/m_0} $$ Parameters ---------- m : np.ndarray List of masses for which to compute the Schechter function A : float Arbitrary amplitude of the Schechter function beta : float Power law exponent m0 : float Characteristic mass (mass at which exponential decay takes over) Returns ------- p(m) - the (unnormalized) probability of an object of a given mass as a function of that object's mass (though you could interpret mass as anything, it's just a number) """ if integral: beta -= 1 return A*m**-beta * np.exp(-m/m0) def modified_schechter(m, m1, **kwargs): """ A Schechter function with a low-level exponential cutoff " Parameters ---------- m : np.ndarray List of masses for which to compute the Schechter function m1 : float Characteristic minimum mass (exponential decay below this mass) ** See schecter for other parameters ** Returns ------- p(m) - the (unnormalized) probability of an object of a given mass as a function of that object's mass (though you could interpret mass as anything, it's just a number) """ return schechter(m, **kwargs) * np.exp(-m1/m) try: import scipy def schechter_cdf(m,A=1,beta=2,m0=100,mmin=10,mmax=None,npts=1e4): """ Return the CDF value of a given mass for a set mmin,mmax mmax will default to 10 m0 if not specified Analytic integral of the Schechter function: http://www.wolframalpha.com/input/?i=integral%28x^-a+exp%28-x%2Fm%29+dx%29 """ if mmax is None: mmax = 10*m0 # integrate the CDF from the minimum to maximum # undefined posint = -m0 * mmax**-beta * (mmax/m0)**beta * scipy.special.gammainc(1-beta, mmax/m0) # undefined negint = -m0 * mmin**-beta * (mmin/m0)**beta * scipy.special.gammainc(1-beta, mmin/m0) posint = -mmax**(1-beta) * scipy.special.expn(beta, mmax/m0) negint = -mmin**(1-beta) * scipy.special.expn(beta, mmin/m0) tot = posint-negint # normalize by the integral # undefined ret = (-m0 * m**-beta * (m/m0)**beta * scipy.special.gammainc(1-beta, m/m0)) / tot ret = (-m**(1-beta) * scipy.special.expn(beta, m/m0) - negint)/ tot return ret def sh_cdf_func(**kwargs): return lambda x: schechter_cdf(x, **kwargs) except ImportError: pass #def schechter_inv(m): # """ # Return p(m) # """ # return scipy.interpolate.interp1d(shfun,arange(.1,20,.01),bounds_error=False,fill_value=20.) def integrate(fn=kroupa, bins=np.logspace(-2,2,500)): xax = (bins[:-1]+bins[1:])/2. integral = (bins[1:]-bins[:-1]) * (fn(bins[:-1])+fn(bins[1:])) / 2. return xax,integral def m_integrate(fn=kroupa, bins=np.logspace(-2,2,500)): xax = (bins[:-1]+bins[1:])/2. integral = xax*(bins[1:]-bins[:-1]) * (fn(bins[:-1])+fn(bins[1:])) / 2. return xax,integral def cumint(fn=kroupa, bins=np.logspace(-2,2,500)): xax,integral = integrate(fn,bins) return integral.cumsum() / integral.sum() def m_cumint(fn=kroupa, bins=np.logspace(-2,2,500)): xax,integral = m_integrate(fn,bins) return integral.cumsum() / integral.sum() massfunctions = {'kroupa':kroupa, 'salpeter':salpeter, 'chabrier':chabrier, 'schechter':schechter,'modified_schechter':modified_schechter} if hasattr(massfunctions, '__iteritems__'): reverse_mf_dict = {v:k for k,v in massfunctions.iteritems()} else: reverse_mf_dict = {v:k for k,v in massfunctions.items()} # salpeter and schechter selections are arbitrary mostcommonmass = {'kroupa':0.08, 'salpeter':0.01, 'chabrier':0.23, 'schecter':0.01,'modified_schechter':0.01} def get_massfunc(massfunc): if type(massfunc) is types.FunctionType or hasattr(massfunc,'__call__'): return massfunc elif type(massfunc) is str: return massfunctions[massfunc] else: raise ValueError("massfunc must either be a string in the set %s or a function" % (",".join(massfunctions.keys()))) def get_massfunc_name(massfunc): if massfunc in reverse_mf_dict: return reverse_mf_dict[massfunc] elif type(massfunc) is str: return massfunc elif hasattr(massfunc,'__name__'): return massfunc.__name__ else: raise ValueError("invalid mass function") def inverse_imf(p, nbins=1000, mmin=0.03, mmax=120, massfunc='kroupa', **kwargs): """ Inverse mass function massfunc can be 'kroupa', 'chabrier', 'salpeter', 'schechter', or a function """ masses = np.logspace(np.log10(mmin),np.log10(mmax),nbins) mf = get_massfunc(massfunc)(masses, integral_form=True, **kwargs) mfcum = mf.cumsum() mfcum /= mfcum.max() # normalize to sum (cdf) return np.interp(p, mfcum, masses)
en
0.664747
Various codes to work with the initial mass function. Stolen shamelessly from <NAME>'s agpy code: https://code.google.com/p/agpy/source/browse/trunk/agpy/imf.py # I use typechecking. Is there a better way to do this? (see inverse_imf below) Generic Mass Function class The differential form of the mass function, d N(M) / dM The integral form of the mass function, N(M) Integrate the mass function over some range Create a default Salpeter mass function, i.e. a power-law mass function the Salpeter 1955 IMF: dn/dm ~ m^-2.35 # three codes for dn/dlog(m) #kroupa = BrokenPowerLaw(breaks={0.08:-0.3, 0.5:1.3, 'last':2.3},mmin=0.03,mmax=120) Kroupa 2001 IMF (http://arxiv.org/abs/astro-ph/0009005, http://adsabs.harvard.edu/abs/2001MNRAS.322..231K) Chabrier 2003 IMF http://adsabs.harvard.edu/abs/2003PASP..115..763C (only valid for m < 1 msun) not sure which of these to use... integral is NOT IMPLEMENTED # This system MF can be parameterized by the same type of lognormal form as # the single MF (eq. [17]), with the same normalization at 1 Msun, with the # coefficients (Chabrier 2003) # This analytic form for the disk MF for single objects below 1 Msun, within these uncertainties, is given by the following lognormal form (Chabrier 2003): A Schechter function with arbitrary defaults (integral may not be correct - exponent hasn't been dealt with at all) $$ A m^{-\\beta} e^{-m/m_0} $$ Parameters ---------- m : np.ndarray List of masses for which to compute the Schechter function A : float Arbitrary amplitude of the Schechter function beta : float Power law exponent m0 : float Characteristic mass (mass at which exponential decay takes over) Returns ------- p(m) - the (unnormalized) probability of an object of a given mass as a function of that object's mass (though you could interpret mass as anything, it's just a number) A Schechter function with a low-level exponential cutoff " Parameters ---------- m : np.ndarray List of masses for which to compute the Schechter function m1 : float Characteristic minimum mass (exponential decay below this mass) ** See schecter for other parameters ** Returns ------- p(m) - the (unnormalized) probability of an object of a given mass as a function of that object's mass (though you could interpret mass as anything, it's just a number) Return the CDF value of a given mass for a set mmin,mmax mmax will default to 10 m0 if not specified Analytic integral of the Schechter function: http://www.wolframalpha.com/input/?i=integral%28x^-a+exp%28-x%2Fm%29+dx%29 # integrate the CDF from the minimum to maximum # undefined posint = -m0 * mmax**-beta * (mmax/m0)**beta * scipy.special.gammainc(1-beta, mmax/m0) # undefined negint = -m0 * mmin**-beta * (mmin/m0)**beta * scipy.special.gammainc(1-beta, mmin/m0) # normalize by the integral # undefined ret = (-m0 * m**-beta * (m/m0)**beta * scipy.special.gammainc(1-beta, m/m0)) / tot #def schechter_inv(m): # """ # Return p(m) # """ # return scipy.interpolate.interp1d(shfun,arange(.1,20,.01),bounds_error=False,fill_value=20.) # salpeter and schechter selections are arbitrary Inverse mass function massfunc can be 'kroupa', 'chabrier', 'salpeter', 'schechter', or a function # normalize to sum (cdf)
2.699579
3
AverageSpeed.py
ddawx123/Smart-Traffic
8
6613729
import os import sys import http.client import json import codecs import time import datetime import sqlite3 import subprocess import platform def getData(): conn = http.client.HTTPConnection("172.16.17.32") conn.request("GET", "/wx/data.php?t=dlzs") jsonstr = conn.getresponse() return jsonstr def Main(): print("绍兴市智慧交通数据分析工具_v1.0内测版\n\n") if (getData().status != 200): print("远程服务器连接失败,请检查网络状态。") exit() #print(getData().read()) data = json.loads(getData().read()) print("检索到共有" + str(len(data)) + "条路况数据,正在计算。\n") reqtime = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time())) fullspeed = 0 for newdata in data: #print(newdata["speed"]) fullspeed = fullspeed + newdata["speed"] print("数据分析结束,主城区平均通行速度:" + str(int(fullspeed / len(data))) + " Km/h") print("\n\n\nCopyright 2012-2017 DingStudio All Rights Reserved") def LoopExecute(): while(1): time.sleep(1) if (platform.system() == "Windows"): os.system('color 0a') os.system('cls') else: os.system('clear') Main() LoopExecute()
import os import sys import http.client import json import codecs import time import datetime import sqlite3 import subprocess import platform def getData(): conn = http.client.HTTPConnection("172.16.17.32") conn.request("GET", "/wx/data.php?t=dlzs") jsonstr = conn.getresponse() return jsonstr def Main(): print("绍兴市智慧交通数据分析工具_v1.0内测版\n\n") if (getData().status != 200): print("远程服务器连接失败,请检查网络状态。") exit() #print(getData().read()) data = json.loads(getData().read()) print("检索到共有" + str(len(data)) + "条路况数据,正在计算。\n") reqtime = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time())) fullspeed = 0 for newdata in data: #print(newdata["speed"]) fullspeed = fullspeed + newdata["speed"] print("数据分析结束,主城区平均通行速度:" + str(int(fullspeed / len(data))) + " Km/h") print("\n\n\nCopyright 2012-2017 DingStudio All Rights Reserved") def LoopExecute(): while(1): time.sleep(1) if (platform.system() == "Windows"): os.system('color 0a') os.system('cls') else: os.system('clear') Main() LoopExecute()
ru
0.208283
#print(getData().read()) #print(newdata["speed"])
2.466831
2
15-17. Menu/window-17-pushdownMenu.py
IvanFoke/TkinterLessons
3
6613730
<filename>15-17. Menu/window-17-pushdownMenu.py from tkinter import * from tkinter import messagebox as mb from tkinter.ttk import Combobox from child_window import ChildWindow # from PIL import Image as PilImage # from PIL import ImageTk, ImageOps class Window: def __init__(self, width, height, title="MyWindow", resizable=(False, False), icon=r"resources/feather.ico"): self.root = Tk() self.root.title(title) # self.root.geometry(f"{width}x{height}+200+200") self.root.geometry("+600+300") # self.root.resizable(resizable[0], resizable[1]) if icon: self.root.iconbitmap(icon) self.auto_save = BooleanVar(value=0) self.auto_load = BooleanVar(value=0) self.value = IntVar() def run(self): self.draw_widgets() self.root.mainloop() def draw_widgets(self): self.draw_menu() Label(self.root, text="Just a label").pack() def draw_menu(self): menu_bar = Menu(self.root) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="Сохранить", command=self.cmd) file_menu.add_separator() file_menu.add_command(label="Выйти", command=self.exit) edit_menu = Menu(menu_bar, tearoff=0) parameters_menu = Menu(edit_menu, tearoff=0) parameters_menu.add_checkbutton(label="Автосохранение", offvalue=0, onvalue=1, variable=self.auto_save) parameters_menu.add_checkbutton(label="Автозагрузка", offvalue=0, onvalue=1, variable=self.auto_load, command=self.check_auto_load) edit_menu.add_cascade(label="Параметры", menu=parameters_menu) edit_menu.add_separator() values_menu = Menu(edit_menu, tearoff=0) values_menu.add_radiobutton(label="Один", value=1, variable=self.value) values_menu.add_radiobutton(label="Два", value=2, variable=self.value) values_menu.add_radiobutton(label="Три", value=3, variable=self.value) edit_menu.add_cascade(label="Значения", menu=values_menu) info_menu = Menu(menu_bar, tearoff=0) info_menu.add_command(label="О приложении", command=self.show_info) menu_bar.add_cascade(label="Файл", menu=file_menu) menu_bar.add_cascade(label="Настройки", menu=edit_menu) menu_bar.add_cascade(label="Справка", menu=info_menu) self.root.configure(menu=menu_bar) def check_auto_load(self): if not self.auto_save.get() and self.auto_load.get(): if mb.askyesno("Ошибка", "Автозагрузка без автосохранения. Хотите установить автосохранение?"): self.auto_save.set(True) def show_info(self): mb.showinfo("Информация", "Лучшее графическое приложение на свете") def auto_save_changed(self): mb.showinfo("AutoSave", f"Value: {self.auto_save.get()}") def age_changed(self): mb.showinfo("Age", f"Value: {self.age.get()}") def cmd(self): mb.showinfo("123", "123") def exit(self): choice = mb.askyesno("Quit", "Do you want to quit?") if choice: self.root.destroy() def create_child(self, width, height, title="Child", resizable=(False, False), icon=None): ChildWindow(self.root, width, height, title, resizable, icon) if __name__ == "__main__": window = Window(500, 500, "TKINTER") # window.create_child(200, 100) window.run()
<filename>15-17. Menu/window-17-pushdownMenu.py from tkinter import * from tkinter import messagebox as mb from tkinter.ttk import Combobox from child_window import ChildWindow # from PIL import Image as PilImage # from PIL import ImageTk, ImageOps class Window: def __init__(self, width, height, title="MyWindow", resizable=(False, False), icon=r"resources/feather.ico"): self.root = Tk() self.root.title(title) # self.root.geometry(f"{width}x{height}+200+200") self.root.geometry("+600+300") # self.root.resizable(resizable[0], resizable[1]) if icon: self.root.iconbitmap(icon) self.auto_save = BooleanVar(value=0) self.auto_load = BooleanVar(value=0) self.value = IntVar() def run(self): self.draw_widgets() self.root.mainloop() def draw_widgets(self): self.draw_menu() Label(self.root, text="Just a label").pack() def draw_menu(self): menu_bar = Menu(self.root) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label="Сохранить", command=self.cmd) file_menu.add_separator() file_menu.add_command(label="Выйти", command=self.exit) edit_menu = Menu(menu_bar, tearoff=0) parameters_menu = Menu(edit_menu, tearoff=0) parameters_menu.add_checkbutton(label="Автосохранение", offvalue=0, onvalue=1, variable=self.auto_save) parameters_menu.add_checkbutton(label="Автозагрузка", offvalue=0, onvalue=1, variable=self.auto_load, command=self.check_auto_load) edit_menu.add_cascade(label="Параметры", menu=parameters_menu) edit_menu.add_separator() values_menu = Menu(edit_menu, tearoff=0) values_menu.add_radiobutton(label="Один", value=1, variable=self.value) values_menu.add_radiobutton(label="Два", value=2, variable=self.value) values_menu.add_radiobutton(label="Три", value=3, variable=self.value) edit_menu.add_cascade(label="Значения", menu=values_menu) info_menu = Menu(menu_bar, tearoff=0) info_menu.add_command(label="О приложении", command=self.show_info) menu_bar.add_cascade(label="Файл", menu=file_menu) menu_bar.add_cascade(label="Настройки", menu=edit_menu) menu_bar.add_cascade(label="Справка", menu=info_menu) self.root.configure(menu=menu_bar) def check_auto_load(self): if not self.auto_save.get() and self.auto_load.get(): if mb.askyesno("Ошибка", "Автозагрузка без автосохранения. Хотите установить автосохранение?"): self.auto_save.set(True) def show_info(self): mb.showinfo("Информация", "Лучшее графическое приложение на свете") def auto_save_changed(self): mb.showinfo("AutoSave", f"Value: {self.auto_save.get()}") def age_changed(self): mb.showinfo("Age", f"Value: {self.age.get()}") def cmd(self): mb.showinfo("123", "123") def exit(self): choice = mb.askyesno("Quit", "Do you want to quit?") if choice: self.root.destroy() def create_child(self, width, height, title="Child", resizable=(False, False), icon=None): ChildWindow(self.root, width, height, title, resizable, icon) if __name__ == "__main__": window = Window(500, 500, "TKINTER") # window.create_child(200, 100) window.run()
en
0.216211
# from PIL import Image as PilImage # from PIL import ImageTk, ImageOps # self.root.geometry(f"{width}x{height}+200+200") # self.root.resizable(resizable[0], resizable[1]) # window.create_child(200, 100)
2.955921
3
test/test_analysis/test_plotting.py
sid-marain/EMAworkbench
0
6613731
<gh_stars>0 ''' Created on 22 jul. 2012 .. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl> ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import matplotlib.pyplot as plt import numpy as np from ema_workbench.analysis.b_and_w_plotting import set_fig_to_bw from ema_workbench.analysis.plotting import * from ema_workbench.analysis.plotting_util import (make_continuous_grouping_specifiers, filter_scalar_outcomes, group_results, BOXPLOT, KDE, VIOLIN, HIST, ENV_LIN) from test import utilities # don't run these tests using nosetest # __test__ = False def test_make_continuous_grouping_specifiers(): array = np.random.randint(1,100, size=(1000,)) categories = make_continuous_grouping_specifiers(array, nr_of_groups=10) for entry in categories: print(repr(entry)) print(np.min(array), np.max(array)) def test_filter_scalar_outcomes(): outcomes = {} for entry in ['a', 'b', 'c']: outcomes[entry] = np.random.rand(10,100) for entry in ['d','e','f']: outcomes[entry] = np.random.rand(10) outcomes = filter_scalar_outcomes(outcomes) print(outcomes.keys()) def test_group_results(): results = utilities.load_eng_trans_data() experiments, outcomes = results # test indices groups = {'set1':np.arange(0,11), 'set2':np.arange(11,25), 'set3':np.arange(25,experiments.shape[0])} groups = group_results(experiments, outcomes, group_by='index', grouping_specifiers=groups.values(), grouping_labels= groups.keys()) total_data = 0 for value in groups.values(): total_data += value[0].shape[0] print(experiments.shape[0], total_data) # test continuous parameter type array = experiments['average planning and construction period T1'] grouping_specifiers = make_continuous_grouping_specifiers(array, nr_of_groups=5) groups = group_results(experiments, outcomes, group_by='average planning and construction period T1', grouping_specifiers=grouping_specifiers, grouping_labels = [str(entry) for entry in grouping_specifiers]) total_data = 0 for value in groups.values(): total_data += value[0].shape[0] print(experiments.shape[0], total_data) # test integer type array = experiments['seed PR T1'] grouping_specifiers = make_continuous_grouping_specifiers(array, nr_of_groups=10) groups = group_results(experiments, outcomes, group_by='seed PR T1', grouping_specifiers=grouping_specifiers, grouping_labels = [str(entry) for entry in grouping_specifiers]) total_data = 0 for value in groups.values(): total_data += value[0].shape[0] print(experiments.shape[0], total_data) # test categorical type grouping_specifiers = set(experiments["policy"]) groups = group_results(experiments, outcomes, group_by='policy', grouping_specifiers=grouping_specifiers, grouping_labels = [str(entry) for entry in grouping_specifiers]) total_data = 0 for value in groups.values(): total_data += value[0].shape[0] print(experiments.shape[0], total_data) def test_lines(): experiments, outcomes = utilities.load_eng_trans_data() lines(experiments, outcomes, outcomes_to_show="total fraction new technologies", experiments_to_show=np.arange(0,600, 20), group_by='policy', grouping_specifiers='basic policy' ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 2), group_by='policy', density=HIST ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 2), group_by='policy', density=KDE ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 2), group_by='policy', density=BOXPLOT ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 2), group_by='policy', density=VIOLIN ) lines(experiments, outcomes, group_by='index', grouping_specifiers = {"blaat": np.arange(1, 100, 2)}, density=KDE, ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=KDE, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'] ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=HIST, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'] ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=BOXPLOT, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'] ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=VIOLIN, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'] ) plt.draw() plt.close('all') lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=KDE, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'], log=True ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=HIST, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'], log=True ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=BOXPLOT, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'], log=True ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=VIOLIN, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'], log=True ) plt.draw() plt.close('all') set_fig_to_bw(lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 20), group_by='policy', density=KDE )[0]) new_outcomes = {} for key, value in outcomes.items(): new_outcomes[key] = value[0:20, :] experiments = experiments[0:20] #no grouping, with density set_fig_to_bw(lines(experiments, new_outcomes, density=KDE)[0]) set_fig_to_bw(lines(experiments, new_outcomes, density=HIST)[0]) set_fig_to_bw(lines(experiments, new_outcomes, density=BOXPLOT)[0]) set_fig_to_bw(lines(experiments, new_outcomes, density=VIOLIN)[0]) # grouping and density set_fig_to_bw(lines(experiments, new_outcomes, group_by='policy', density='kde')[0]) # grouping, density as histograms # grouping and density set_fig_to_bw(lines(experiments, new_outcomes, group_by='policy', density='hist', legend=False)[0]) plt.draw() plt.close('all') def test_envelopes(): experiments, outcomes = utilities.load_eng_trans_data() #testing titles envelopes(experiments, outcomes, density=None, titles=None) envelopes(experiments, outcomes, density=None, titles={}) envelopes(experiments, outcomes, density=None, titles={'total fraction new technologies': 'a'}) plt.draw() plt.close('all') #testing ylabels envelopes(experiments, outcomes, density=None, ylabels=None) envelopes(experiments, outcomes, density=None, ylabels={}) envelopes(experiments, outcomes, density=None, ylabels={'total fraction new technologies': 'a'}) plt.draw() plt.close('all') #no grouping no density envelopes(experiments, outcomes, titles=None) set_fig_to_bw(envelopes(experiments, outcomes, density=None)[0]) plt.draw() plt.close('all') #no grouping, with density envelopes(experiments, outcomes, density=KDE) envelopes(experiments, outcomes, density=HIST) envelopes(experiments, outcomes, density=BOXPLOT) envelopes(experiments, outcomes, density=VIOLIN) set_fig_to_bw(envelopes(experiments, outcomes, density=VIOLIN)[0]) plt.draw() plt.close('all') # grouping and density kde envelopes(experiments, outcomes, group_by='policy', density=VIOLIN) envelopes(experiments, outcomes, group_by='policy', density=BOXPLOT) envelopes(experiments, outcomes, group_by='policy', density=KDE, grouping_specifiers=['no policy', 'adaptive policy']) envelopes(experiments, outcomes, group_by='policy', density=BOXPLOT, grouping_specifiers=['no policy', 'adaptive policy']) envelopes(experiments, outcomes, group_by='policy', density=KDE) plt.draw() plt.close('all') envelopes(experiments, outcomes, group_by='policy', density=VIOLIN) envelopes(experiments, outcomes, group_by='policy', density=BOXPLOT) envelopes(experiments, outcomes, group_by='policy', density=KDE) envelopes(experiments, outcomes, group_by='policy', density=HIST) plt.draw() plt.close('all') envelopes(experiments, outcomes, group_by='policy', density=VIOLIN, log=True) envelopes(experiments, outcomes, group_by='policy', density=BOXPLOT, log=True) envelopes(experiments, outcomes, group_by='policy', density=KDE, log=True) envelopes(experiments, outcomes, group_by='policy', density=HIST, log=True) plt.draw() plt.close('all') # grouping and density hist envelopes(experiments, outcomes, group_by='policy', density=HIST) envelopes(experiments, outcomes, group_by='policy', density=HIST) set_fig_to_bw(envelopes(experiments, outcomes, group_by='policy', density=KDE)[0]) # grouping and density envelopes(experiments, outcomes, group_by='policy', density=KDE, fill=True) set_fig_to_bw(envelopes(experiments, outcomes, group_by='policy', density=KDE, fill=True)[0]) plt.draw() plt.close('all') def test_kde_over_time(): experiments, outcomes = utilities.load_eng_trans_data() kde_over_time(experiments, outcomes, log=False) kde_over_time(experiments, outcomes, log=True) kde_over_time(experiments, outcomes, group_by='policy', grouping_specifiers=['no policy', 'adaptive policy']) plt.draw() plt.close('all') def test_multiple_densities(): experiments, outcomes = utilities.load_eng_trans_data() ooi = 'total fraction new technologies' multiple_densities(experiments, outcomes, group_by="policy", points_in_time = [2010]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010, 2100]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010, 2050, 2100]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010, 2020, 2050, 2080]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010, 2020, 2040, 2060, 2100]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=KDE, experiments_to_show=[1,2,10]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=HIST, experiments_to_show=[1,2,10]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=BOXPLOT, experiments_to_show=[1,2,10]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=VIOLIN, experiments_to_show=[1,2,10]) plt.draw() plt.close('all') multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=KDE, experiments_to_show=[1,2,10], log=True) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=HIST, experiments_to_show=[1,2,10], log=True) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=BOXPLOT, experiments_to_show=[1,2,10], log=True) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=VIOLIN, experiments_to_show=[1,2,10], log=True) plt.draw() plt.close('all') if __name__ == '__main__': # test_lines() # test_envelopes() test_kde_over_time() # test_multiple_densities() # test_filter_scalar_outcomes() # test_group_results() # test_make_continuous_grouping_specifiers()
''' Created on 22 jul. 2012 .. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl> ''' from __future__ import (absolute_import, print_function, division, unicode_literals) import matplotlib.pyplot as plt import numpy as np from ema_workbench.analysis.b_and_w_plotting import set_fig_to_bw from ema_workbench.analysis.plotting import * from ema_workbench.analysis.plotting_util import (make_continuous_grouping_specifiers, filter_scalar_outcomes, group_results, BOXPLOT, KDE, VIOLIN, HIST, ENV_LIN) from test import utilities # don't run these tests using nosetest # __test__ = False def test_make_continuous_grouping_specifiers(): array = np.random.randint(1,100, size=(1000,)) categories = make_continuous_grouping_specifiers(array, nr_of_groups=10) for entry in categories: print(repr(entry)) print(np.min(array), np.max(array)) def test_filter_scalar_outcomes(): outcomes = {} for entry in ['a', 'b', 'c']: outcomes[entry] = np.random.rand(10,100) for entry in ['d','e','f']: outcomes[entry] = np.random.rand(10) outcomes = filter_scalar_outcomes(outcomes) print(outcomes.keys()) def test_group_results(): results = utilities.load_eng_trans_data() experiments, outcomes = results # test indices groups = {'set1':np.arange(0,11), 'set2':np.arange(11,25), 'set3':np.arange(25,experiments.shape[0])} groups = group_results(experiments, outcomes, group_by='index', grouping_specifiers=groups.values(), grouping_labels= groups.keys()) total_data = 0 for value in groups.values(): total_data += value[0].shape[0] print(experiments.shape[0], total_data) # test continuous parameter type array = experiments['average planning and construction period T1'] grouping_specifiers = make_continuous_grouping_specifiers(array, nr_of_groups=5) groups = group_results(experiments, outcomes, group_by='average planning and construction period T1', grouping_specifiers=grouping_specifiers, grouping_labels = [str(entry) for entry in grouping_specifiers]) total_data = 0 for value in groups.values(): total_data += value[0].shape[0] print(experiments.shape[0], total_data) # test integer type array = experiments['seed PR T1'] grouping_specifiers = make_continuous_grouping_specifiers(array, nr_of_groups=10) groups = group_results(experiments, outcomes, group_by='seed PR T1', grouping_specifiers=grouping_specifiers, grouping_labels = [str(entry) for entry in grouping_specifiers]) total_data = 0 for value in groups.values(): total_data += value[0].shape[0] print(experiments.shape[0], total_data) # test categorical type grouping_specifiers = set(experiments["policy"]) groups = group_results(experiments, outcomes, group_by='policy', grouping_specifiers=grouping_specifiers, grouping_labels = [str(entry) for entry in grouping_specifiers]) total_data = 0 for value in groups.values(): total_data += value[0].shape[0] print(experiments.shape[0], total_data) def test_lines(): experiments, outcomes = utilities.load_eng_trans_data() lines(experiments, outcomes, outcomes_to_show="total fraction new technologies", experiments_to_show=np.arange(0,600, 20), group_by='policy', grouping_specifiers='basic policy' ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 2), group_by='policy', density=HIST ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 2), group_by='policy', density=KDE ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 2), group_by='policy', density=BOXPLOT ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 2), group_by='policy', density=VIOLIN ) lines(experiments, outcomes, group_by='index', grouping_specifiers = {"blaat": np.arange(1, 100, 2)}, density=KDE, ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=KDE, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'] ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=HIST, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'] ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=BOXPLOT, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'] ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=VIOLIN, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'] ) plt.draw() plt.close('all') lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=KDE, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'], log=True ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=HIST, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'], log=True ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=BOXPLOT, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'], log=True ) lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 30), group_by='policy', density=VIOLIN, show_envelope=True, grouping_specifiers=['no policy', 'adaptive policy'], log=True ) plt.draw() plt.close('all') set_fig_to_bw(lines(experiments, outcomes, experiments_to_show=np.arange(0,600, 20), group_by='policy', density=KDE )[0]) new_outcomes = {} for key, value in outcomes.items(): new_outcomes[key] = value[0:20, :] experiments = experiments[0:20] #no grouping, with density set_fig_to_bw(lines(experiments, new_outcomes, density=KDE)[0]) set_fig_to_bw(lines(experiments, new_outcomes, density=HIST)[0]) set_fig_to_bw(lines(experiments, new_outcomes, density=BOXPLOT)[0]) set_fig_to_bw(lines(experiments, new_outcomes, density=VIOLIN)[0]) # grouping and density set_fig_to_bw(lines(experiments, new_outcomes, group_by='policy', density='kde')[0]) # grouping, density as histograms # grouping and density set_fig_to_bw(lines(experiments, new_outcomes, group_by='policy', density='hist', legend=False)[0]) plt.draw() plt.close('all') def test_envelopes(): experiments, outcomes = utilities.load_eng_trans_data() #testing titles envelopes(experiments, outcomes, density=None, titles=None) envelopes(experiments, outcomes, density=None, titles={}) envelopes(experiments, outcomes, density=None, titles={'total fraction new technologies': 'a'}) plt.draw() plt.close('all') #testing ylabels envelopes(experiments, outcomes, density=None, ylabels=None) envelopes(experiments, outcomes, density=None, ylabels={}) envelopes(experiments, outcomes, density=None, ylabels={'total fraction new technologies': 'a'}) plt.draw() plt.close('all') #no grouping no density envelopes(experiments, outcomes, titles=None) set_fig_to_bw(envelopes(experiments, outcomes, density=None)[0]) plt.draw() plt.close('all') #no grouping, with density envelopes(experiments, outcomes, density=KDE) envelopes(experiments, outcomes, density=HIST) envelopes(experiments, outcomes, density=BOXPLOT) envelopes(experiments, outcomes, density=VIOLIN) set_fig_to_bw(envelopes(experiments, outcomes, density=VIOLIN)[0]) plt.draw() plt.close('all') # grouping and density kde envelopes(experiments, outcomes, group_by='policy', density=VIOLIN) envelopes(experiments, outcomes, group_by='policy', density=BOXPLOT) envelopes(experiments, outcomes, group_by='policy', density=KDE, grouping_specifiers=['no policy', 'adaptive policy']) envelopes(experiments, outcomes, group_by='policy', density=BOXPLOT, grouping_specifiers=['no policy', 'adaptive policy']) envelopes(experiments, outcomes, group_by='policy', density=KDE) plt.draw() plt.close('all') envelopes(experiments, outcomes, group_by='policy', density=VIOLIN) envelopes(experiments, outcomes, group_by='policy', density=BOXPLOT) envelopes(experiments, outcomes, group_by='policy', density=KDE) envelopes(experiments, outcomes, group_by='policy', density=HIST) plt.draw() plt.close('all') envelopes(experiments, outcomes, group_by='policy', density=VIOLIN, log=True) envelopes(experiments, outcomes, group_by='policy', density=BOXPLOT, log=True) envelopes(experiments, outcomes, group_by='policy', density=KDE, log=True) envelopes(experiments, outcomes, group_by='policy', density=HIST, log=True) plt.draw() plt.close('all') # grouping and density hist envelopes(experiments, outcomes, group_by='policy', density=HIST) envelopes(experiments, outcomes, group_by='policy', density=HIST) set_fig_to_bw(envelopes(experiments, outcomes, group_by='policy', density=KDE)[0]) # grouping and density envelopes(experiments, outcomes, group_by='policy', density=KDE, fill=True) set_fig_to_bw(envelopes(experiments, outcomes, group_by='policy', density=KDE, fill=True)[0]) plt.draw() plt.close('all') def test_kde_over_time(): experiments, outcomes = utilities.load_eng_trans_data() kde_over_time(experiments, outcomes, log=False) kde_over_time(experiments, outcomes, log=True) kde_over_time(experiments, outcomes, group_by='policy', grouping_specifiers=['no policy', 'adaptive policy']) plt.draw() plt.close('all') def test_multiple_densities(): experiments, outcomes = utilities.load_eng_trans_data() ooi = 'total fraction new technologies' multiple_densities(experiments, outcomes, group_by="policy", points_in_time = [2010]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010, 2100]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010, 2050, 2100]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010, 2020, 2050, 2080]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010, 2020, 2040, 2060, 2100]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=KDE, experiments_to_show=[1,2,10]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=HIST, experiments_to_show=[1,2,10]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=BOXPLOT, experiments_to_show=[1,2,10]) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=VIOLIN, experiments_to_show=[1,2,10]) plt.draw() plt.close('all') multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=KDE, experiments_to_show=[1,2,10], log=True) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=HIST, experiments_to_show=[1,2,10], log=True) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=BOXPLOT, experiments_to_show=[1,2,10], log=True) multiple_densities(experiments, outcomes, outcomes_to_show=ooi, group_by="policy", points_in_time = [2010,2020, 2040, 2060, 2080, 2100], plot_type=ENV_LIN, density=VIOLIN, experiments_to_show=[1,2,10], log=True) plt.draw() plt.close('all') if __name__ == '__main__': # test_lines() # test_envelopes() test_kde_over_time() # test_multiple_densities() # test_filter_scalar_outcomes() # test_group_results() # test_make_continuous_grouping_specifiers()
en
0.40855
Created on 22 jul. 2012 .. codeauthor:: jhkwakkel <j.h.kwakkel (at) tudelft (dot) nl> # don't run these tests using nosetest # __test__ = False # test indices # test continuous parameter type # test integer type # test categorical type #no grouping, with density # grouping and density # grouping, density as histograms # grouping and density #testing titles #testing ylabels #no grouping no density #no grouping, with density # grouping and density kde # grouping and density hist # grouping and density # test_lines() # test_envelopes() # test_multiple_densities() # test_filter_scalar_outcomes() # test_group_results() # test_make_continuous_grouping_specifiers()
2.263146
2
convert_pptx.py
yuhal/ppt-convert
4
6613732
# -*- coding: utf-8 -*- # !python3 """ PPT convert PPTX """ from changeOffice import Change change = Change("./") change.ppt2pptx() print(change.get_allPath())
# -*- coding: utf-8 -*- # !python3 """ PPT convert PPTX """ from changeOffice import Change change = Change("./") change.ppt2pptx() print(change.get_allPath())
en
0.457089
# -*- coding: utf-8 -*- # !python3 PPT convert PPTX
2.66839
3
setup.py
mypleasureteam/mann
0
6613733
"""Setup for Mann on PyPi.""" from distutils.core import setup setup( name='mann', packages=['mypleasure'], version='0.9.1', description='A multi-purpose logger and notifier.', author='<NAME>', author_email='<EMAIL>', url='https://github.com/mypleasureteam/mann', download_url='https://github.com/mypleasureteam/mann/tarball/0.1', keywords=['logging', 'notification', 'trello', 'slack'], classifiers=[], )
"""Setup for Mann on PyPi.""" from distutils.core import setup setup( name='mann', packages=['mypleasure'], version='0.9.1', description='A multi-purpose logger and notifier.', author='<NAME>', author_email='<EMAIL>', url='https://github.com/mypleasureteam/mann', download_url='https://github.com/mypleasureteam/mann/tarball/0.1', keywords=['logging', 'notification', 'trello', 'slack'], classifiers=[], )
en
0.499595
Setup for Mann on PyPi.
1.343032
1
magmap/gui/vis_3d.py
kaparna126/magellanmapper
10
6613734
# 3D visualization in MagellanMapper import math from time import time import numpy as np from skimage import filters, restoration, transform from magmap.cv import segmenter from magmap.io import libmag from magmap.plot import colormaps, plot_3d from magmap.settings import config class Vis3D: """3D visualization object for handling Mayavi/VTK tasks. Attributes: scene (:class:`mayavi.tools.mlab_scene_model.MlabSceneModel`): Mayavi scene. fn_update_coords (func): Callback to update coordinates; defaults to None. surfaces (list): List of Mayavi surfaces for each displayed channel; defaults to None. blobs (list[:class:`mayavi.modules.glyph.Glyph`]): List of Mayavi glyphs, where each glyph typically contains many 3D points representing blob positions; defaults to None. """ #: float: Maximum number of points to show. _MASK_DIVIDEND = 10000.0 # 3D max points def __init__(self, scene): """Initialize a 3D visualization object. Args: scene (:class:`mayavi.tools.mlab_scene_model.MlabSceneModel`): Mayavi scene. """ self.scene = scene # callbacks self.fn_update_coords = None # generated Mayavi objects self.surfaces = None self.blobs = None def update_img_display(self, minimum=None, maximum=None, brightness=None, contrast=None, alpha=None): """Update the displayed image settings. Args: minimum (float): Minimum intensity. maximum (float): Maximum intensity. brightness (float): Brightness gamma. contrast (float): Contrast factor. alpha (float): Opacity, from 0-1, where 1 is fully opaque. Returns: """ if self.surfaces: for surface in self.surfaces: if alpha is not None: surface.actor.property.opacity = alpha def plot_3d_points(self, roi, channel, flipz=False, offset=None): """Plots all pixels as points in 3D space. Points falling below a given threshold will be removed, allowing the viewer to see through the presumed background to masses within the region of interest. Args: roi (:class:`numpy.ndarray`): Region of interest either as a 3D ``z,y,x`` or 4D ``z,y,x,c`` array. channel (int): Channel to select, which can be None to indicate all channels. flipz (bool): True to invert the ROI along the z-axis to match the handedness of Matplotlib with z progressing upward; defaults to False. offset (Sequence[int]): Origin coordinates in ``z,y,x``; defaults to None. Returns: bool: True if points were rendered, False if no points to render. """ print("Plotting ROI as 3D points") # streamline the image if roi is None or roi.size < 1: return False roi = plot_3d.saturate_roi(roi, clip_vmax=98.5, channel=channel) roi = np.clip(roi, 0.2, 0.8) roi = restoration.denoise_tv_chambolle(roi, weight=0.1) # separate parallel arrays for each dimension of all coordinates for # Mayavi input format, with the ROI itself given as a 1D scalar array ; # TODO: consider using np.mgrid to construct the x,y,z arrays time_start = time() shape = roi.shape isotropic = plot_3d.get_isotropic_vis(config.roi_profile) z = np.ones((shape[0], shape[1] * shape[2])) for i in range(shape[0]): z[i] = z[i] * i if flipz: # invert along z-axis to match handedness of Matplotlib with z up z *= -1 if offset is not None: offset = np.copy(offset) offset[0] *= -1 y = np.ones((shape[0] * shape[1], shape[2])) for i in range(shape[0]): for j in range(shape[1]): y[i * shape[1] + j] = y[i * shape[1] + j] * j x = np.ones((shape[0] * shape[1], shape[2])) for i in range(shape[0] * shape[1]): x[i] = np.arange(shape[2]) if offset is not None: offset = np.multiply(offset, isotropic) coords = [z, y, x] for i, _ in enumerate(coords): # scale coordinates for isotropy coords[i] *= isotropic[i] if offset is not None: # translate by offset coords[i] += offset[i] multichannel, channels = plot_3d.setup_channels(roi, channel, 3) for chl in channels: roi_show = roi[..., chl] if multichannel else roi roi_show_1d = roi_show.reshape(roi_show.size) if chl == 0: x = np.reshape(x, roi_show.size) y = np.reshape(y, roi_show.size) z = np.reshape(z, roi_show.size) settings = config.get_roi_profile(chl) # clear background points to see remaining structures thresh = 0 if len(np.unique(roi_show)) > 1: # need > 1 val to threshold try: thresh = filters.threshold_otsu(roi_show, 64) except ValueError as e: thresh = np.median(roi_show) print("could not determine Otsu threshold, taking median " "({}) instead".format(thresh)) thresh *= settings["points_3d_thresh"] print("removing 3D points below threshold of {}".format(thresh)) remove = np.where(roi_show_1d < thresh) roi_show_1d = np.delete(roi_show_1d, remove) # adjust range from 0-1 to region of colormap to use roi_show_1d = libmag.normalize(roi_show_1d, 0.6, 1.0) points_len = roi_show_1d.size if points_len == 0: print("no 3D points to display") return False mask = math.ceil(points_len / self._MASK_DIVIDEND) print("points: {}, mask: {}".format(points_len, mask)) if any(np.isnan(roi_show_1d)): # TODO: see if some NaNs are permissible print("NaN values for 3D points, will not show 3D visualization") return False pts = self.scene.mlab.points3d( np.delete(x, remove), np.delete(y, remove), np.delete(z, remove), roi_show_1d, mode="sphere", scale_mode="scalar", mask_points=mask, line_width=1.0, vmax=1.0, vmin=0.0, transparent=True) cmap = colormaps.get_cmap(config.cmaps, chl) if cmap is not None: pts.module_manager.scalar_lut_manager.lut.table = cmap( range(0, 256)) * 255 # scale glyphs to partially fill in gaps from isotropic scaling; # do not use actor scaling as it also translates the points when # not positioned at the origin pts.glyph.glyph.scale_factor = 2 * max(isotropic) # keep visual ordering of surfaces when opacity is reduced self.scene.renderer.use_depth_peeling = True print("time for 3D points display: {}".format(time() - time_start)) return True def plot_3d_surface(self, roi, channel, segment=False, flipz=False, offset=None): """Plots areas with greater intensity as 3D surfaces. The scene will be cleared before display. Args: roi (:class:`numpy.ndarray`): Region of interest either as a 3D ``z,y,x`` or 4D ``z,y,x,c`` array. channel (int): Channel to select, which can be None to indicate all channels. segment (bool): True to denoise and segment ``roi`` before displaying, which may remove artifacts that might otherwise lead to spurious surfaces. Defaults to False. flipz: True to invert ``roi`` along z-axis to match handedness of Matplotlib with z progressing upward; defaults to False. offset (Sequence[int]): Origin coordinates in ``z,y,x``; defaults to None. Returns: list: List of Mayavi surfaces for each displayed channel, which are also stored in :attr:`surfaces`. """ # Plot in Mayavi print("viewing 3D surface") pipeline = self.scene.mlab.pipeline settings = config.roi_profile if flipz: # invert along z-axis to match handedness of Matplotlib with z up roi = roi[::-1] if offset is not None: # invert z-offset and translate by ROI z-size so ROI is # mirrored across the xy-plane offset = np.copy(offset) offset[0] = -offset[0] - roi.shape[0] isotropic = plot_3d.get_isotropic_vis(settings) # saturate to remove noise and normalize values roi = plot_3d.saturate_roi(roi, channel=channel) # turn off segmentation if ROI too big (arbitrarily set here as # > 10 million pixels) to avoid performance hit and since likely showing # large region of downsampled image anyway, where don't need hi res num_pixels = np.prod(roi.shape) to_segment = num_pixels < 10000000 time_start = time() multichannel, channels = plot_3d.setup_channels(roi, channel, 3) surfaces = [] for chl in channels: roi_show = roi[..., chl] if multichannel else roi # clip to minimize sub-nuclear variation roi_show = np.clip(roi_show, 0.2, 0.8) if segment: # denoising makes for much cleaner images but also seems to # allow structures to blend together # TODO: consider segmenting individual structures and rendering # as separate surfaces to avoid blending roi_show = restoration.denoise_tv_chambolle( roi_show, weight=0.1) # build surface from segmented ROI if to_segment: vmin, vmax = np.percentile(roi_show, (40, 70)) walker = segmenter.segment_rw( roi_show, chl, vmin=vmin, vmax=vmax) roi_show *= np.subtract(walker[0], 1) else: print("deferring segmentation as {} px is above threshold" .format(num_pixels)) # ROI is in (z, y, x) order, so need to transpose or swap x,z axes roi_show = np.transpose(roi_show) surface = pipeline.scalar_field(roi_show) # Contour -> Surface pipeline # create the surface surface = pipeline.contour(surface) # remove many more extraneous points surface = pipeline.user_defined( surface, filter="SmoothPolyDataFilter") surface.filter.number_of_iterations = 400 surface.filter.relaxation_factor = 0.015 # distinguishing pos vs neg curvatures? surface = pipeline.user_defined(surface, filter="Curvatures") surface = self.scene.mlab.pipeline.surface(surface) module_manager = surface.module_manager module_manager.scalar_lut_manager.data_range = np.array([-2, 0]) module_manager.scalar_lut_manager.lut_mode = "gray" ''' # Surface pipleline with contours enabled (similar to above?) surface = pipeline.contour_surface( surface, color=(0.7, 1, 0.7), line_width=6.0) surface.actor.property.representation = 'wireframe' #surface.actor.property.line_width = 6.0 surface.actor.mapper.scalar_visibility = False ''' ''' # IsoSurface pipeline # uses unique IsoSurface module but appears to have # similar output to contour_surface surface = pipeline.iso_surface(surface) # limit contours for simpler surfaces including smaller file sizes; # TODO: consider making settable as arg or through profile surface.contour.number_of_contours = 1 try: # increase min to further reduce complexity surface.contour.minimum_contour = 0.5 surface.contour.maximum_contour = 0.8 except Exception as e: print(e) print("ignoring min/max contour for now") ''' if offset is not None: # translate to offset scaled by isotropic factor surface.actor.actor.position = np.multiply( offset, isotropic)[::-1] # scale surfaces, which expands/contracts but does not appear # to translate the surface position surface.actor.actor.scale = isotropic[::-1] surfaces.append(surface) # keep visual ordering of surfaces when opacity is reduced self.scene.renderer.use_depth_peeling = True print("time to render 3D surface: {}".format(time() - time_start)) self.surfaces = surfaces return surfaces def _shadow_blob(self, x, y, z, cmap_indices, cmap, scale): """Shows blobs as shadows projected parallel to the 3D visualization. Parmas: x: Array of x-coordinates of blobs. y: Array of y-coordinates of blobs. z: Array of z-coordinates of blobs. cmap_indices: Indices of blobs for the colormap, usually given as a simple ascending sequence the same size as the number of blobs. cmap: The colormap, usually the same as for the segments. scale: Array of scaled size of each blob. """ pts_shadows = self.scene.mlab.points3d( x, y, z, cmap_indices, mode="2dcircle", scale_mode="none", scale_factor=scale * 0.8, resolution=20) pts_shadows.module_manager.scalar_lut_manager.lut.table = cmap return pts_shadows def show_blobs(self, segments, segs_in_mask, cmap, roi_offset, roi_size, show_shadows=False, flipz=None): """Show 3D blobs as points. Args: segments: Labels from 3D blob detection method. segs_in_mask: Boolean mask for segments within the ROI; all other segments are assumed to be from padding and border regions surrounding the ROI. cmap (:class:`numpy.ndaarry`): Colormap as a 2D Numpy array in the format ``[[R, G, B, alpha], ...]``. roi_offset (Sequence[int]): Region of interest offset in ``z,y,x``. roi_size (Sequence[int]): Region of interest size in ``z,y,x``. Used to show the ROI outline. show_shadows: True if shadows of blobs should be depicted on planes behind the blobs; defaults to False. flipz (bool): True to invert blobs along the z-axis to match the handedness of Matplotlib with z progressing upward; defaults to False. Returns: A 3-element tuple containing ``pts_in``, the 3D points within the ROI; ``cmap'', the random colormap generated with a color for each blob, and ``scale``, the current size of the points. """ if segments.shape[0] <= 0: return None, 0 if roi_offset is None: roi_offset = np.zeros(3, dtype=np.int) if self.blobs: for blob in self.blobs: # remove existing blob glyphs from the pipeline blob.remove() settings = config.roi_profile # copy blobs with duplicate columns to access original values for # the coordinates callback when a blob is selected segs = np.concatenate((segments[:, :4], segments[:, :4]), axis=1) isotropic = plot_3d.get_isotropic_vis(settings) if flipz: # invert along z-axis within the same original space, eg to match # handedness of Matplotlib with z up segs[:, 0] *= -1 roi_offset = np.copy(roi_offset) roi_offset[0] *= -1 roi_size = np.copy(roi_size) roi_size[0] *= -1 segs[:, :3] = np.add(segs[:, :3], roi_offset) if isotropic is not None: # adjust position based on isotropic factor roi_offset = np.multiply(roi_offset, isotropic) roi_size = np.multiply(roi_size[:3], isotropic) segs[:, :3] = np.multiply(segs[:, :3], isotropic) radii = segs[:, 3] scale = 5 if radii is None else np.mean(np.mean(radii) + np.amax(radii)) print("blob point scaling: {}".format(scale)) # colormap has to be at least 2 colors segs_in = segs[segs_in_mask] cmap_indices = np.arange(segs_in.shape[0]) if show_shadows: # show projections onto side planes, assumed to be at -10 units # along the given axis segs_ones = np.ones(segs.shape[0]) # xy self._shadow_blob( segs_in[:, 2], segs_in[:, 1], segs_ones * -10, cmap_indices, cmap, scale) # xz shadows = self._shadow_blob( segs_in[:, 2], segs_in[:, 0], segs_ones * -10, cmap_indices, cmap, scale) shadows.actor.actor.orientation = [90, 0, 0] shadows.actor.actor.position = [0, -20, 0] # yz shadows = self._shadow_blob( segs_in[:, 1], segs_in[:, 0], segs_ones * -10, cmap_indices, cmap, scale) shadows.actor.actor.orientation = [90, 90, 0] shadows.actor.actor.position = [0, 0, 0] # show blobs within the ROI points_len = len(segs) mask = math.ceil(points_len / self._MASK_DIVIDEND) print("points: {}, mask: {}".format(points_len, mask)) pts_in = None self.blobs = [] if len(segs_in) > 0: # each Glyph contains multiple 3D points, one for each blob pts_in = self.scene.mlab.points3d( segs_in[:, 2], segs_in[:, 1], segs_in[:, 0], cmap_indices, mask_points=mask, scale_mode="none", scale_factor=scale, resolution=50) pts_in.module_manager.scalar_lut_manager.lut.table = cmap self.blobs.append(pts_in) # show blobs within padding or border region as black and more # transparent segs_out_mask = np.logical_not(segs_in_mask) if np.sum(segs_out_mask) > 0: self.blobs.append(self.scene.mlab.points3d( segs[segs_out_mask, 2], segs[segs_out_mask, 1], segs[segs_out_mask, 0], color=(0, 0, 0), mask_points=mask, scale_mode="none", scale_factor=scale / 2, resolution=50, opacity=0.2)) def pick_callback(pick): # handle picking blobs/glyphs if pick.actor in pts_in.actor.actors: # get the blob corresponding to the picked glyph actor blobi = pick.point_id // glyph_points.shape[0] else: # find the closest blob to the pick position dists = np.linalg.norm( segs_in[:, :3] - pick.pick_position[::-1], axis=1) blobi = np.argmin(dists) if dists[blobi] > max_dist: # remove blob if not within a tolerated distance blobi = None if blobi is None: # revert outline to full ROI if no blob is found self.show_roi_outline(roi_offset, roi_size) else: # move outline cube to surround picked blob; each glyph has # has many points, and each point ID maps to a data index # after floor division by the number of points z, y, x, r = segs_in[blobi, :4] outline.bounds = (x - r, x + r, y - r, y + r, z - r, z + r) if self.fn_update_coords: # callback to update coordinates using blob's orig coords self.fn_update_coords(np.add( segs_in[blobi, 4:7], roi_offset).astype(np.int)) # show ROI outline and make blobs pickable, falling back to closest # blobs within 20% of the longest ROI edge to be picked if present outline = self.show_roi_outline(roi_offset, roi_size) print(outline) glyph_points = pts_in.glyph.glyph_source.glyph_source.output.points.\ to_array() max_dist = max(roi_size) * 0.2 self.scene.mlab.gcf().on_mouse_pick(pick_callback) return pts_in, scale def _shadow_img2d(self, img2d, shape, axis): """Shows a plane along the given axis as a shadow parallel to the 3D visualization. Args: img2d: The plane to show. shape: Shape of the ROI. axis: Axis along which the plane lies. Returns: The displayed plane. """ img2d = np.swapaxes(img2d, 0, 1) img2d[img2d < 1] = 0 # expands the plane to match the size of the xy plane, with this # plane in the middle extra_z = (shape[axis] - shape[0]) // 2 if extra_z > 0: img2d_full = np.zeros(shape[1] * shape[2]) img2d_full = np.reshape(img2d_full, [shape[1], shape[2]]) img2d_full[:, extra_z:extra_z + img2d.shape[1]] = img2d img2d = img2d_full return self.scene.mlab.imshow(img2d, opacity=0.5, colormap="gray") def plot_2d_shadows(self, roi, flipz=False): """Plots 2D shadows in each axis around the 3D visualization. Args: roi (:class:`numpy.ndarray`): Region of interest. flipz (bool): True to invert ``roi`` along z-axis to match handedness of Matplotlib with z progressing upward; defaults to False. """ # set up shapes, accounting for any isotropic resizing if flipz: # invert along z-axis to match handedness of Matplotlib with z up roi = roi[::-1] if len(roi.shape) > 2: # covert 4D to 3D array, using only the 1st channel roi = roi[:, :, :, 0] isotropic = plot_3d.get_isotropic_vis(config.roi_profile) shape = roi.shape shape_iso = np.multiply(roi.shape, isotropic).astype(np.int) shape_iso_mid = shape_iso // 2 # TODO: shift z by +10? # xy-plane, positioned just below the 3D ROI img2d = roi[shape[0] // 2, :, :] img2d = transform.resize( img2d, np.multiply(img2d.shape, isotropic[1:]).astype(np.int), preserve_range=True) img2d_mlab = self._shadow_img2d(img2d, shape_iso, 0) # Mayavi positions are in x,y,z img2d_mlab.actor.position = [ shape_iso_mid[2], shape_iso_mid[1], -10] # xz-plane img2d = roi[:, shape[1] // 2, :] img2d = transform.resize( img2d, np.multiply(img2d.shape, isotropic[[0, 2]]).astype(np.int), preserve_range=True) img2d_mlab = self._shadow_img2d(img2d, shape_iso, 2) img2d_mlab.actor.position = [ -10, shape_iso_mid[1], shape_iso_mid[0]] img2d_mlab.actor.orientation = [90, 90, 0] # yz-plane img2d = roi[:, :, shape[2] // 2] img2d = transform.resize( img2d, np.multiply(img2d.shape, isotropic[:2]).astype(np.int), preserve_range=True) img2d_mlab = self._shadow_img2d(img2d, shape_iso, 1) img2d_mlab.actor.position = [ shape_iso_mid[2], -10, shape_iso_mid[0]] img2d_mlab.actor.orientation = [90, 0, 0] def show_roi_outline(self, roi_offset, roi_size): """Show plot outline to show ROI borders. Args: roi_offset (Sequence[int]): Region of interest offset in ``z,y,x``. roi_size (Sequence[int]): Region of interest size in ``z,y,x``. Returns: :class:`mayavi.modules.outline.Outline`: Outline object. """ # manually calculate extent since the default bounds do not always # capture all objects and to include any empty border spaces return self.scene.mlab.outline( extent=np.array(tuple(zip(roi_offset, np.add( roi_offset, roi_size)))).ravel()[::-1]) def clear_scene(self): """Clear the scene.""" print("Clearing 3D scene") self.scene.mlab.clf()
# 3D visualization in MagellanMapper import math from time import time import numpy as np from skimage import filters, restoration, transform from magmap.cv import segmenter from magmap.io import libmag from magmap.plot import colormaps, plot_3d from magmap.settings import config class Vis3D: """3D visualization object for handling Mayavi/VTK tasks. Attributes: scene (:class:`mayavi.tools.mlab_scene_model.MlabSceneModel`): Mayavi scene. fn_update_coords (func): Callback to update coordinates; defaults to None. surfaces (list): List of Mayavi surfaces for each displayed channel; defaults to None. blobs (list[:class:`mayavi.modules.glyph.Glyph`]): List of Mayavi glyphs, where each glyph typically contains many 3D points representing blob positions; defaults to None. """ #: float: Maximum number of points to show. _MASK_DIVIDEND = 10000.0 # 3D max points def __init__(self, scene): """Initialize a 3D visualization object. Args: scene (:class:`mayavi.tools.mlab_scene_model.MlabSceneModel`): Mayavi scene. """ self.scene = scene # callbacks self.fn_update_coords = None # generated Mayavi objects self.surfaces = None self.blobs = None def update_img_display(self, minimum=None, maximum=None, brightness=None, contrast=None, alpha=None): """Update the displayed image settings. Args: minimum (float): Minimum intensity. maximum (float): Maximum intensity. brightness (float): Brightness gamma. contrast (float): Contrast factor. alpha (float): Opacity, from 0-1, where 1 is fully opaque. Returns: """ if self.surfaces: for surface in self.surfaces: if alpha is not None: surface.actor.property.opacity = alpha def plot_3d_points(self, roi, channel, flipz=False, offset=None): """Plots all pixels as points in 3D space. Points falling below a given threshold will be removed, allowing the viewer to see through the presumed background to masses within the region of interest. Args: roi (:class:`numpy.ndarray`): Region of interest either as a 3D ``z,y,x`` or 4D ``z,y,x,c`` array. channel (int): Channel to select, which can be None to indicate all channels. flipz (bool): True to invert the ROI along the z-axis to match the handedness of Matplotlib with z progressing upward; defaults to False. offset (Sequence[int]): Origin coordinates in ``z,y,x``; defaults to None. Returns: bool: True if points were rendered, False if no points to render. """ print("Plotting ROI as 3D points") # streamline the image if roi is None or roi.size < 1: return False roi = plot_3d.saturate_roi(roi, clip_vmax=98.5, channel=channel) roi = np.clip(roi, 0.2, 0.8) roi = restoration.denoise_tv_chambolle(roi, weight=0.1) # separate parallel arrays for each dimension of all coordinates for # Mayavi input format, with the ROI itself given as a 1D scalar array ; # TODO: consider using np.mgrid to construct the x,y,z arrays time_start = time() shape = roi.shape isotropic = plot_3d.get_isotropic_vis(config.roi_profile) z = np.ones((shape[0], shape[1] * shape[2])) for i in range(shape[0]): z[i] = z[i] * i if flipz: # invert along z-axis to match handedness of Matplotlib with z up z *= -1 if offset is not None: offset = np.copy(offset) offset[0] *= -1 y = np.ones((shape[0] * shape[1], shape[2])) for i in range(shape[0]): for j in range(shape[1]): y[i * shape[1] + j] = y[i * shape[1] + j] * j x = np.ones((shape[0] * shape[1], shape[2])) for i in range(shape[0] * shape[1]): x[i] = np.arange(shape[2]) if offset is not None: offset = np.multiply(offset, isotropic) coords = [z, y, x] for i, _ in enumerate(coords): # scale coordinates for isotropy coords[i] *= isotropic[i] if offset is not None: # translate by offset coords[i] += offset[i] multichannel, channels = plot_3d.setup_channels(roi, channel, 3) for chl in channels: roi_show = roi[..., chl] if multichannel else roi roi_show_1d = roi_show.reshape(roi_show.size) if chl == 0: x = np.reshape(x, roi_show.size) y = np.reshape(y, roi_show.size) z = np.reshape(z, roi_show.size) settings = config.get_roi_profile(chl) # clear background points to see remaining structures thresh = 0 if len(np.unique(roi_show)) > 1: # need > 1 val to threshold try: thresh = filters.threshold_otsu(roi_show, 64) except ValueError as e: thresh = np.median(roi_show) print("could not determine Otsu threshold, taking median " "({}) instead".format(thresh)) thresh *= settings["points_3d_thresh"] print("removing 3D points below threshold of {}".format(thresh)) remove = np.where(roi_show_1d < thresh) roi_show_1d = np.delete(roi_show_1d, remove) # adjust range from 0-1 to region of colormap to use roi_show_1d = libmag.normalize(roi_show_1d, 0.6, 1.0) points_len = roi_show_1d.size if points_len == 0: print("no 3D points to display") return False mask = math.ceil(points_len / self._MASK_DIVIDEND) print("points: {}, mask: {}".format(points_len, mask)) if any(np.isnan(roi_show_1d)): # TODO: see if some NaNs are permissible print("NaN values for 3D points, will not show 3D visualization") return False pts = self.scene.mlab.points3d( np.delete(x, remove), np.delete(y, remove), np.delete(z, remove), roi_show_1d, mode="sphere", scale_mode="scalar", mask_points=mask, line_width=1.0, vmax=1.0, vmin=0.0, transparent=True) cmap = colormaps.get_cmap(config.cmaps, chl) if cmap is not None: pts.module_manager.scalar_lut_manager.lut.table = cmap( range(0, 256)) * 255 # scale glyphs to partially fill in gaps from isotropic scaling; # do not use actor scaling as it also translates the points when # not positioned at the origin pts.glyph.glyph.scale_factor = 2 * max(isotropic) # keep visual ordering of surfaces when opacity is reduced self.scene.renderer.use_depth_peeling = True print("time for 3D points display: {}".format(time() - time_start)) return True def plot_3d_surface(self, roi, channel, segment=False, flipz=False, offset=None): """Plots areas with greater intensity as 3D surfaces. The scene will be cleared before display. Args: roi (:class:`numpy.ndarray`): Region of interest either as a 3D ``z,y,x`` or 4D ``z,y,x,c`` array. channel (int): Channel to select, which can be None to indicate all channels. segment (bool): True to denoise and segment ``roi`` before displaying, which may remove artifacts that might otherwise lead to spurious surfaces. Defaults to False. flipz: True to invert ``roi`` along z-axis to match handedness of Matplotlib with z progressing upward; defaults to False. offset (Sequence[int]): Origin coordinates in ``z,y,x``; defaults to None. Returns: list: List of Mayavi surfaces for each displayed channel, which are also stored in :attr:`surfaces`. """ # Plot in Mayavi print("viewing 3D surface") pipeline = self.scene.mlab.pipeline settings = config.roi_profile if flipz: # invert along z-axis to match handedness of Matplotlib with z up roi = roi[::-1] if offset is not None: # invert z-offset and translate by ROI z-size so ROI is # mirrored across the xy-plane offset = np.copy(offset) offset[0] = -offset[0] - roi.shape[0] isotropic = plot_3d.get_isotropic_vis(settings) # saturate to remove noise and normalize values roi = plot_3d.saturate_roi(roi, channel=channel) # turn off segmentation if ROI too big (arbitrarily set here as # > 10 million pixels) to avoid performance hit and since likely showing # large region of downsampled image anyway, where don't need hi res num_pixels = np.prod(roi.shape) to_segment = num_pixels < 10000000 time_start = time() multichannel, channels = plot_3d.setup_channels(roi, channel, 3) surfaces = [] for chl in channels: roi_show = roi[..., chl] if multichannel else roi # clip to minimize sub-nuclear variation roi_show = np.clip(roi_show, 0.2, 0.8) if segment: # denoising makes for much cleaner images but also seems to # allow structures to blend together # TODO: consider segmenting individual structures and rendering # as separate surfaces to avoid blending roi_show = restoration.denoise_tv_chambolle( roi_show, weight=0.1) # build surface from segmented ROI if to_segment: vmin, vmax = np.percentile(roi_show, (40, 70)) walker = segmenter.segment_rw( roi_show, chl, vmin=vmin, vmax=vmax) roi_show *= np.subtract(walker[0], 1) else: print("deferring segmentation as {} px is above threshold" .format(num_pixels)) # ROI is in (z, y, x) order, so need to transpose or swap x,z axes roi_show = np.transpose(roi_show) surface = pipeline.scalar_field(roi_show) # Contour -> Surface pipeline # create the surface surface = pipeline.contour(surface) # remove many more extraneous points surface = pipeline.user_defined( surface, filter="SmoothPolyDataFilter") surface.filter.number_of_iterations = 400 surface.filter.relaxation_factor = 0.015 # distinguishing pos vs neg curvatures? surface = pipeline.user_defined(surface, filter="Curvatures") surface = self.scene.mlab.pipeline.surface(surface) module_manager = surface.module_manager module_manager.scalar_lut_manager.data_range = np.array([-2, 0]) module_manager.scalar_lut_manager.lut_mode = "gray" ''' # Surface pipleline with contours enabled (similar to above?) surface = pipeline.contour_surface( surface, color=(0.7, 1, 0.7), line_width=6.0) surface.actor.property.representation = 'wireframe' #surface.actor.property.line_width = 6.0 surface.actor.mapper.scalar_visibility = False ''' ''' # IsoSurface pipeline # uses unique IsoSurface module but appears to have # similar output to contour_surface surface = pipeline.iso_surface(surface) # limit contours for simpler surfaces including smaller file sizes; # TODO: consider making settable as arg or through profile surface.contour.number_of_contours = 1 try: # increase min to further reduce complexity surface.contour.minimum_contour = 0.5 surface.contour.maximum_contour = 0.8 except Exception as e: print(e) print("ignoring min/max contour for now") ''' if offset is not None: # translate to offset scaled by isotropic factor surface.actor.actor.position = np.multiply( offset, isotropic)[::-1] # scale surfaces, which expands/contracts but does not appear # to translate the surface position surface.actor.actor.scale = isotropic[::-1] surfaces.append(surface) # keep visual ordering of surfaces when opacity is reduced self.scene.renderer.use_depth_peeling = True print("time to render 3D surface: {}".format(time() - time_start)) self.surfaces = surfaces return surfaces def _shadow_blob(self, x, y, z, cmap_indices, cmap, scale): """Shows blobs as shadows projected parallel to the 3D visualization. Parmas: x: Array of x-coordinates of blobs. y: Array of y-coordinates of blobs. z: Array of z-coordinates of blobs. cmap_indices: Indices of blobs for the colormap, usually given as a simple ascending sequence the same size as the number of blobs. cmap: The colormap, usually the same as for the segments. scale: Array of scaled size of each blob. """ pts_shadows = self.scene.mlab.points3d( x, y, z, cmap_indices, mode="2dcircle", scale_mode="none", scale_factor=scale * 0.8, resolution=20) pts_shadows.module_manager.scalar_lut_manager.lut.table = cmap return pts_shadows def show_blobs(self, segments, segs_in_mask, cmap, roi_offset, roi_size, show_shadows=False, flipz=None): """Show 3D blobs as points. Args: segments: Labels from 3D blob detection method. segs_in_mask: Boolean mask for segments within the ROI; all other segments are assumed to be from padding and border regions surrounding the ROI. cmap (:class:`numpy.ndaarry`): Colormap as a 2D Numpy array in the format ``[[R, G, B, alpha], ...]``. roi_offset (Sequence[int]): Region of interest offset in ``z,y,x``. roi_size (Sequence[int]): Region of interest size in ``z,y,x``. Used to show the ROI outline. show_shadows: True if shadows of blobs should be depicted on planes behind the blobs; defaults to False. flipz (bool): True to invert blobs along the z-axis to match the handedness of Matplotlib with z progressing upward; defaults to False. Returns: A 3-element tuple containing ``pts_in``, the 3D points within the ROI; ``cmap'', the random colormap generated with a color for each blob, and ``scale``, the current size of the points. """ if segments.shape[0] <= 0: return None, 0 if roi_offset is None: roi_offset = np.zeros(3, dtype=np.int) if self.blobs: for blob in self.blobs: # remove existing blob glyphs from the pipeline blob.remove() settings = config.roi_profile # copy blobs with duplicate columns to access original values for # the coordinates callback when a blob is selected segs = np.concatenate((segments[:, :4], segments[:, :4]), axis=1) isotropic = plot_3d.get_isotropic_vis(settings) if flipz: # invert along z-axis within the same original space, eg to match # handedness of Matplotlib with z up segs[:, 0] *= -1 roi_offset = np.copy(roi_offset) roi_offset[0] *= -1 roi_size = np.copy(roi_size) roi_size[0] *= -1 segs[:, :3] = np.add(segs[:, :3], roi_offset) if isotropic is not None: # adjust position based on isotropic factor roi_offset = np.multiply(roi_offset, isotropic) roi_size = np.multiply(roi_size[:3], isotropic) segs[:, :3] = np.multiply(segs[:, :3], isotropic) radii = segs[:, 3] scale = 5 if radii is None else np.mean(np.mean(radii) + np.amax(radii)) print("blob point scaling: {}".format(scale)) # colormap has to be at least 2 colors segs_in = segs[segs_in_mask] cmap_indices = np.arange(segs_in.shape[0]) if show_shadows: # show projections onto side planes, assumed to be at -10 units # along the given axis segs_ones = np.ones(segs.shape[0]) # xy self._shadow_blob( segs_in[:, 2], segs_in[:, 1], segs_ones * -10, cmap_indices, cmap, scale) # xz shadows = self._shadow_blob( segs_in[:, 2], segs_in[:, 0], segs_ones * -10, cmap_indices, cmap, scale) shadows.actor.actor.orientation = [90, 0, 0] shadows.actor.actor.position = [0, -20, 0] # yz shadows = self._shadow_blob( segs_in[:, 1], segs_in[:, 0], segs_ones * -10, cmap_indices, cmap, scale) shadows.actor.actor.orientation = [90, 90, 0] shadows.actor.actor.position = [0, 0, 0] # show blobs within the ROI points_len = len(segs) mask = math.ceil(points_len / self._MASK_DIVIDEND) print("points: {}, mask: {}".format(points_len, mask)) pts_in = None self.blobs = [] if len(segs_in) > 0: # each Glyph contains multiple 3D points, one for each blob pts_in = self.scene.mlab.points3d( segs_in[:, 2], segs_in[:, 1], segs_in[:, 0], cmap_indices, mask_points=mask, scale_mode="none", scale_factor=scale, resolution=50) pts_in.module_manager.scalar_lut_manager.lut.table = cmap self.blobs.append(pts_in) # show blobs within padding or border region as black and more # transparent segs_out_mask = np.logical_not(segs_in_mask) if np.sum(segs_out_mask) > 0: self.blobs.append(self.scene.mlab.points3d( segs[segs_out_mask, 2], segs[segs_out_mask, 1], segs[segs_out_mask, 0], color=(0, 0, 0), mask_points=mask, scale_mode="none", scale_factor=scale / 2, resolution=50, opacity=0.2)) def pick_callback(pick): # handle picking blobs/glyphs if pick.actor in pts_in.actor.actors: # get the blob corresponding to the picked glyph actor blobi = pick.point_id // glyph_points.shape[0] else: # find the closest blob to the pick position dists = np.linalg.norm( segs_in[:, :3] - pick.pick_position[::-1], axis=1) blobi = np.argmin(dists) if dists[blobi] > max_dist: # remove blob if not within a tolerated distance blobi = None if blobi is None: # revert outline to full ROI if no blob is found self.show_roi_outline(roi_offset, roi_size) else: # move outline cube to surround picked blob; each glyph has # has many points, and each point ID maps to a data index # after floor division by the number of points z, y, x, r = segs_in[blobi, :4] outline.bounds = (x - r, x + r, y - r, y + r, z - r, z + r) if self.fn_update_coords: # callback to update coordinates using blob's orig coords self.fn_update_coords(np.add( segs_in[blobi, 4:7], roi_offset).astype(np.int)) # show ROI outline and make blobs pickable, falling back to closest # blobs within 20% of the longest ROI edge to be picked if present outline = self.show_roi_outline(roi_offset, roi_size) print(outline) glyph_points = pts_in.glyph.glyph_source.glyph_source.output.points.\ to_array() max_dist = max(roi_size) * 0.2 self.scene.mlab.gcf().on_mouse_pick(pick_callback) return pts_in, scale def _shadow_img2d(self, img2d, shape, axis): """Shows a plane along the given axis as a shadow parallel to the 3D visualization. Args: img2d: The plane to show. shape: Shape of the ROI. axis: Axis along which the plane lies. Returns: The displayed plane. """ img2d = np.swapaxes(img2d, 0, 1) img2d[img2d < 1] = 0 # expands the plane to match the size of the xy plane, with this # plane in the middle extra_z = (shape[axis] - shape[0]) // 2 if extra_z > 0: img2d_full = np.zeros(shape[1] * shape[2]) img2d_full = np.reshape(img2d_full, [shape[1], shape[2]]) img2d_full[:, extra_z:extra_z + img2d.shape[1]] = img2d img2d = img2d_full return self.scene.mlab.imshow(img2d, opacity=0.5, colormap="gray") def plot_2d_shadows(self, roi, flipz=False): """Plots 2D shadows in each axis around the 3D visualization. Args: roi (:class:`numpy.ndarray`): Region of interest. flipz (bool): True to invert ``roi`` along z-axis to match handedness of Matplotlib with z progressing upward; defaults to False. """ # set up shapes, accounting for any isotropic resizing if flipz: # invert along z-axis to match handedness of Matplotlib with z up roi = roi[::-1] if len(roi.shape) > 2: # covert 4D to 3D array, using only the 1st channel roi = roi[:, :, :, 0] isotropic = plot_3d.get_isotropic_vis(config.roi_profile) shape = roi.shape shape_iso = np.multiply(roi.shape, isotropic).astype(np.int) shape_iso_mid = shape_iso // 2 # TODO: shift z by +10? # xy-plane, positioned just below the 3D ROI img2d = roi[shape[0] // 2, :, :] img2d = transform.resize( img2d, np.multiply(img2d.shape, isotropic[1:]).astype(np.int), preserve_range=True) img2d_mlab = self._shadow_img2d(img2d, shape_iso, 0) # Mayavi positions are in x,y,z img2d_mlab.actor.position = [ shape_iso_mid[2], shape_iso_mid[1], -10] # xz-plane img2d = roi[:, shape[1] // 2, :] img2d = transform.resize( img2d, np.multiply(img2d.shape, isotropic[[0, 2]]).astype(np.int), preserve_range=True) img2d_mlab = self._shadow_img2d(img2d, shape_iso, 2) img2d_mlab.actor.position = [ -10, shape_iso_mid[1], shape_iso_mid[0]] img2d_mlab.actor.orientation = [90, 90, 0] # yz-plane img2d = roi[:, :, shape[2] // 2] img2d = transform.resize( img2d, np.multiply(img2d.shape, isotropic[:2]).astype(np.int), preserve_range=True) img2d_mlab = self._shadow_img2d(img2d, shape_iso, 1) img2d_mlab.actor.position = [ shape_iso_mid[2], -10, shape_iso_mid[0]] img2d_mlab.actor.orientation = [90, 0, 0] def show_roi_outline(self, roi_offset, roi_size): """Show plot outline to show ROI borders. Args: roi_offset (Sequence[int]): Region of interest offset in ``z,y,x``. roi_size (Sequence[int]): Region of interest size in ``z,y,x``. Returns: :class:`mayavi.modules.outline.Outline`: Outline object. """ # manually calculate extent since the default bounds do not always # capture all objects and to include any empty border spaces return self.scene.mlab.outline( extent=np.array(tuple(zip(roi_offset, np.add( roi_offset, roi_size)))).ravel()[::-1]) def clear_scene(self): """Clear the scene.""" print("Clearing 3D scene") self.scene.mlab.clf()
en
0.807034
# 3D visualization in MagellanMapper 3D visualization object for handling Mayavi/VTK tasks. Attributes: scene (:class:`mayavi.tools.mlab_scene_model.MlabSceneModel`): Mayavi scene. fn_update_coords (func): Callback to update coordinates; defaults to None. surfaces (list): List of Mayavi surfaces for each displayed channel; defaults to None. blobs (list[:class:`mayavi.modules.glyph.Glyph`]): List of Mayavi glyphs, where each glyph typically contains many 3D points representing blob positions; defaults to None. #: float: Maximum number of points to show. # 3D max points Initialize a 3D visualization object. Args: scene (:class:`mayavi.tools.mlab_scene_model.MlabSceneModel`): Mayavi scene. # callbacks # generated Mayavi objects Update the displayed image settings. Args: minimum (float): Minimum intensity. maximum (float): Maximum intensity. brightness (float): Brightness gamma. contrast (float): Contrast factor. alpha (float): Opacity, from 0-1, where 1 is fully opaque. Returns: Plots all pixels as points in 3D space. Points falling below a given threshold will be removed, allowing the viewer to see through the presumed background to masses within the region of interest. Args: roi (:class:`numpy.ndarray`): Region of interest either as a 3D ``z,y,x`` or 4D ``z,y,x,c`` array. channel (int): Channel to select, which can be None to indicate all channels. flipz (bool): True to invert the ROI along the z-axis to match the handedness of Matplotlib with z progressing upward; defaults to False. offset (Sequence[int]): Origin coordinates in ``z,y,x``; defaults to None. Returns: bool: True if points were rendered, False if no points to render. # streamline the image # separate parallel arrays for each dimension of all coordinates for # Mayavi input format, with the ROI itself given as a 1D scalar array ; # TODO: consider using np.mgrid to construct the x,y,z arrays # invert along z-axis to match handedness of Matplotlib with z up # scale coordinates for isotropy # translate by offset # clear background points to see remaining structures # need > 1 val to threshold # adjust range from 0-1 to region of colormap to use # TODO: see if some NaNs are permissible # scale glyphs to partially fill in gaps from isotropic scaling; # do not use actor scaling as it also translates the points when # not positioned at the origin # keep visual ordering of surfaces when opacity is reduced Plots areas with greater intensity as 3D surfaces. The scene will be cleared before display. Args: roi (:class:`numpy.ndarray`): Region of interest either as a 3D ``z,y,x`` or 4D ``z,y,x,c`` array. channel (int): Channel to select, which can be None to indicate all channels. segment (bool): True to denoise and segment ``roi`` before displaying, which may remove artifacts that might otherwise lead to spurious surfaces. Defaults to False. flipz: True to invert ``roi`` along z-axis to match handedness of Matplotlib with z progressing upward; defaults to False. offset (Sequence[int]): Origin coordinates in ``z,y,x``; defaults to None. Returns: list: List of Mayavi surfaces for each displayed channel, which are also stored in :attr:`surfaces`. # Plot in Mayavi # invert along z-axis to match handedness of Matplotlib with z up # invert z-offset and translate by ROI z-size so ROI is # mirrored across the xy-plane # saturate to remove noise and normalize values # turn off segmentation if ROI too big (arbitrarily set here as # > 10 million pixels) to avoid performance hit and since likely showing # large region of downsampled image anyway, where don't need hi res # clip to minimize sub-nuclear variation # denoising makes for much cleaner images but also seems to # allow structures to blend together # TODO: consider segmenting individual structures and rendering # as separate surfaces to avoid blending # build surface from segmented ROI # ROI is in (z, y, x) order, so need to transpose or swap x,z axes # Contour -> Surface pipeline # create the surface # remove many more extraneous points # distinguishing pos vs neg curvatures? # Surface pipleline with contours enabled (similar to above?) surface = pipeline.contour_surface( surface, color=(0.7, 1, 0.7), line_width=6.0) surface.actor.property.representation = 'wireframe' #surface.actor.property.line_width = 6.0 surface.actor.mapper.scalar_visibility = False # IsoSurface pipeline # uses unique IsoSurface module but appears to have # similar output to contour_surface surface = pipeline.iso_surface(surface) # limit contours for simpler surfaces including smaller file sizes; # TODO: consider making settable as arg or through profile surface.contour.number_of_contours = 1 try: # increase min to further reduce complexity surface.contour.minimum_contour = 0.5 surface.contour.maximum_contour = 0.8 except Exception as e: print(e) print("ignoring min/max contour for now") # translate to offset scaled by isotropic factor # scale surfaces, which expands/contracts but does not appear # to translate the surface position # keep visual ordering of surfaces when opacity is reduced Shows blobs as shadows projected parallel to the 3D visualization. Parmas: x: Array of x-coordinates of blobs. y: Array of y-coordinates of blobs. z: Array of z-coordinates of blobs. cmap_indices: Indices of blobs for the colormap, usually given as a simple ascending sequence the same size as the number of blobs. cmap: The colormap, usually the same as for the segments. scale: Array of scaled size of each blob. Show 3D blobs as points. Args: segments: Labels from 3D blob detection method. segs_in_mask: Boolean mask for segments within the ROI; all other segments are assumed to be from padding and border regions surrounding the ROI. cmap (:class:`numpy.ndaarry`): Colormap as a 2D Numpy array in the format ``[[R, G, B, alpha], ...]``. roi_offset (Sequence[int]): Region of interest offset in ``z,y,x``. roi_size (Sequence[int]): Region of interest size in ``z,y,x``. Used to show the ROI outline. show_shadows: True if shadows of blobs should be depicted on planes behind the blobs; defaults to False. flipz (bool): True to invert blobs along the z-axis to match the handedness of Matplotlib with z progressing upward; defaults to False. Returns: A 3-element tuple containing ``pts_in``, the 3D points within the ROI; ``cmap'', the random colormap generated with a color for each blob, and ``scale``, the current size of the points. # remove existing blob glyphs from the pipeline # copy blobs with duplicate columns to access original values for # the coordinates callback when a blob is selected # invert along z-axis within the same original space, eg to match # handedness of Matplotlib with z up # adjust position based on isotropic factor # colormap has to be at least 2 colors # show projections onto side planes, assumed to be at -10 units # along the given axis # xy # xz # yz # show blobs within the ROI # each Glyph contains multiple 3D points, one for each blob # show blobs within padding or border region as black and more # transparent # handle picking blobs/glyphs # get the blob corresponding to the picked glyph actor # find the closest blob to the pick position # remove blob if not within a tolerated distance # revert outline to full ROI if no blob is found # move outline cube to surround picked blob; each glyph has # has many points, and each point ID maps to a data index # after floor division by the number of points # callback to update coordinates using blob's orig coords # show ROI outline and make blobs pickable, falling back to closest # blobs within 20% of the longest ROI edge to be picked if present Shows a plane along the given axis as a shadow parallel to the 3D visualization. Args: img2d: The plane to show. shape: Shape of the ROI. axis: Axis along which the plane lies. Returns: The displayed plane. # expands the plane to match the size of the xy plane, with this # plane in the middle Plots 2D shadows in each axis around the 3D visualization. Args: roi (:class:`numpy.ndarray`): Region of interest. flipz (bool): True to invert ``roi`` along z-axis to match handedness of Matplotlib with z progressing upward; defaults to False. # set up shapes, accounting for any isotropic resizing # invert along z-axis to match handedness of Matplotlib with z up # covert 4D to 3D array, using only the 1st channel # TODO: shift z by +10? # xy-plane, positioned just below the 3D ROI # Mayavi positions are in x,y,z # xz-plane # yz-plane Show plot outline to show ROI borders. Args: roi_offset (Sequence[int]): Region of interest offset in ``z,y,x``. roi_size (Sequence[int]): Region of interest size in ``z,y,x``. Returns: :class:`mayavi.modules.outline.Outline`: Outline object. # manually calculate extent since the default bounds do not always # capture all objects and to include any empty border spaces Clear the scene.
2.247025
2
maddpg/common/torch_utils.py
cying9/maddpg
0
6613735
import torch from torch import nn from torch import functional as F def get_device(disable_cuda=False): if (not disable_cuda) & torch.cuda.is_available(): device = "cuda" print(f'Using CUDA ({torch.cuda.get_device_name(torch.cuda.current_device())})') else: print('Using CPU') device = "cpu" return torch.device(device) def init_params(model, gain=1.0): for params in model.parameters(): if len(params.shape) > 1: nn.init.xavier_uniform_(params.data, gain=gain)
import torch from torch import nn from torch import functional as F def get_device(disable_cuda=False): if (not disable_cuda) & torch.cuda.is_available(): device = "cuda" print(f'Using CUDA ({torch.cuda.get_device_name(torch.cuda.current_device())})') else: print('Using CPU') device = "cpu" return torch.device(device) def init_params(model, gain=1.0): for params in model.parameters(): if len(params.shape) > 1: nn.init.xavier_uniform_(params.data, gain=gain)
none
1
2.755692
3
overlap/overlap/overlap.py
carlos-ferras/code-challenge
1
6613736
<filename>overlap/overlap/overlap.py from typing import Tuple Line = Tuple[int, int] def is_number_inside_boundaries(number: int, boundaries: Line) -> bool: """Check if a number is contained into the specified boundaries :param number: The number to check into the boundaries :param boundaries: Two numbers tuple whit first element < second element :return: True if the number is inside the boundaries, if not, False """ return min(boundaries) <= number <= max(boundaries) def overlap_ordered(line1: Line, line2: Line) -> bool: """Check if two lines in the X axis overlap; the first one must be before or inside the second :param line1: Two numbers tuple whit first element < second element :param line2: Two numbers tuple whit first element < second element :return: True if the lines overlap, if not, False """ return is_number_inside_boundaries(line1[0], line2) or is_number_inside_boundaries(line1[1], line2) def overlap(line1: Line, line2: Line) -> bool: """Check if two lines in the X axis overlap :param line1: Two numbers tuple whit first element < second element :param line2: Two numbers tuple whit first element < second element :return: True if the lines overlap, if not, False """ return overlap_ordered(line1, line2) or overlap_ordered(line2, line1)
<filename>overlap/overlap/overlap.py from typing import Tuple Line = Tuple[int, int] def is_number_inside_boundaries(number: int, boundaries: Line) -> bool: """Check if a number is contained into the specified boundaries :param number: The number to check into the boundaries :param boundaries: Two numbers tuple whit first element < second element :return: True if the number is inside the boundaries, if not, False """ return min(boundaries) <= number <= max(boundaries) def overlap_ordered(line1: Line, line2: Line) -> bool: """Check if two lines in the X axis overlap; the first one must be before or inside the second :param line1: Two numbers tuple whit first element < second element :param line2: Two numbers tuple whit first element < second element :return: True if the lines overlap, if not, False """ return is_number_inside_boundaries(line1[0], line2) or is_number_inside_boundaries(line1[1], line2) def overlap(line1: Line, line2: Line) -> bool: """Check if two lines in the X axis overlap :param line1: Two numbers tuple whit first element < second element :param line2: Two numbers tuple whit first element < second element :return: True if the lines overlap, if not, False """ return overlap_ordered(line1, line2) or overlap_ordered(line2, line1)
en
0.808119
Check if a number is contained into the specified boundaries :param number: The number to check into the boundaries :param boundaries: Two numbers tuple whit first element < second element :return: True if the number is inside the boundaries, if not, False Check if two lines in the X axis overlap; the first one must be before or inside the second :param line1: Two numbers tuple whit first element < second element :param line2: Two numbers tuple whit first element < second element :return: True if the lines overlap, if not, False Check if two lines in the X axis overlap :param line1: Two numbers tuple whit first element < second element :param line2: Two numbers tuple whit first element < second element :return: True if the lines overlap, if not, False
3.944636
4
lib/python/treadmill/sproc/warpgate.py
bretttegartms/treadmill
133
6613737
<reponame>bretttegartms/treadmill """Warpgate client CLI. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import click from treadmill import cli from treadmill.warpgate import client _LOGGER = logging.getLogger(__name__) def init(): """Top level command handler.""" @click.command() @click.option('--policy-servers', type=cli.LIST, required=True, help='Warpgate policy servers') @click.option('--service-principal', type=str, default='host', help='Warpgate service principal.') @click.option('--policy', type=str, required=True, envvar='WARPGATE_POLICY', help='Warpget policy to use') @click.option('--tun-dev', type=str, required=True, help='Device to use when establishing tunnels.') @click.option('--tun-addr', type=str, required=False, help='Local IP address to use when establishing tunnels.') def warpgate(policy_servers, service_principal, policy, tun_dev, tun_addr): """Run warpgate connection manager. """ _LOGGER.info( 'Launch client => %s, tunnel: %s[%s], policy: %s, principal: %s', policy_servers, tun_dev, tun_addr, policy, service_principal, ) # Never exits client.run_client( policy_servers, service_principal, policy, tun_dev, tun_addr ) return warpgate
"""Warpgate client CLI. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import click from treadmill import cli from treadmill.warpgate import client _LOGGER = logging.getLogger(__name__) def init(): """Top level command handler.""" @click.command() @click.option('--policy-servers', type=cli.LIST, required=True, help='Warpgate policy servers') @click.option('--service-principal', type=str, default='host', help='Warpgate service principal.') @click.option('--policy', type=str, required=True, envvar='WARPGATE_POLICY', help='Warpget policy to use') @click.option('--tun-dev', type=str, required=True, help='Device to use when establishing tunnels.') @click.option('--tun-addr', type=str, required=False, help='Local IP address to use when establishing tunnels.') def warpgate(policy_servers, service_principal, policy, tun_dev, tun_addr): """Run warpgate connection manager. """ _LOGGER.info( 'Launch client => %s, tunnel: %s[%s], policy: %s, principal: %s', policy_servers, tun_dev, tun_addr, policy, service_principal, ) # Never exits client.run_client( policy_servers, service_principal, policy, tun_dev, tun_addr ) return warpgate
en
0.749999
Warpgate client CLI. Top level command handler. Run warpgate connection manager. # Never exits
2.201168
2
scripts/data-importer/main.py
vhermecz/gitariskola
0
6613738
import urllib.request import xlrd3 as xlrd import json import re DATA_URL = "http://www.musztydobay.hu/osszescsalidalexcel.xls" def download_data(url): """Download data from URL and return in binary-string""" response = urllib.request.urlopen(url) data = response.read() return data def extract_from_excel_blob(data): """Open binary blob xls and return data from first sheet in list of strings""" book = xlrd.open_workbook(file_contents = data) sh = book.sheet_by_index(0) for rx in range(sh.nrows): yield [cx.value for cx in sh.row(rx)] def extract_chords(text): def splitter(texts, sep): presult = map(lambda x: x.split(sep), texts) return [item for sublist in presult for item in sublist] def cleanse_chordlist(text): text = re.split('-|\.', text) text = map(str.strip, text) text = map(str.lower, text) text = map(str.capitalize, text) text = list(filter(lambda x:x not in ['', 'Git'], text)) return text text = [text.replace('–', '-').replace('…', '').upper()] text = splitter(text, "V.") text = splitter(text, "VAGY") text = splitter(text, "//") text = splitter(text, "GITISK") text = [cleanse_chordlist(item) for item in text] return text def extract_pageref(text): result = [] while text: index = text.find("-") book = text[0:index+1].strip("-") text = text[index+1:] if index > -1 else "" pages = [] while True: full, page = re.match("(([^,.+]*)[,.+]*)", text).groups() if page: pages.append(page.lstrip("0")) text = text[len(full):] if not len(text) or not text[0].isdigit(): break if pages: book = book.strip() if book == "C" or book.startswith("G"): book = "G" if book == "Cs": book = "Cs1" result.append(dict( book=book, pages=pages, )) return result def convert_to_json_data(data): """Convert list of strings to json format""" if next(data) != ['Dal neve', 'Előadó', 'Könyv', 'Akkord', 'Akkord száma']: raise ValueError("Check input. Might be broken.") for idx, (title, performer, pageref, chords, _) in enumerate(data): chords = [i for i in extract_chords(chords) if i] pageref = extract_pageref(pageref) yield dict( idx=idx, title=title, performer=performer, pagerefs=pageref, chords=chords, ) def export_json(data, fname): """Export json data to file""" data = list(data) with open(fname, "w") as fp: fp.write("//Autogenerated do not modify\n\nexport const CHORDINFO = " + json.dumps(data, indent=4, sort_keys=True) + ";") def main(): data = download_data(DATA_URL) data = extract_from_excel_blob(data) data = convert_to_json_data(data) export_json(data, "../../src/config/chordinfo.js") if __name__ == "__main__": main()
import urllib.request import xlrd3 as xlrd import json import re DATA_URL = "http://www.musztydobay.hu/osszescsalidalexcel.xls" def download_data(url): """Download data from URL and return in binary-string""" response = urllib.request.urlopen(url) data = response.read() return data def extract_from_excel_blob(data): """Open binary blob xls and return data from first sheet in list of strings""" book = xlrd.open_workbook(file_contents = data) sh = book.sheet_by_index(0) for rx in range(sh.nrows): yield [cx.value for cx in sh.row(rx)] def extract_chords(text): def splitter(texts, sep): presult = map(lambda x: x.split(sep), texts) return [item for sublist in presult for item in sublist] def cleanse_chordlist(text): text = re.split('-|\.', text) text = map(str.strip, text) text = map(str.lower, text) text = map(str.capitalize, text) text = list(filter(lambda x:x not in ['', 'Git'], text)) return text text = [text.replace('–', '-').replace('…', '').upper()] text = splitter(text, "V.") text = splitter(text, "VAGY") text = splitter(text, "//") text = splitter(text, "GITISK") text = [cleanse_chordlist(item) for item in text] return text def extract_pageref(text): result = [] while text: index = text.find("-") book = text[0:index+1].strip("-") text = text[index+1:] if index > -1 else "" pages = [] while True: full, page = re.match("(([^,.+]*)[,.+]*)", text).groups() if page: pages.append(page.lstrip("0")) text = text[len(full):] if not len(text) or not text[0].isdigit(): break if pages: book = book.strip() if book == "C" or book.startswith("G"): book = "G" if book == "Cs": book = "Cs1" result.append(dict( book=book, pages=pages, )) return result def convert_to_json_data(data): """Convert list of strings to json format""" if next(data) != ['Dal neve', 'Előadó', 'Könyv', 'Akkord', 'Akkord száma']: raise ValueError("Check input. Might be broken.") for idx, (title, performer, pageref, chords, _) in enumerate(data): chords = [i for i in extract_chords(chords) if i] pageref = extract_pageref(pageref) yield dict( idx=idx, title=title, performer=performer, pagerefs=pageref, chords=chords, ) def export_json(data, fname): """Export json data to file""" data = list(data) with open(fname, "w") as fp: fp.write("//Autogenerated do not modify\n\nexport const CHORDINFO = " + json.dumps(data, indent=4, sort_keys=True) + ";") def main(): data = download_data(DATA_URL) data = extract_from_excel_blob(data) data = convert_to_json_data(data) export_json(data, "../../src/config/chordinfo.js") if __name__ == "__main__": main()
en
0.712132
Download data from URL and return in binary-string Open binary blob xls and return data from first sheet in list of strings Convert list of strings to json format Export json data to file
3.293633
3
biobb_amber/nab/__init__.py
bioexcel/biobb_amber
0
6613739
name = "nab" __all__ = ["nab_build_dna_structure"]
name = "nab" __all__ = ["nab_build_dna_structure"]
none
1
1.010792
1
other_code/TIFtoJPG.py
EoNjesajo/SemiSeg_CPS_Reproduction
0
6613740
import os import cv2 from skimage.io import imread file_path = "path to tif data dir" save_path = "path to save dir" for file_name in os.listdir(file_path): print(file_name) image = imread(file_path+file_name) image = image / (2**14-1, 2**14-1, 2**14-1, 2**14-1) *255 image = image[...,:3] name = file_name.split('.')[0] + '.jpg' cv2.imwrite(os.path.join(save_path,name),image,[int(cv2.IMWRITE_JPEG_QUALITY), 200])
import os import cv2 from skimage.io import imread file_path = "path to tif data dir" save_path = "path to save dir" for file_name in os.listdir(file_path): print(file_name) image = imread(file_path+file_name) image = image / (2**14-1, 2**14-1, 2**14-1, 2**14-1) *255 image = image[...,:3] name = file_name.split('.')[0] + '.jpg' cv2.imwrite(os.path.join(save_path,name),image,[int(cv2.IMWRITE_JPEG_QUALITY), 200])
none
1
2.994003
3
pyglasstools/thermo/__init__.py
muhammadhasyim/pyglasstools
1
6613741
<filename>pyglasstools/thermo/__init__.py R""" Thermodynamic observables. """ from pyglasstools.thermo import _thermo import pyglasstools from pyglasstools import _pyglasstools, comm, rank, size, solvers_list import numpy as np def initialize_global(names,dim): list_obs = {} if any("potentialenergy" in s for s in names): if dim == 2: list_obs['potentialenergy'] = _thermo.GlobalPotentialEnergy2D("potentialenergy", "SCALAR", False) elif dim == 3: list_obs['potentialenergy'] = _thermo.GlobalPotentialEnergy3D("potentialenergy", "SCALAR", False) if any("virialstress" in s for s in names): if any("elastic" in s for s in names) is True: if dim == 2: list_obs['elasticvirialstress'] = _thermo.GlobalElasticVirialStress2D("elasticvirialstress", "2-TENSOR", False) elif dim == 3: list_obs['elasticvirialstress'] = _thermo.GlobalElasticVirialStress3D("elasticvirialstress", "2-TENSOR", False) if any("elastic" in s for s in names) is False: if dim == 2: list_obs['virialstress'] = _thermo.GlobalVirialStress2D("virialstress", "2-TENSOR", False) elif dim == 3: list_obs['virialstress'] = _thermo.GlobalVirialStress3D("virialstress", "2-TENSOR", False) if any("kineticstress" in s for s in names): if dim == 2: list_obs['kineticstress'] = _thermo.GlobalKineticStress2D("kineticstress", "2-TENSOR", True) elif dim == 3: list_obs['kineticstress'] = _thermo.GlobalKineticStress3D("kineticstress", "2-TENSOR", True) if any("borntensor" in s for s in names): if dim == 2: list_obs['borntensor'] = _thermo.GlobalBornTensor2D("borntensor", "4-TENSOR", False) elif dim == 3: list_obs['borntensor'] = _thermo.GlobalBornTensor3D("borntensor", "4-TENSOR", False) return list_obs class calculator(object): global solvers_list def __init__(self): #Initialize system data and pair potential of the system self.manager = _pyglasstools.Manager(); self.thermocalculator = _thermo.ThermoCalculator( pyglasstools.get_sysdata().cppparticledata, pyglasstools.get_potential().cpppairpotential) solvers_list.append(self) def add_observables(self, observables): for name in observables: self.thermocalculator.addObservable(observables[name]) def run(self): self.thermocalculator.compute() def update(self,frame_num): pyglasstools.update_sysdata(frame_num); self.thermocalculator.setSystemData(pyglasstools.get_sysdata().cppparticledata)
<filename>pyglasstools/thermo/__init__.py R""" Thermodynamic observables. """ from pyglasstools.thermo import _thermo import pyglasstools from pyglasstools import _pyglasstools, comm, rank, size, solvers_list import numpy as np def initialize_global(names,dim): list_obs = {} if any("potentialenergy" in s for s in names): if dim == 2: list_obs['potentialenergy'] = _thermo.GlobalPotentialEnergy2D("potentialenergy", "SCALAR", False) elif dim == 3: list_obs['potentialenergy'] = _thermo.GlobalPotentialEnergy3D("potentialenergy", "SCALAR", False) if any("virialstress" in s for s in names): if any("elastic" in s for s in names) is True: if dim == 2: list_obs['elasticvirialstress'] = _thermo.GlobalElasticVirialStress2D("elasticvirialstress", "2-TENSOR", False) elif dim == 3: list_obs['elasticvirialstress'] = _thermo.GlobalElasticVirialStress3D("elasticvirialstress", "2-TENSOR", False) if any("elastic" in s for s in names) is False: if dim == 2: list_obs['virialstress'] = _thermo.GlobalVirialStress2D("virialstress", "2-TENSOR", False) elif dim == 3: list_obs['virialstress'] = _thermo.GlobalVirialStress3D("virialstress", "2-TENSOR", False) if any("kineticstress" in s for s in names): if dim == 2: list_obs['kineticstress'] = _thermo.GlobalKineticStress2D("kineticstress", "2-TENSOR", True) elif dim == 3: list_obs['kineticstress'] = _thermo.GlobalKineticStress3D("kineticstress", "2-TENSOR", True) if any("borntensor" in s for s in names): if dim == 2: list_obs['borntensor'] = _thermo.GlobalBornTensor2D("borntensor", "4-TENSOR", False) elif dim == 3: list_obs['borntensor'] = _thermo.GlobalBornTensor3D("borntensor", "4-TENSOR", False) return list_obs class calculator(object): global solvers_list def __init__(self): #Initialize system data and pair potential of the system self.manager = _pyglasstools.Manager(); self.thermocalculator = _thermo.ThermoCalculator( pyglasstools.get_sysdata().cppparticledata, pyglasstools.get_potential().cpppairpotential) solvers_list.append(self) def add_observables(self, observables): for name in observables: self.thermocalculator.addObservable(observables[name]) def run(self): self.thermocalculator.compute() def update(self,frame_num): pyglasstools.update_sysdata(frame_num); self.thermocalculator.setSystemData(pyglasstools.get_sysdata().cppparticledata)
en
0.749152
Thermodynamic observables. #Initialize system data and pair potential of the system
2.13444
2
Projects/Online Workouts/w3resource/Dictionary/program-13.py
ivenpoker/Python-Projects
1
6613742
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Creates a dictionary from two lists. # # Program Author : <NAME> <<EMAIL>> # # Creation Date : November 28, 2019 # # # ############################################################################################ import random def random_list(low: int, high: int, size: int) -> list: return [random.randint(low, high) for _ in range(size)] def create_dict(listA: list, listB: list) -> dict: new_dict = dict() for (k, v) in zip(listA, listB): new_dict[k] = v return new_dict if __name__ == "__main__": list_A = random_list(low=0, high=10, size=5) list_B = random_list(low=0, high=10, size=5) print(f'List A: {list_A}') print(f'List B: {list_B}') print(f'New dictionary: {create_dict(listA=list_A, listB=list_B)}')
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Creates a dictionary from two lists. # # Program Author : <NAME> <<EMAIL>> # # Creation Date : November 28, 2019 # # # ############################################################################################ import random def random_list(low: int, high: int, size: int) -> list: return [random.randint(low, high) for _ in range(size)] def create_dict(listA: list, listB: list) -> dict: new_dict = dict() for (k, v) in zip(listA, listB): new_dict[k] = v return new_dict if __name__ == "__main__": list_A = random_list(low=0, high=10, size=5) list_B = random_list(low=0, high=10, size=5) print(f'List A: {list_A}') print(f'List B: {list_B}') print(f'New dictionary: {create_dict(listA=list_A, listB=list_B)}')
de
0.602497
#!/usr/bin/env python3 ############################################################################################ # # # Program purpose: Creates a dictionary from two lists. # # Program Author : <NAME> <<EMAIL>> # # Creation Date : November 28, 2019 # # # ############################################################################################
4.372369
4
447/app.py
kaixiang1992/python-flask
0
6613743
<filename>447/app.py from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) @app.route('/') def hello_world(): return render_template('home.html') @app.route('/login/', methods=['GET', 'POST']) def login(): # TODO: GET请求返回登录页面 if request.method == 'GET': return render_template('login.html') else: # TODO: 登录后重定向到个人中心页面 username = request.form.get('username') if username: return redirect(url_for('profile', username=username), 302) else: return redirect(url_for('profile', username='无名氏'), 302) @app.route('/profile/') def profile(): # TODO: 登录后显示登录昵称 if request.args.get('username'): return '登录成功,当前用户:%s' % request.args.get('username') else: # TODO: 未登录重定向登录界面 return redirect(url_for('login'), 302) if __name__ == '__main__': app.run(debug=True, host='192.168.31.176', port=8080)
<filename>447/app.py from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) @app.route('/') def hello_world(): return render_template('home.html') @app.route('/login/', methods=['GET', 'POST']) def login(): # TODO: GET请求返回登录页面 if request.method == 'GET': return render_template('login.html') else: # TODO: 登录后重定向到个人中心页面 username = request.form.get('username') if username: return redirect(url_for('profile', username=username), 302) else: return redirect(url_for('profile', username='无名氏'), 302) @app.route('/profile/') def profile(): # TODO: 登录后显示登录昵称 if request.args.get('username'): return '登录成功,当前用户:%s' % request.args.get('username') else: # TODO: 未登录重定向登录界面 return redirect(url_for('login'), 302) if __name__ == '__main__': app.run(debug=True, host='192.168.31.176', port=8080)
zh
0.990584
# TODO: GET请求返回登录页面 # TODO: 登录后重定向到个人中心页面 # TODO: 登录后显示登录昵称 # TODO: 未登录重定向登录界面
2.923476
3
tracardi_pushover_webhook/model/pushover_payload.py
bartdob/pushOver
0
6613744
from pydantic import BaseModel from tracardi.domain.entity import Entity class PushOverAuth(BaseModel): token: str user: str class PushOverConfiguration(BaseModel): source: Entity message: str
from pydantic import BaseModel from tracardi.domain.entity import Entity class PushOverAuth(BaseModel): token: str user: str class PushOverConfiguration(BaseModel): source: Entity message: str
none
1
2.137351
2
Neural Network/TensorFlow/TensorFlow.py
marcelkotze007/mk007---ML-Python-library
0
6613745
<filename>Neural Network/TensorFlow/TensorFlow.py import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from datetime import datetime as dt N = 500 D = 2 M = 30 K = 3 #first cloud is centred at (0, -2) X1 = np.random.randn(500, 2) + np.array([0, -2]) #second cloud is centred at (2, 2) X2 = np.random.randn(500, 2) + np.array([2, 2]) #Third cloud is centred at (-2, 2) X3 = np.random.randn(500, 2) + np.array([-2, 2]) X = np.vstack((X1,X2,X3)) Y = np.array([0]*N + [1]*N + [2]*N) N1 = len(Y) T = np.zeros((N1, K)) T[np.arange(N1), Y[:].astype(np.int32)] = 1 def init_weights(shape): return tf.Variable(tf.random_normal(shape, stddev = 0.01)) def forward(X, W1, b1, W2, b2): #Z = tf.nn.sigmoid(tf.matmul(X, W1) + b1) #Z = tf.nn.tanh(tf.matmul(X, W1) + b1) Z = tf.nn.relu(tf.matmul(X, W1) + b1) return tf.matmul(Z, W2) + b2 tfX = tf.placeholder(tf.float32, [None, D]) tfY = tf.placeholder(tf.float32, [None, K]) W1 = init_weights([D,M]) b1 = init_weights([M]) W2 = init_weights([M,K]) b2 = init_weights([K]) logits = forward(tfX, W1, b1, W2, b2) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = logits, labels = tfY)) train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) predict_op = tf.argmax(logits, 1) sessions = tf.Session() init = tf.initialize_all_variables() sessions.run(init) dt0 = dt.now() for i in range(10000): sessions.run(train_op, feed_dict={tfX: X, tfY: T}) pred = sessions.run(predict_op, feed_dict={tfX: X, tfY: T}) print(np.mean(Y == pred)) print(dt.now() - dt0)
<filename>Neural Network/TensorFlow/TensorFlow.py import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from datetime import datetime as dt N = 500 D = 2 M = 30 K = 3 #first cloud is centred at (0, -2) X1 = np.random.randn(500, 2) + np.array([0, -2]) #second cloud is centred at (2, 2) X2 = np.random.randn(500, 2) + np.array([2, 2]) #Third cloud is centred at (-2, 2) X3 = np.random.randn(500, 2) + np.array([-2, 2]) X = np.vstack((X1,X2,X3)) Y = np.array([0]*N + [1]*N + [2]*N) N1 = len(Y) T = np.zeros((N1, K)) T[np.arange(N1), Y[:].astype(np.int32)] = 1 def init_weights(shape): return tf.Variable(tf.random_normal(shape, stddev = 0.01)) def forward(X, W1, b1, W2, b2): #Z = tf.nn.sigmoid(tf.matmul(X, W1) + b1) #Z = tf.nn.tanh(tf.matmul(X, W1) + b1) Z = tf.nn.relu(tf.matmul(X, W1) + b1) return tf.matmul(Z, W2) + b2 tfX = tf.placeholder(tf.float32, [None, D]) tfY = tf.placeholder(tf.float32, [None, K]) W1 = init_weights([D,M]) b1 = init_weights([M]) W2 = init_weights([M,K]) b2 = init_weights([K]) logits = forward(tfX, W1, b1, W2, b2) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = logits, labels = tfY)) train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) predict_op = tf.argmax(logits, 1) sessions = tf.Session() init = tf.initialize_all_variables() sessions.run(init) dt0 = dt.now() for i in range(10000): sessions.run(train_op, feed_dict={tfX: X, tfY: T}) pred = sessions.run(predict_op, feed_dict={tfX: X, tfY: T}) print(np.mean(Y == pred)) print(dt.now() - dt0)
en
0.730465
#first cloud is centred at (0, -2) #second cloud is centred at (2, 2) #Third cloud is centred at (-2, 2) #Z = tf.nn.sigmoid(tf.matmul(X, W1) + b1) #Z = tf.nn.tanh(tf.matmul(X, W1) + b1)
3.241101
3
remote_control/management/commands/runremote.py
adrienemery/auv-control-api
0
6613746
import logging from autobahn.asyncio.component import Component, run from django.core.management.base import BaseCommand from django.conf import settings from remote_control.remote_control import RemoteInterface logging.basicConfig(level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **options): url = settings.CROSSBAR_URL realm = settings.CROSSBAR_REALM comp = Component( transports=url, realm=realm, session_factory=RemoteInterface, ) run([comp])
import logging from autobahn.asyncio.component import Component, run from django.core.management.base import BaseCommand from django.conf import settings from remote_control.remote_control import RemoteInterface logging.basicConfig(level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **options): url = settings.CROSSBAR_URL realm = settings.CROSSBAR_REALM comp = Component( transports=url, realm=realm, session_factory=RemoteInterface, ) run([comp])
none
1
1.897983
2
archive/migrations/0001_initial.py
pastpages/savemy.news
19
6613747
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-04 18:02 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Clip', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('url', models.URLField()), ], ), migrations.CreateModel( name='Memento', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp', models.DateTimeField(auto_now_add=True, db_index=True)), ('archive', models.CharField(choices=[('archive.org', 'archive.org')], db_index=True, default='archive.org', max_length=1000)), ('url', models.URLField()), ], ), migrations.AddField( model_name='clip', name='memento', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='archive.Memento'), ), migrations.AddField( model_name='clip', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-04 18:02 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Clip', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('url', models.URLField()), ], ), migrations.CreateModel( name='Memento', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('timestamp', models.DateTimeField(auto_now_add=True, db_index=True)), ('archive', models.CharField(choices=[('archive.org', 'archive.org')], db_index=True, default='archive.org', max_length=1000)), ('url', models.URLField()), ], ), migrations.AddField( model_name='clip', name='memento', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='archive.Memento'), ), migrations.AddField( model_name='clip', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
en
0.751848
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-04 18:02
1.698528
2
src/paql_eval/sketch_refine/partitioning/quad_tree.py
ahmadchatha/Scalable-PaQL-Queries
6
6613748
from src.utils.log import log class QuadTreePartitioning(object): def __init__(self, db, dataset_size, nbits, cid_type_cast, data_table_name, repr_table_name, clust_attrs, data_attrs, max_clust_size, min_n_clusters, epsilon, index_table_name, indexing_attrs, sr_schema, obj_type=None): self.sr_schema = sr_schema self.labels_ = None self.N = dataset_size self.nbits = nbits self.db = db self.data_table_name = data_table_name self.repr_table_name = repr_table_name self.clust_attrs = clust_attrs self.data_attrs = data_attrs self.global_depth = 0 self.max_clust_size = max_clust_size self.min_n_clusters = min_n_clusters self.epsilon = epsilon self.partitioned_cids = set() self.index_table_name = index_table_name self.obj_type = obj_type if self.epsilon is not None: assert self.obj_type is not None self.indexing_attrs = indexing_attrs self.clust_attrs_mask = "".join("1" if attr in self.clust_attrs else "0" for attr in self.indexing_attrs) log("Clust attrs mask: {}".format(self.clust_attrs_mask)) self.partitioning_sql = None # Will be set later, in fit() self.aggregating_sql = None # Will be set later, in fit() self.cid_type_cast = cid_type_cast self.mask_type_cast = "BIT({})".format(self.nbits) def store_representatives(self): """ Store partitioning to data table and representatives to representative table and set labels (partition sizes). """ empirical_epsilon_max = ( "CASE WHEN avg_{attr} > 0 THEN " " (radius / avg_{attr})::float " "ELSE " " NULL " "END AS emp_eps_max_{attr}" ) empirical_epsilon_min = ( "CASE WHEN avg_{attr} > 0 THEN " " (radius / (avg_{attr} - radius))::float " "ELSE " " NULL " "END AS emp_eps_min_{attr}" ) # Store representatives log("Storing representative table '{repr_table}'...".format(repr_table=self.repr_table_name)) self.db.sql_update( "DROP TABLE IF EXISTS {SR}.{repr_table};\n" "CREATE TABLE {SR}.{repr_table} AS " "SELECT cid, {attrs}, cid_size, radius, {emp_eps_max}, {emp_eps_min} " "FROM {SR}.centroids".format( SR=self.sr_schema, repr_table=self.repr_table_name, attrs=",".join("avg_{attr}::float as {attr}".format(attr=attr) for attr in self.data_attrs), emp_eps_max=",".join(empirical_epsilon_max.format(attr=attr) for attr in self.clust_attrs), emp_eps_min=",".join(empirical_epsilon_min.format(attr=attr) for attr in self.clust_attrs), )) log("Representative table stored.") # Create index on representative table log("Creating index on representative table...") self.db.sql_update( "CREATE INDEX ON {SR}.{repr_table} (cid)".format( SR=self.sr_schema, repr_table=self.repr_table_name)) log("Index on representative table created.") def fit(self, only_representatives=False, indexing=False): """ Labels is a list of cluster labels with same lenght as dataset "data". Each label labels[i] is a cluster index indicating which of the n_clusters clusters data[i] belongs to. """ assert self.max_clust_size is not None or self.min_n_clusters is not None averages_sql = ", ".join( "AVG({attr}) AS avg_{attr}".format(attr=attr) for attr in self.data_attrs) mins_sql = ", ".join( "MIN({attr}) AS min_{attr}".format(attr=attr) for attr in self.clust_attrs) maxs_sql = ", ".join( "MAX({attr}) AS max_{attr}".format(attr=attr) for attr in self.clust_attrs) # The basic centroid table does not contain the radius yet centroids_basic = ( "SELECT " " cid, " " COUNT(*) AS cid_size, \n" " {avgs}, \n" " {mins}, \n" " {maxs} \n" "FROM {D} \n" "GROUP BY cid".format( D=self.data_table_name, avgs=averages_sql, mins=mins_sql, maxs=maxs_sql)) if self.obj_type is None: averages_eps_val = None elif self.obj_type.lower() == "maximize": averages_eps_val = "avg_{attr} * {epsilon}" elif self.obj_type.lower() == "minimize": averages_eps_val = "avg_{attr} * ({epsilon} / (1 + {epsilon}))" else: raise Exception("Unknown objective type.") # This is the complete centroid table, containing radius information centroids_complete = ( "SELECT " " cid, \n" " cid_size, \n" " {averages}, \n" " {radius} AS radius \n" " {averages_eps} \n" " {radiuses} \n" "FROM centroids_basic A").format( averages=",".join("avg_{attr}".format(attr=attr) for attr in self.data_attrs), radius="GREATEST({})".format(",".join( "A.avg_{attr} - A.min_{attr}, A.max_{attr} - A.avg_{attr}".format(attr=attr) for attr in self.clust_attrs)), # The followings are used when epsilon is set, to ensure a certain clustering quality averages_eps=("," + ",".join( ("(" + averages_eps_val + ") AS avg_eps_{attr}").format( attr=attr, epsilon=self.epsilon) for attr in self.clust_attrs)) if self.epsilon is not None else "", radiuses=("," + ",".join( "GREATEST(A.avg_{attr} - A.min_{attr}, A.max_{attr} - A.avg_{attr}) AS radius_{attr}".format(attr=attr) for attr in self.clust_attrs)) if self.epsilon is not None else "") self.db.sql_update("DROP MATERIALIZED VIEW IF EXISTS {SR}.centroids".format(SR=self.sr_schema)) # Create the materialized view that stores the current centroids self.db.sql_update( "CREATE MATERIALIZED VIEW {SR}.centroids AS \n" "WITH centroids_basic AS (\n" "{centroids_basic} \n" ") \n" "{centroids_complete} \n" "WITH NO DATA".format( SR=self.sr_schema, centroids_basic=centroids_basic, centroids_complete=centroids_complete)) self.aggregating_sql = "REFRESH MATERIALIZED VIEW {SR}.centroids".format(SR=self.sr_schema) # Define partitioning query: keep partitioning only groups that violate the size and radius conditions neg_size_condition = "A.cid_size > {}".format(self.max_clust_size) # NOTE: This condition is more fine grained that saying MAX(radius_attr) <= MIN(agv_aggr) # and it can cause less partitioning, although it still satisfies the approximation bounds. # So it's preferable. neg_radius_condition = "FALSE" if self.epsilon is None else " OR ".join( "A.radius_{attr} > A.avg_eps_{attr}".format(attr=attr) for attr in self.clust_attrs) self.partitioning_sql = ( "UPDATE {D} D SET cid = (" # NOTE: THIS PARTITION INDEX SCHEME DOESN'T SUPPORT THE INDEX "(0::BIT({diff_bits}) || ({internal_cid})::BIT({k})) | (D.cid::BIT({nbits}) << {k})" ")::{cid_type_cast} \n" "FROM {SR}.centroids A \n" "WHERE ({neg_size_condition} OR {neg_radius_condition}) \n" "AND D.cid = A.cid" "".format( SR=self.sr_schema, D=self.data_table_name, internal_cid=" || ".join( "(CASE" " WHEN D.{attr} IS NULL OR A.avg_{attr} IS NULL OR D.{attr} = A.avg_{attr} THEN " " round(random())::int::bit(1) " " ELSE " " (D.{attr} < A.avg_{attr})::int::bit(1) " "END)".format(attr=attr) for attr in self.clust_attrs), k=len(self.clust_attrs), nbits=self.nbits, diff_bits=self.nbits - len(self.clust_attrs), cid_type_cast=self.cid_type_cast, mask_type_cast=self.mask_type_cast, neg_size_condition=neg_size_condition, neg_radius_condition=neg_radius_condition)) ################################################################################## # RUN PARTITIONING PROCESS ################################################################################## if not only_representatives: keep = True tree_level = 0 while keep: keep = self.partition(tree_level, indexing) > 0 tree_level += 1 else: log("Only computing the representatives...") self.db.sql_update(self.aggregating_sql) log("Representatives computed.") # Store partitioning to data table self.store_representatives() # Clean up self.db.sql_update("DROP MATERIALIZED VIEW {SR}.centroids".format(SR=self.sr_schema)) def partition(self, tree_level, indexing): log("aggregating at tree level {}...".format(tree_level)) self.db.sql_update(self.aggregating_sql) if indexing: level_index_table_name = "{}_l{}".format(self.index_table_name, tree_level) # Store the aggregated meta info in separate tables, one for each tree level log("storing indexing level in table '{}'...".format(level_index_table_name)) self.db.sql_update( "DROP TABLE IF EXISTS {SR}.{level_index_table_name};" "CREATE TABLE {SR}.{level_index_table_name} AS " "SELECT * FROM {SR}.centroids;" "CREATE INDEX ON {SR}.{level_index_table_name} USING btree (cid)".format( SR=self.sr_schema, level_index_table_name=level_index_table_name)) log("analyzing data table...") self.db.sql_update("ANALYZE {D}".format(D=self.data_table_name)) # Partition only clusters whose size is above the threshold log("partitioning at tree level {}...".format(tree_level)) print print self.partitioning_sql.format(tree_level=tree_level) new_cids_n = self.db.sql_update(self.partitioning_sql.format(tree_level=tree_level)) log("new partitions: {}...".format(new_cids_n)) self.db.commit() return new_cids_n
from src.utils.log import log class QuadTreePartitioning(object): def __init__(self, db, dataset_size, nbits, cid_type_cast, data_table_name, repr_table_name, clust_attrs, data_attrs, max_clust_size, min_n_clusters, epsilon, index_table_name, indexing_attrs, sr_schema, obj_type=None): self.sr_schema = sr_schema self.labels_ = None self.N = dataset_size self.nbits = nbits self.db = db self.data_table_name = data_table_name self.repr_table_name = repr_table_name self.clust_attrs = clust_attrs self.data_attrs = data_attrs self.global_depth = 0 self.max_clust_size = max_clust_size self.min_n_clusters = min_n_clusters self.epsilon = epsilon self.partitioned_cids = set() self.index_table_name = index_table_name self.obj_type = obj_type if self.epsilon is not None: assert self.obj_type is not None self.indexing_attrs = indexing_attrs self.clust_attrs_mask = "".join("1" if attr in self.clust_attrs else "0" for attr in self.indexing_attrs) log("Clust attrs mask: {}".format(self.clust_attrs_mask)) self.partitioning_sql = None # Will be set later, in fit() self.aggregating_sql = None # Will be set later, in fit() self.cid_type_cast = cid_type_cast self.mask_type_cast = "BIT({})".format(self.nbits) def store_representatives(self): """ Store partitioning to data table and representatives to representative table and set labels (partition sizes). """ empirical_epsilon_max = ( "CASE WHEN avg_{attr} > 0 THEN " " (radius / avg_{attr})::float " "ELSE " " NULL " "END AS emp_eps_max_{attr}" ) empirical_epsilon_min = ( "CASE WHEN avg_{attr} > 0 THEN " " (radius / (avg_{attr} - radius))::float " "ELSE " " NULL " "END AS emp_eps_min_{attr}" ) # Store representatives log("Storing representative table '{repr_table}'...".format(repr_table=self.repr_table_name)) self.db.sql_update( "DROP TABLE IF EXISTS {SR}.{repr_table};\n" "CREATE TABLE {SR}.{repr_table} AS " "SELECT cid, {attrs}, cid_size, radius, {emp_eps_max}, {emp_eps_min} " "FROM {SR}.centroids".format( SR=self.sr_schema, repr_table=self.repr_table_name, attrs=",".join("avg_{attr}::float as {attr}".format(attr=attr) for attr in self.data_attrs), emp_eps_max=",".join(empirical_epsilon_max.format(attr=attr) for attr in self.clust_attrs), emp_eps_min=",".join(empirical_epsilon_min.format(attr=attr) for attr in self.clust_attrs), )) log("Representative table stored.") # Create index on representative table log("Creating index on representative table...") self.db.sql_update( "CREATE INDEX ON {SR}.{repr_table} (cid)".format( SR=self.sr_schema, repr_table=self.repr_table_name)) log("Index on representative table created.") def fit(self, only_representatives=False, indexing=False): """ Labels is a list of cluster labels with same lenght as dataset "data". Each label labels[i] is a cluster index indicating which of the n_clusters clusters data[i] belongs to. """ assert self.max_clust_size is not None or self.min_n_clusters is not None averages_sql = ", ".join( "AVG({attr}) AS avg_{attr}".format(attr=attr) for attr in self.data_attrs) mins_sql = ", ".join( "MIN({attr}) AS min_{attr}".format(attr=attr) for attr in self.clust_attrs) maxs_sql = ", ".join( "MAX({attr}) AS max_{attr}".format(attr=attr) for attr in self.clust_attrs) # The basic centroid table does not contain the radius yet centroids_basic = ( "SELECT " " cid, " " COUNT(*) AS cid_size, \n" " {avgs}, \n" " {mins}, \n" " {maxs} \n" "FROM {D} \n" "GROUP BY cid".format( D=self.data_table_name, avgs=averages_sql, mins=mins_sql, maxs=maxs_sql)) if self.obj_type is None: averages_eps_val = None elif self.obj_type.lower() == "maximize": averages_eps_val = "avg_{attr} * {epsilon}" elif self.obj_type.lower() == "minimize": averages_eps_val = "avg_{attr} * ({epsilon} / (1 + {epsilon}))" else: raise Exception("Unknown objective type.") # This is the complete centroid table, containing radius information centroids_complete = ( "SELECT " " cid, \n" " cid_size, \n" " {averages}, \n" " {radius} AS radius \n" " {averages_eps} \n" " {radiuses} \n" "FROM centroids_basic A").format( averages=",".join("avg_{attr}".format(attr=attr) for attr in self.data_attrs), radius="GREATEST({})".format(",".join( "A.avg_{attr} - A.min_{attr}, A.max_{attr} - A.avg_{attr}".format(attr=attr) for attr in self.clust_attrs)), # The followings are used when epsilon is set, to ensure a certain clustering quality averages_eps=("," + ",".join( ("(" + averages_eps_val + ") AS avg_eps_{attr}").format( attr=attr, epsilon=self.epsilon) for attr in self.clust_attrs)) if self.epsilon is not None else "", radiuses=("," + ",".join( "GREATEST(A.avg_{attr} - A.min_{attr}, A.max_{attr} - A.avg_{attr}) AS radius_{attr}".format(attr=attr) for attr in self.clust_attrs)) if self.epsilon is not None else "") self.db.sql_update("DROP MATERIALIZED VIEW IF EXISTS {SR}.centroids".format(SR=self.sr_schema)) # Create the materialized view that stores the current centroids self.db.sql_update( "CREATE MATERIALIZED VIEW {SR}.centroids AS \n" "WITH centroids_basic AS (\n" "{centroids_basic} \n" ") \n" "{centroids_complete} \n" "WITH NO DATA".format( SR=self.sr_schema, centroids_basic=centroids_basic, centroids_complete=centroids_complete)) self.aggregating_sql = "REFRESH MATERIALIZED VIEW {SR}.centroids".format(SR=self.sr_schema) # Define partitioning query: keep partitioning only groups that violate the size and radius conditions neg_size_condition = "A.cid_size > {}".format(self.max_clust_size) # NOTE: This condition is more fine grained that saying MAX(radius_attr) <= MIN(agv_aggr) # and it can cause less partitioning, although it still satisfies the approximation bounds. # So it's preferable. neg_radius_condition = "FALSE" if self.epsilon is None else " OR ".join( "A.radius_{attr} > A.avg_eps_{attr}".format(attr=attr) for attr in self.clust_attrs) self.partitioning_sql = ( "UPDATE {D} D SET cid = (" # NOTE: THIS PARTITION INDEX SCHEME DOESN'T SUPPORT THE INDEX "(0::BIT({diff_bits}) || ({internal_cid})::BIT({k})) | (D.cid::BIT({nbits}) << {k})" ")::{cid_type_cast} \n" "FROM {SR}.centroids A \n" "WHERE ({neg_size_condition} OR {neg_radius_condition}) \n" "AND D.cid = A.cid" "".format( SR=self.sr_schema, D=self.data_table_name, internal_cid=" || ".join( "(CASE" " WHEN D.{attr} IS NULL OR A.avg_{attr} IS NULL OR D.{attr} = A.avg_{attr} THEN " " round(random())::int::bit(1) " " ELSE " " (D.{attr} < A.avg_{attr})::int::bit(1) " "END)".format(attr=attr) for attr in self.clust_attrs), k=len(self.clust_attrs), nbits=self.nbits, diff_bits=self.nbits - len(self.clust_attrs), cid_type_cast=self.cid_type_cast, mask_type_cast=self.mask_type_cast, neg_size_condition=neg_size_condition, neg_radius_condition=neg_radius_condition)) ################################################################################## # RUN PARTITIONING PROCESS ################################################################################## if not only_representatives: keep = True tree_level = 0 while keep: keep = self.partition(tree_level, indexing) > 0 tree_level += 1 else: log("Only computing the representatives...") self.db.sql_update(self.aggregating_sql) log("Representatives computed.") # Store partitioning to data table self.store_representatives() # Clean up self.db.sql_update("DROP MATERIALIZED VIEW {SR}.centroids".format(SR=self.sr_schema)) def partition(self, tree_level, indexing): log("aggregating at tree level {}...".format(tree_level)) self.db.sql_update(self.aggregating_sql) if indexing: level_index_table_name = "{}_l{}".format(self.index_table_name, tree_level) # Store the aggregated meta info in separate tables, one for each tree level log("storing indexing level in table '{}'...".format(level_index_table_name)) self.db.sql_update( "DROP TABLE IF EXISTS {SR}.{level_index_table_name};" "CREATE TABLE {SR}.{level_index_table_name} AS " "SELECT * FROM {SR}.centroids;" "CREATE INDEX ON {SR}.{level_index_table_name} USING btree (cid)".format( SR=self.sr_schema, level_index_table_name=level_index_table_name)) log("analyzing data table...") self.db.sql_update("ANALYZE {D}".format(D=self.data_table_name)) # Partition only clusters whose size is above the threshold log("partitioning at tree level {}...".format(tree_level)) print print self.partitioning_sql.format(tree_level=tree_level) new_cids_n = self.db.sql_update(self.partitioning_sql.format(tree_level=tree_level)) log("new partitions: {}...".format(new_cids_n)) self.db.commit() return new_cids_n
en
0.721673
# Will be set later, in fit() # Will be set later, in fit() Store partitioning to data table and representatives to representative table and set labels (partition sizes). # Store representatives # Create index on representative table Labels is a list of cluster labels with same lenght as dataset "data". Each label labels[i] is a cluster index indicating which of the n_clusters clusters data[i] belongs to. # The basic centroid table does not contain the radius yet # This is the complete centroid table, containing radius information # The followings are used when epsilon is set, to ensure a certain clustering quality # Create the materialized view that stores the current centroids # Define partitioning query: keep partitioning only groups that violate the size and radius conditions # NOTE: This condition is more fine grained that saying MAX(radius_attr) <= MIN(agv_aggr) # and it can cause less partitioning, although it still satisfies the approximation bounds. # So it's preferable. # NOTE: THIS PARTITION INDEX SCHEME DOESN'T SUPPORT THE INDEX ################################################################################## # RUN PARTITIONING PROCESS ################################################################################## # Store partitioning to data table # Clean up # Store the aggregated meta info in separate tables, one for each tree level # Partition only clusters whose size is above the threshold
2.405413
2
components/matchers.py
vdvchen/SGMNet
61
6613749
import torch import numpy as np import os from collections import OrderedDict,namedtuple import sys ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, ROOT_DIR) from sgmnet import matcher as SGM_Model from superglue import matcher as SG_Model from utils import evaluation_utils class GNN_Matcher(object): def __init__(self,config,model_name): assert model_name=='SGM' or model_name=='SG' config=namedtuple('config',config.keys())(*config.values()) self.p_th=config.p_th self.model = SGM_Model(config) if model_name=='SGM' else SG_Model(config) self.model.cuda(),self.model.eval() checkpoint = torch.load(os.path.join(config.model_dir, 'model_best.pth')) #for ddp model if list(checkpoint['state_dict'].items())[0][0].split('.')[0]=='module': new_stat_dict=OrderedDict() for key,value in checkpoint['state_dict'].items(): new_stat_dict[key[7:]]=value checkpoint['state_dict']=new_stat_dict self.model.load_state_dict(checkpoint['state_dict']) def run(self,test_data): norm_x1,norm_x2=evaluation_utils.normalize_size(test_data['x1'][:,:2],test_data['size1']),\ evaluation_utils.normalize_size(test_data['x2'][:,:2],test_data['size2']) x1,x2=np.concatenate([norm_x1,test_data['x1'][:,2,np.newaxis]],axis=-1),np.concatenate([norm_x2,test_data['x2'][:,2,np.newaxis]],axis=-1) feed_data={'x1':torch.from_numpy(x1[np.newaxis]).cuda().float(), 'x2':torch.from_numpy(x2[np.newaxis]).cuda().float(), 'desc1':torch.from_numpy(test_data['desc1'][np.newaxis]).cuda().float(), 'desc2':torch.from_numpy(test_data['desc2'][np.newaxis]).cuda().float()} with torch.no_grad(): res=self.model(feed_data,test_mode=True) p=res['p'] index1,index2=self.match_p(p[0,:-1,:-1]) corr1,corr2=test_data['x1'][:,:2][index1.cpu()],test_data['x2'][:,:2][index2.cpu()] if len(corr1.shape)==1: corr1,corr2=corr1[np.newaxis],corr2[np.newaxis] return corr1,corr2 def match_p(self,p):#p N*M score,index=torch.topk(p,k=1,dim=-1) _,index2=torch.topk(p,k=1,dim=-2) mask_th,index,index2=score[:,0]>self.p_th,index[:,0],index2.squeeze(0) mask_mc=index2[index] == torch.arange(len(p)).cuda() mask=mask_th&mask_mc index1,index2=torch.nonzero(mask).squeeze(1),index[mask] return index1,index2 class NN_Matcher(object): def __init__(self,config): config=namedtuple('config',config.keys())(*config.values()) self.mutual_check=config.mutual_check self.ratio_th=config.ratio_th def run(self,test_data): desc1,desc2,x1,x2=test_data['desc1'],test_data['desc2'],test_data['x1'],test_data['x2'] desc_mat=np.sqrt(abs((desc1**2).sum(-1)[:,np.newaxis]+(desc2**2).sum(-1)[np.newaxis]-2*desc1@desc2.T)) nn_index=np.argpartition(desc_mat,kth=(1,2),axis=-1) dis_value12=np.take_along_axis(desc_mat,nn_index, axis=-1) ratio_score=dis_value12[:,0]/dis_value12[:,1] nn_index1=nn_index[:,0] nn_index2=np.argmin(desc_mat,axis=0) mask_ratio,mask_mutual=ratio_score<self.ratio_th,np.arange(len(x1))==nn_index2[nn_index1] corr1,corr2=x1[:,:2],x2[:,:2][nn_index1] if self.mutual_check: mask=mask_ratio&mask_mutual else: mask=mask_ratio corr1,corr2=corr1[mask],corr2[mask] return corr1,corr2
import torch import numpy as np import os from collections import OrderedDict,namedtuple import sys ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, ROOT_DIR) from sgmnet import matcher as SGM_Model from superglue import matcher as SG_Model from utils import evaluation_utils class GNN_Matcher(object): def __init__(self,config,model_name): assert model_name=='SGM' or model_name=='SG' config=namedtuple('config',config.keys())(*config.values()) self.p_th=config.p_th self.model = SGM_Model(config) if model_name=='SGM' else SG_Model(config) self.model.cuda(),self.model.eval() checkpoint = torch.load(os.path.join(config.model_dir, 'model_best.pth')) #for ddp model if list(checkpoint['state_dict'].items())[0][0].split('.')[0]=='module': new_stat_dict=OrderedDict() for key,value in checkpoint['state_dict'].items(): new_stat_dict[key[7:]]=value checkpoint['state_dict']=new_stat_dict self.model.load_state_dict(checkpoint['state_dict']) def run(self,test_data): norm_x1,norm_x2=evaluation_utils.normalize_size(test_data['x1'][:,:2],test_data['size1']),\ evaluation_utils.normalize_size(test_data['x2'][:,:2],test_data['size2']) x1,x2=np.concatenate([norm_x1,test_data['x1'][:,2,np.newaxis]],axis=-1),np.concatenate([norm_x2,test_data['x2'][:,2,np.newaxis]],axis=-1) feed_data={'x1':torch.from_numpy(x1[np.newaxis]).cuda().float(), 'x2':torch.from_numpy(x2[np.newaxis]).cuda().float(), 'desc1':torch.from_numpy(test_data['desc1'][np.newaxis]).cuda().float(), 'desc2':torch.from_numpy(test_data['desc2'][np.newaxis]).cuda().float()} with torch.no_grad(): res=self.model(feed_data,test_mode=True) p=res['p'] index1,index2=self.match_p(p[0,:-1,:-1]) corr1,corr2=test_data['x1'][:,:2][index1.cpu()],test_data['x2'][:,:2][index2.cpu()] if len(corr1.shape)==1: corr1,corr2=corr1[np.newaxis],corr2[np.newaxis] return corr1,corr2 def match_p(self,p):#p N*M score,index=torch.topk(p,k=1,dim=-1) _,index2=torch.topk(p,k=1,dim=-2) mask_th,index,index2=score[:,0]>self.p_th,index[:,0],index2.squeeze(0) mask_mc=index2[index] == torch.arange(len(p)).cuda() mask=mask_th&mask_mc index1,index2=torch.nonzero(mask).squeeze(1),index[mask] return index1,index2 class NN_Matcher(object): def __init__(self,config): config=namedtuple('config',config.keys())(*config.values()) self.mutual_check=config.mutual_check self.ratio_th=config.ratio_th def run(self,test_data): desc1,desc2,x1,x2=test_data['desc1'],test_data['desc2'],test_data['x1'],test_data['x2'] desc_mat=np.sqrt(abs((desc1**2).sum(-1)[:,np.newaxis]+(desc2**2).sum(-1)[np.newaxis]-2*desc1@desc2.T)) nn_index=np.argpartition(desc_mat,kth=(1,2),axis=-1) dis_value12=np.take_along_axis(desc_mat,nn_index, axis=-1) ratio_score=dis_value12[:,0]/dis_value12[:,1] nn_index1=nn_index[:,0] nn_index2=np.argmin(desc_mat,axis=0) mask_ratio,mask_mutual=ratio_score<self.ratio_th,np.arange(len(x1))==nn_index2[nn_index1] corr1,corr2=x1[:,:2],x2[:,:2][nn_index1] if self.mutual_check: mask=mask_ratio&mask_mutual else: mask=mask_ratio corr1,corr2=corr1[mask],corr2[mask] return corr1,corr2
en
0.204195
#for ddp model #p N*M
1.946727
2
evolocity/preprocessing/__init__.py
samsledje/evolocity
25
6613750
from .featurize_seqs import featurize_fasta, featurize_seqs, get_model from .neighbors import pca, neighbors, remove_duplicate_nodes
from .featurize_seqs import featurize_fasta, featurize_seqs, get_model from .neighbors import pca, neighbors, remove_duplicate_nodes
none
1
1.159764
1