content
stringlengths
5
1.05M
# -*- coding: future_fstrings -*- from fabric.context_managers import cd from fabric.operations import run from fabric.state import env def __task_clean_releases(): with cd(env.release_path): releases = env.get("keep_releases") or 5 releases_count = int(releases) if str(releases).isdigit() else 5 run(f'rm -rf `ls -t | tail -n +{releases_count + 1}`')
import re import random import aiohttp from fuzzywuzzy import fuzz import logging from . import config from skybeard.beards import BeardChatHandler logger = logging.getLogger(__name__) async def get_key(): return BeardChatHandler.key BOT_JSON = None async def get_me(): global BOT_JSON if not BOT_JSON: async with aiohttp.ClientSession() as session: async with session.get( "https://api.telegram.org/bot{}/getMe".format( BeardChatHandler.key)) as resp: BOT_JSON = (await resp.json())['result'] return BOT_JSON async def passes_partial_ratio(s1, s2, min_partial_ratio=75.0): """Returns True if lowercase s1 and s2 matches enough.""" return fuzz.partial_ratio( s1.lower(), s2.lower() ) > min_partial_ratio async def is_being_thanked(bot, msg): me = await get_me() try: thank_you_matches = ( re.match( r"\b{}\b".format(x).lower(), msg['text'].lower()) for x in config.thank_yous) partial_ratio_cut = 75.0 name_or_username_matches = [ await passes_partial_ratio(me['first_name'], msg['text']), await passes_partial_ratio(me['username'], msg['text']), ] if any(thank_you_matches) and any(name_or_username_matches): return True except KeyError: pass class ThankYouBeard(BeardChatHandler): __userhelp__ = """A simple thank you beard. Replies when thanked.""" __commands__ = [ (is_being_thanked, 'say_thank_you', None) ] async def say_thank_you(self, msg): await self.sender.sendMessage( random.choice(config.your_welcomes).format(name=msg['from']['first_name']))
# coding: utf-8 """A tornado based Jupyter lab server.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. # TODO: import base server app import os from jupyter_core.paths import jupyter_config_path, jupyter_path from notebook.notebookapp import NotebookApp from traitlets import List, Unicode, default from traitlets.config.manager import BaseJSONConfigManager def get_labextensions(parent=None): """Get the list of enabled lab extensions""" extensions = [] config_dirs = [os.path.join(p, 'labconfig') for p in jupyter_config_path()] for config_dir in config_dirs: cm = BaseJSONConfigManager(parent=parent, config_dir=config_dir) data = cm.get("jupyterlab_config") labextensions = ( data.setdefault("LabApp", {}) .setdefault("labextensions", {}) ) for name, enabled in labextensions.items(): if enabled: extensions.append(name) return extensions class LabApp(NotebookApp): description = """ JupyterLab - An extensible computational environment for Jupyter. This launches a Tornado based HTML Server that serves up an HTML5/Javascript JupyterLab client. """ examples = """ jupyter lab # start JupyterLab jupyter lab --certfile=mycert.pem # use SSL/TLS certificate """ subcommands = dict() default_url = Unicode('/lab', config=True, help="The default URL to redirect to from `/`" ) extra_labextensions_path = List(Unicode(), config=True, help="""extra paths to look for JupyterLab extensions""" ) labextensions = List(Unicode()) @default('labextensions') def _labextensions_default(self): return get_labextensions(parent=self) @property def labextensions_path(self): """The path to look for JupyterLab extensions""" return self.extra_labextensions_path + jupyter_path('labextensions') def init_webapp(self): super(LabApp, self).init_webapp() self.web_app.labextensions = self.labextensions #----------------------------------------------------------------------------- # Main entry point #----------------------------------------------------------------------------- main = launch_new_instance = LabApp.launch_instance
# Copyright 2021 The Cirq Developers # # 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 # # https://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 pytest import numpy as np import sympy import cirq @pytest.mark.parametrize( 'gate, num_copies, qubits', [ (cirq.testing.SingleQubitGate(), 2, cirq.LineQubit.range(2)), (cirq.X**0.5, 4, cirq.LineQubit.range(4)), ], ) def test_parallel_gate_operation_init(gate, num_copies, qubits): v = cirq.ParallelGate(gate, num_copies) assert v.sub_gate == gate assert v.num_copies == num_copies assert v.on(*qubits).qubits == tuple(qubits) @pytest.mark.parametrize( 'gate, num_copies, qubits, error_msg', [ (cirq.testing.SingleQubitGate(), 3, cirq.LineQubit.range(2), "Wrong number of qubits"), ( cirq.testing.SingleQubitGate(), 0, cirq.LineQubit.range(4), "gate must be applied at least once", ), ( cirq.testing.SingleQubitGate(), 2, [cirq.NamedQubit("a"), cirq.NamedQubit("a")], "Duplicate", ), (cirq.testing.TwoQubitGate(), 2, cirq.LineQubit.range(4), "must be a single qubit gate"), ], ) def test_invalid_parallel_gate_operation(gate, num_copies, qubits, error_msg): with pytest.raises(ValueError, match=error_msg): cirq.ParallelGate(gate, num_copies)(*qubits) @pytest.mark.parametrize( 'gate, num_copies, qubits', [(cirq.X, 2, cirq.LineQubit.range(2)), (cirq.H**0.5, 4, cirq.LineQubit.range(4))], ) def test_decompose(gate, num_copies, qubits): g = cirq.ParallelGate(gate, num_copies) step = gate.num_qubits() qubit_lists = [qubits[i * step : (i + 1) * step] for i in range(num_copies)] assert set(cirq.decompose_once(g(*qubits))) == set(gate.on_each(qubit_lists)) def test_decompose_raises(): g = cirq.ParallelGate(cirq.X, 2) qubits = cirq.LineQubit.range(4) with pytest.raises(ValueError, match=r'len\(qubits\)=4 should be 2'): cirq.decompose_once_with_qubits(g, qubits) def test_with_num_copies(): g = cirq.testing.SingleQubitGate() pg = cirq.ParallelGate(g, 3) assert pg.with_num_copies(5) == cirq.ParallelGate(g, 5) def test_extrapolate(): # If the gate isn't extrapolatable, you get a type error. g = cirq.ParallelGate(cirq.testing.SingleQubitGate(), 2) with pytest.raises(TypeError): _ = g**0.5 # If the gate is extrapolatable, the effect is applied on the underlying gate. g = cirq.ParallelGate(cirq.Y, 2) assert g**0.5 == cirq.ParallelGate(cirq.Y**0.5, 2) assert cirq.inverse(g) == g**-1 == cirq.ParallelGate(cirq.Y**-1, 2) @pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once]) def test_parameterizable_gates(resolve_fn): r = cirq.ParamResolver({'a': 0.5}) g1 = cirq.ParallelGate(cirq.Z ** sympy.Symbol('a'), 2) assert cirq.is_parameterized(g1) g2 = resolve_fn(g1, r) assert not cirq.is_parameterized(g2) @pytest.mark.parametrize('gate', [cirq.X ** sympy.Symbol("a"), cirq.testing.SingleQubitGate()]) def test_no_unitary(gate): g = cirq.ParallelGate(gate, 2) assert not cirq.has_unitary(g) assert cirq.unitary(g, None) is None @pytest.mark.parametrize( 'gate, num_copies, qubits', [ (cirq.X**0.5, 2, cirq.LineQubit.range(2)), (cirq.MatrixGate(cirq.unitary(cirq.H**0.25)), 6, cirq.LineQubit.range(6)), ], ) def test_unitary(gate, num_copies, qubits): g = cirq.ParallelGate(gate, num_copies) step = gate.num_qubits() qubit_lists = [qubits[i * step : (i + 1) * step] for i in range(num_copies)] np.testing.assert_allclose( cirq.unitary(g), cirq.unitary(cirq.Circuit(gate.on_each(qubit_lists))), atol=1e-6 ) def test_not_implemented_diagram(): q = cirq.LineQubit.range(2) g = cirq.testing.SingleQubitGate() c = cirq.Circuit() c.append(cirq.ParallelGate(g, 2)(*q)) assert 'cirq.testing.gate_features.SingleQubitGate ' in str(c) def test_repr(): assert repr(cirq.ParallelGate(cirq.X, 2)) == 'cirq.ParallelGate(sub_gate=cirq.X, num_copies=2)' def test_str(): assert str(cirq.ParallelGate(cirq.X**0.5, 10)) == 'X**0.5 x 10' def test_equivalent_circuit(): qreg = cirq.LineQubit.range(4) oldc = cirq.Circuit() newc = cirq.Circuit() single_qubit_gates = [cirq.X ** (1 / 2), cirq.Y ** (1 / 3), cirq.Z**-1] for gate in single_qubit_gates: for qubit in qreg: oldc.append(gate.on(qubit)) newc.append(cirq.ParallelGate(gate, 4)(*qreg)) cirq.testing.assert_has_diagram(newc, oldc.to_text_diagram()) cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(oldc, newc, atol=1e-6) @pytest.mark.parametrize('gate, num_copies', [(cirq.X, 1), (cirq.Y, 2), (cirq.Z, 3), (cirq.H, 4)]) def test_parallel_gate_operation_is_consistent(gate, num_copies): cirq.testing.assert_implements_consistent_protocols(cirq.ParallelGate(gate, num_copies)) def test_trace_distance(): s = cirq.X**0.25 two_g = cirq.ParallelGate(s, 2) three_g = cirq.ParallelGate(s, 3) four_g = cirq.ParallelGate(s, 4) assert cirq.approx_eq(cirq.trace_distance_bound(two_g), np.sin(np.pi / 4)) assert cirq.approx_eq(cirq.trace_distance_bound(three_g), np.sin(3 * np.pi / 8)) assert cirq.approx_eq(cirq.trace_distance_bound(four_g), 1.0) spg = cirq.ParallelGate(cirq.X ** sympy.Symbol('a'), 4) assert cirq.approx_eq(cirq.trace_distance_bound(spg), 1.0) @pytest.mark.parametrize('gate, num_copies', [(cirq.X, 1), (cirq.Y, 2), (cirq.Z, 3), (cirq.H, 4)]) def test_parallel_gate_op(gate, num_copies): qubits = cirq.LineQubit.range(num_copies * gate.num_qubits()) assert cirq.parallel_gate_op(gate, *qubits) == cirq.ParallelGate(gate, num_copies).on(*qubits)
# project/server/models.py import datetime from project.server import app, db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) email = db.Column(db.String(255), unique=True, nullable=False) password = db.Column(db.String(255), nullable=False) registered_on = db.Column(db.DateTime, nullable=False) admin = db.Column(db.Boolean, nullable=False, default=False) def __init__(self, email, password, admin=False): self.email = email self.password = bcrypt.generate_password_hash( password, app.config.get('BCRYPT_LOG_ROUNDS') ) self.registered_on = datetime.datetime.now() self.admin = admin def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id def __repr__(self): return '<User {0}>'.format(self.email) class Transaction(db.Model): __tablename__ = "transactions" id = db.Column(db.Integer, primary_key=True) method = db.Column(db.String(10), nullable=False) uri = db.Column(db.String(255), nullable=False) status = db.Column(db.Integer) ctype = db.Column(db.String(255)) verificationStatusId = db.Column(db.Integer) depth = db.Column(db.Integer, nullable=False) parentId = db.Column(db.Integer, nullable=False) def __init__(self, id, method, uri, status, ctype, vsi, depth, parentId): self.id = id self.method = method self.uri = uri self.status = status self.ctype = ctype self.verificationStatusId = vsi self.depth = depth self.parentId = parentId class Alias(db.Model): __tablename__ = "aliases" id = db.Column(db.Integer, primary_key=True, nullable=False) transactionId = db.Column(db.Integer, nullable=False) uri = db.Column(db.String(255), nullable=False) def __init__(self, tid, uri): self.transactionId = tid self.uri = uri class Link(db.Model): __tablename__ = "link" id = db.Column(db.Integer, primary_key=True, nullable=False) fromUri = db.Column(db.String(255), nullable=False) toUri = db.Column(db.String(255), nullable=False) good = db.Column(db.Boolean, nullable=False) processed = db.Column(db.Boolean, nullable=False) requestId = db.Column(db.Integer) responseId = db.Column(db.Integer, nullable=False) def __init__(self, id, fromUri, toUri, good, processed, requestId, responseId): self.id = id self.toUri = toUri self.fromUri = fromUri self.good = good self.processed = processed self.requestId = requestId self.responseId = responseId class Defect(db.Model): __tablename__ = "defect" findingId = db.Column(db.Integer, primary_key=True, nullable=False) type = db.Column(db.String(255), nullable=False) description = db.Column(db.String) evidence = db.Column(db.String, nullable=False) severity = db.Column(db.Numeric, nullable=False) responseId = db.Column(db.Integer, nullable=False) uri = db.Column(db.String(255), nullable=False) def __init__(self, findingId, type, description, evidence, severity, responseId, uri): self.findingId = findingId self.type = type self.description = description self.evidence = evidence self.severity = severity self.responseId = responseId self.uri = uri
from django.contrib import admin from .models import Patient from .forms import PatientAdminForm # Register your models here. class PatientAdmin(admin.ModelAdmin): form = PatientAdminForm list_display = ['user','created', 'last_updated', 'cart_code'] readonly_fields = ['created', 'last_updated'] admin.site.register(Patient, PatientAdmin)
import numpy as np # make any plots not use display from matplotlib import use use('Agg') import matplotlib.pyplot as plt # used for ECDF import statsmodels.api as sm from selection.algorithms.lasso import instance from selection.algorithms.forward_step import forward_step, info_crit_stop, data_carving_IC from selection.tests.decorators import set_sampling_params_iftrue @set_sampling_params_iftrue(True) def test_FS(k=10, ndraw=5000, burnin=5000, nsim=None): n, p = 100, 200 X = np.random.standard_normal((n,p)) + 0.4 * np.random.standard_normal(n)[:,None] X /= (X.std(0)[None,:] * np.sqrt(n)) Y = np.random.standard_normal(100) * 0.5 FS = forward_step(X, Y, covariance=0.5**2 * np.identity(n)) for i in range(k): FS.next(compute_pval=True) print 'first %s variables selected' % k, FS.variables print 'pivots for 3rd selected model knowing that we performed %d steps of forward stepwise' % k print FS.model_pivots(3) print FS.model_pivots(3, saturated=False, which_var=[FS.variables[2]], burnin=burnin, ndraw=ndraw) print FS.model_quadratic(3) @set_sampling_params_iftrue(True) def test_FS_unknown(k=10, ndraw=5000, burnin=5000, nsim=None): n, p = 100, 200 X = np.random.standard_normal((n,p)) + 0.4 * np.random.standard_normal(n)[:,None] X /= (X.std(0)[None,:] * np.sqrt(n)) Y = np.random.standard_normal(100) * 0.5 FS = forward_step(X, Y) for i in range(k): FS.next() print 'first %s variables selected' % k, FS.variables print 'pivots for last variable of 3rd selected model knowing that we performed %d steps of forward stepwise' % k print FS.model_pivots(3, saturated=False, which_var=[FS.variables[2]], burnin=burnin, ndraw=ndraw) @set_sampling_params_iftrue(True) def test_subset(k=10, ndraw=5000, burnin=5000, nsim=None): n, p = 100, 200 X = np.random.standard_normal((n,p)) + 0.4 * np.random.standard_normal(n)[:,None] X /= (X.std(0)[None,:] * np.sqrt(n)) Y = np.random.standard_normal(100) * 0.5 subset = np.ones(n, np.bool) subset[-10:] = 0 FS = forward_step(X, Y, subset=subset, covariance=0.5**2 * np.identity(n)) for i in range(k): FS.next() print 'first %s variables selected' % k, FS.variables print 'pivots for last variable of 3rd selected model knowing that we performed %d steps of forward stepwise' % k print FS.model_pivots(3, saturated=True) print FS.model_pivots(3, saturated=False, which_var=[FS.variables[2]], burnin=burnin, ndraw=ndraw) FS = forward_step(X, Y, subset=subset) for i in range(k): FS.next() print FS.model_pivots(3, saturated=False, which_var=[FS.variables[2]], burnin=burnin, ndraw=ndraw) @set_sampling_params_iftrue(True) def test_BIC(do_sample=True, ndraw=8000, burnin=2000, nsim=None, force=False): X, Y, beta, active, sigma = instance() n, p = X.shape FS = info_crit_stop(Y, X, sigma, cost=np.log(n)) final_model = len(FS.variables) active = set(list(active)) if active.issubset(FS.variables) or force: which_var = [v for v in FS.variables if v not in active] if do_sample: return [pval[-1] for pval in FS.model_pivots(final_model, saturated=False, burnin=burnin, ndraw=ndraw, which_var=which_var)] else: saturated_pivots = FS.model_pivots(final_model, which_var=which_var) return [pval[-1] for pval in saturated_pivots] return [] def simulate_null(saturated=True, ndraw=8000, burnin=2000): n, p = 100, 40 X = np.random.standard_normal((n,p)) + 0.4 * np.random.standard_normal(n)[:,None] X /= (X.std(0)[None,:] * np.sqrt(n)) Y = np.random.standard_normal(100) * 0.5 FS = forward_step(X, Y, covariance=0.5**2 * np.identity(n)) for i in range(5): FS.next() return [p[-1] for p in FS.model_pivots(3, saturated=saturated, ndraw=ndraw, burnin=burnin)] @set_sampling_params_iftrue(True) def test_ecdf(nsim=1000, BIC=False, saturated=True, burnin=2000, ndraw=8000): P = [] for _ in range(nsim): if not BIC: P.extend(simulate_null(saturated=saturated, ndraw=ndraw, burnin=burnin)) else: P.extend(test_BIC(do_sample=True, ndraw=ndraw, burnin=burnin)) P = np.array(P) ecdf = sm.distributions.ECDF(P) plt.clf() plt.plot(ecdf.x, ecdf.y, linewidth=4, color='black') plt.show() @set_sampling_params_iftrue(True) def test_data_carving_IC(nsim=500, n=100, p=200, s=7, sigma=5, rho=0.3, snr=7., split_frac=0.9, ndraw=5000, burnin=1000, df=np.inf, coverage=0.90, compute_intervals=False): counter = 0 while counter < nsim: counter += 1 X, y, beta, active, sigma = instance(n=n, p=p, s=s, sigma=sigma, rho=rho, snr=snr, df=df) mu = np.dot(X, beta) splitn = int(n*split_frac) indices = np.arange(n) np.random.shuffle(indices) stage_one = indices[:splitn] FS = info_crit_stop(y, X, sigma, cost=np.log(n), subset=stage_one) if set(range(s)).issubset(FS.active): results, FS = data_carving_IC(y, X, sigma, stage_one=stage_one, splitting=True, ndraw=ndraw, burnin=burnin, coverage=coverage, compute_intervals=compute_intervals, cost=np.log(n)) carve = [r[1] for r in results] split = [r[3] for r in results] Xa = X[:,FS.variables[:-1]] truth = np.dot(np.linalg.pinv(Xa), mu) split_coverage = [] carve_coverage = [] for result, t in zip(results, truth): _, _, ci, _, si = result carve_coverage.append((ci[0] < t) * (t < ci[1])) split_coverage.append((si[0] < t) * (t < si[1])) return ([carve[j] for j, i in enumerate(FS.active) if i >= s], [split[j] for j, i in enumerate(FS.active) if i >= s], [carve[j] for j, i in enumerate(FS.active) if i < s], [split[j] for j, i in enumerate(FS.active) if i < s], counter, carve_coverage, split_coverage) @set_sampling_params_iftrue(True) def test_full_pvals(n=100, p=40, rho=0.3, snr=4, ndraw=8000, burnin=2000, nsim=None): X, y, beta, active, sigma = instance(n=n, p=p, snr=snr, rho=rho) FS = forward_step(X, y, covariance=sigma**2 * np.identity(n)) from scipy.stats import norm as ndist pval = [] completed_yet = False for i in range(min(n, p)): FS.next() var_select, pval_select = FS.model_pivots(i+1, alternative='twosided', which_var=[FS.variables[-1]], saturated=False, burnin=burnin, ndraw=ndraw)[0] pval_saturated = FS.model_pivots(i+1, alternative='twosided', which_var=[FS.variables[-1]], saturated=True)[0][1] # now, nominal ones LSfunc = np.linalg.pinv(FS.X[:,FS.variables]) Z = np.dot(LSfunc[-1], FS.Y) / (np.linalg.norm(LSfunc[-1]) * sigma) pval_nominal = 2 * ndist.sf(np.fabs(Z)) pval.append((var_select, pval_select, pval_saturated, pval_nominal)) if set(active).issubset(np.array(pval)[:,0]) and not completed_yet: completed_yet = True completion_index = i + 1 return X, y, beta, active, sigma, np.array(pval), completion_index @set_sampling_params_iftrue(False) def test_mcmc_tests(n=100, p=40, s=4, rho=0.3, snr=5, ndraw=None, burnin=2000, nsim=None, nstep=200, method='serial'): X, y, beta, active, sigma = instance(n=n, p=p, snr=snr, rho=rho, s=s) FS = forward_step(X, y, covariance=sigma**2 * np.identity(n)) extra_steps = 4 null_rank, alt_rank = None, None for i in range(min(n, p)): FS.next() if extra_steps <= 0: null_rank = FS.mcmc_test(i+1, variable=FS.variables[i-2], nstep=nstep, burnin=burnin, method="serial") alt_rank = FS.mcmc_test(i+1, variable=FS.variables[0], burnin=burnin, nstep=nstep, method="parallel") break if set(active).issubset(FS.variables): extra_steps -= 1 return null_rank, alt_rank @set_sampling_params_iftrue(False) def test_independence_null_mcmc(n=100, p=40, s=4, rho=0.5, snr=5, ndraw=None, burnin=2000, nsim=None, nstep=200, method='serial'): X, y, beta, active, sigma = instance(n=n, p=p, snr=snr, rho=rho, s=s) FS = forward_step(X, y, covariance=sigma**2 * np.identity(n)) extra_steps = 4 completed = False null_ranks = [] for i in range(min(n, p)): FS.next() if completed and extra_steps > 0: null_rank = FS.mcmc_test(i+1, variable=FS.variables[-1], nstep=nstep, burnin=burnin, method="serial") null_ranks.append(int(null_rank)) if extra_steps <= 0: break if set(active).issubset(FS.variables): extra_steps -= 1 completed = True return tuple(null_ranks)
import csv import os import tempfile import pytest from topo_processor.metadata.csv_loader.csv_loader import read_csv def test_read_csv() -> None: metadata_path = os.path.join(os.getcwd(), "test_data", "historical_aerial_photos_metadata.csv") metadata = read_csv(metadata_path, "raw_filename", "sufi") assert len(metadata) == 5 assert list(metadata.keys()) == ["WRONG_PHOTO_TYPE", "MULTIPLE_ASSET", "CONTROL", "WRONG_SURVEY", "CONTROL_2"] def test_error_on_wrong_file_name() -> None: metadata_path = "./data/historical_aerial_photos_metadata.csv" with pytest.raises(Exception, match=r"^Cannot find "): read_csv(metadata_path, "raw_filename", "sufi") def test_error_on_duplicate_file() -> None: temp_file = tempfile.NamedTemporaryFile() header = [ "WKT", "sufi", "survey", "run", "photo_no", "alternate_survey_name", "camera", "camera_sequence_no", "nominal_focal_length", "altitude", "scale", "photocentre_lat", "photocentre_lon", "date", "film", "film_sequence_no", "photo_type", "format", "source", "physical_film_condition", "image_anomalies", "scanned", "raw_filename", "released_filename", "when_scanned", "photo_version", ] row = [ "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "WRONG_PHOTO_TYPE", "", "", "", ] with open(temp_file.name, "a", encoding="utf-8") as csv_file: writer = csv.writer(csv_file) writer.writerow(header) writer.writerow(row) writer.writerow(row) with pytest.raises(Exception, match=r'Duplicate "WRONG_PHOTO_TYPE" found in "' + temp_file.name + '"'): read_csv(temp_file.name, "raw_filename", "sufi") def test_read_csv_column_filter() -> None: metadata_path = os.path.join(os.getcwd(), "test_data", "historical_survey_footprint_metadata.csv") metadata = read_csv(metadata_path, "SURVEY", columns=["NAME"]) assert len(metadata) == 4 assert list(metadata.keys()) == ["SURVEY_1", "SURVEY_3", "SURVEY_2", "SURVEY_NO_NAME"] assert list(metadata.values()) == [{"NAME": "TE KUITI 1"}, {"NAME": "AUCKLAND 1"}, {"NAME": "WELLINGTON 2"}, {"NAME": ""}]
import pytest from flask import g, session from app.db import get_db @pytest.mark.parametrize(('username', 'password', 'message'), ( ('', '', b'Incorrect username.'), ('test', '', b'Incorrect password.'), ('test', 'test', b'Ok.'), )) def test_login(client, username, password, message): response = client.post( '/read', json={'username': username, 'password': password}, headers={'content-type': 'application/json'} ) # Couldnt handle the status but Errors are handeled assert response.status_code == 200 json_data = response.get_json() if json_data: assert json_data["data"]["accounts"][0]["iban"] == "ES232100123303030000" else: assert message in response.data
from PyQt5.QtSql import QSqlDatabase, QSqlQuery import pymysql from datetime import date import time class LinkDatabaseInMysql: def __init__(self, username, pass_word): self.connection = pymysql.connect( host='localhost', port=3306, user=username, password=password, db='journaldatabase', charset='utf8mb4' ) self.cur = self.connection.cursor() print('登录成功') # 查询语句返回结果 def select_sql(self, sql): self.cur.execute(sql) result = self.cur.fetchall() print(result) return result # 更新、删除、插入时的sql语句调用 def update_sql(self, sql: str): try: self.cur.execute(sql) self.connection.commit() print(sql.split(' ')[0] + '语句执行成功') return True except pymysql.Error as e: print(sql.split(' ')[0] + '语句执行失败') print(e.args[0], e.args[1]) self.connection.rollback() return False def update_sql_with_data(self, sql: str, data): try: self.cur.execute(sql, data) self.connection.commit() print(sql.split(' ')[0] + '语句执行成功') return True except pymysql.Error as e: print(sql.split(' ')[0] + '语句执行失败') print(e.args[0], e.args[1]) self.connection.rollback() return False # 登录验证 def check_log_in(self, account, pwd, mode): isValidate = False if account == "": feedback = "请输入账号!" return isValidate, feedback if pwd == "": feedback = "请输入密码!" return isValidate, feedback if mode == "": feedback = "请选择账户类型!" return isValidate, feedback table = "administer" if mode == "admin" else "reader" account_attribute = "ANO" if mode == "admin" else "RNO" sql = "select * from %s where %s = '%s';" % (table, account_attribute, account) result = self.select_sql(sql) if len(result) == 0: feedback = "账号错误!请重新输入" return isValidate, feedback if result[0][2] != pwd: feedback = "密码错误!请重新输入" return isValidate, feedback isValidate = True feedback = "账号密码正确!" return isValidate, feedback # 读者功能方法 def borrow_inquiry(self, reader_no): # 进行查询 sql = '''select JNAME, YEAR, VOLUME, NUMBER, BORROWTIME, RETURNTIME is not null AS isRETURN from borrow, journalregister where borrow.JNO = journalregister.JNO and borrow.RNO = '%s';''' % reader_no result = self.select_sql(sql) return result def borrow_inquiry_with_condition(self, reader_no): # 进行未归还借阅查询 sql = '''select JNAME, YEAR, VOLUME, NUMBER, BORROWTIME, RETURNTIME is not null AS isRETURN from borrow, journalregister where borrow.JNO = journalregister.JNO and borrow.RETURNTIME is null and borrow.RNO = '%s';''' % reader_no result = self.select_sql(sql) return result def journal_inquiry(self, keyword): sql = '''select JNAME, YEAR, VOLUME, NUMBER, PAPERTITLE, AUTHOR, PAGES from journalcontent, journalregister where journalcontent.JNO = journalregister.JNO and (journalcontent.KEYWORD1 = '%s' or journalcontent.KEYWORD2 = '%s' or journalcontent.KEYWORD3 = '%s' or journalcontent.KEYWORD4 = '%s' or journalcontent.KEYWORD5 = '%s');''' % \ (keyword, keyword, keyword, keyword, keyword) result = self.select_sql(sql) return result def book(self, record): journal_name = record[1] year = int(record[2]) volume = int(record[3]) number = int(record[4]) # 检查待预定期刊是否存在 journal_whether_exist_sql = """select JNO from journalregister where JNAME="%s" and YEAR=%d and VOLUME=%d and NUMBER=%d """ % \ (journal_name, year, volume, number) journal_exist_result = connect.select_sql(journal_whether_exist_sql) if len(journal_exist_result) == 0: result, feedback = False, "NotExist" return result, feedback # 检查待预定期刊借阅情况 journal_no = journal_exist_result[0][0] borrowed_jno = connect.select_sql('''select JNO from borrow where RETURNTIME is NULL;''') if journal_exist_result[0] not in borrowed_jno: result, feedback = False, "ReadyToBorrow" return result, feedback current_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())) insert_subscribe_sql = """ insert into subscribe(`RNO`,`JNO`,`APPOINTTIME`) values(%s,%s,%s)""" data = [record[0], journal_no, current_time] insert_result = self.update_sql_with_data(insert_subscribe_sql, data) feedback = "Ok" return insert_result, feedback def get_maxJNO(self): sql = "select JNO from journalregister" JNOs = self.select_sql(sql) maxJNO = max([int(i[0]) for i in JNOs]) + 1 return maxJNO # 管理员功能方法 def instock_register(self, instocks): for i in range(len(instocks)): it = instocks[i] x = self.get_maxJNO() y = [x] data = y + it sql = '''INSERT INTO journalregister(JNO, JNAME, YEAR, VOLUME, NUMBER) VALUES (%s, %s, %s, %s, %s)''' if not self.update_sql_with_data(sql, data): # 返回数据库插入操作是否成功 return False return True def catalog_register(self, catalogs): for i in range(len(catalogs)): data = catalogs[i] # print(data) sql = '''INSERT INTO journallist(JNAME,ISSN,CN,POSTCODE,CIRCLE,ADDRESS,SECTION) VALUES(%s,%s,%s,%s,%s,%s,%s)''' if not self.update_sql_with_data(sql, data): return False return True def get_JNO(self, journal_name, year, volume, number): print("In getJNO!") find_jno_sql = '''select JNO from journalregister where JNAME='%s' and YEAR=%d and VOLUME=%d and NUMBER=%d;''' % \ (journal_name, year, volume, number) journal_no = self.select_sql(find_jno_sql) if len(journal_no) == 0: return None return journal_no[0][0] def content_register(self, contents): for i in range(len(contents)): p = contents[i] journal_name = p[0] year = int(p[1]) volume = int(p[2]) number = int(p[3]) journal_no = self.get_JNO(journal_name, year, volume, number) if journal_no is None: return False data = [journal_no] + p[4:] sql = '''INSERT INTO journalcontent (JNO,PAPERTITLE,AUTHOR,KEYWORD1,KEYWORD2,KEYWORD3,KEYWORD4,KEYWORD5,PAGES) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)''' if not self.update_sql_with_data(sql, data): return False return True def borrow_register(self, record): reader_no = record[0] journal_name = record[1] year = int(record[2]) volume = int(record[3]) number = int(record[4]) borrow_date = record[5] journal_no = self.get_JNO(journal_name, year, volume, number) if journal_no is None: return False insert_sql = '''insert into borrow values ('%s', '%s', '%s', NULL);''' % (reader_no, journal_no, borrow_date) insert_result = self.update_sql(insert_sql) return insert_result def return_register(self, record): reader_no = record[0] journal_name = record[1] year = int(record[2]) volume = int(record[3]) number = int(record[4]) return_date = record[5] journal_no = self.get_JNO(journal_name, year, volume, number) if journal_no is None: return False update_sql = '''update borrow set RETURNTIME = '%s' where RNO = '%s' and JNO = '%s' ;''' % (return_date, reader_no, journal_no) update_result = self.update_sql(update_sql) return update_result def whereabouts_inquiry(self, jno): check_in_journal_sql = """select JNO from journalregister where JNO="%s" """ \ % jno check_in_result = connect.select_sql(check_in_journal_sql) if len(check_in_result) == 0: result, feedback = [], "NotExist" return result, feedback destination_sql = """select reader.RNO,reader.RNAME, timestampdiff(day,borrow.BORROWTIME,ifnull(borrow.RETURNTIME,now())), borrow.BORROWTIME, ifnull(borrow.RETURNTIME,now()) from reader,borrow where reader.RNO=borrow.RNO and borrow.JNO="%s" """ \ % jno result = connect.select_sql(destination_sql) feedback = "Ok" return result, feedback def subscribe(self, old_subscribes, new_subscribes): d = date.today() year = d.year + 1 # 年份 row_count = len(old_subscribes) for row in range(row_count): amount = int(old_subscribes[row][2]) sql = '''INSERT INTO `order`(JNAME,YEAR,AMOUNT) VALUES ("%s",%d,%d);''' % \ (old_subscribes[row][0], year, amount) if not self.update_sql(sql): return False row_count = len(new_subscribes) for row in range(row_count): third = int(new_subscribes[row][3]) sql2 = '''INSERT INTO `order`(JNAME,YEAR,AMOUNT) VALUES ("%s",%d,%d);''' % \ (new_subscribes[row][0], year, third) if not self.update_sql(sql2): return False return True class LinkDatabaseInPyQt: def login(self, username, password): self.db = QSqlDatabase.addDatabase('QMYSQL') self.db.setHostName('localhost') self.db.setDatabaseName('journaldatabase') self.db.setUserName(username) self.db.setPassword(password) if not self.db.open(): print(self.db.lastError().text()) else: print('登录成功') def get_all_table_names(self): print(self.db.tables()) # 执行selectsql语句返回查询结果 def selectsql(self, sql): query = QSqlQuery(sql) while query.next(): print(query.value(0)) # 执行删除、插入、更新语句 def changesql(self, sql): pass user = 'root' password = 'zhangweikuo1997+' connect = LinkDatabaseInMysql(user, password) if __name__ == "__main__": rno = input("please input reader no: ") print("output:") if len(rno) != 9: print("illegal reader no") else: result = connect.borrow_inquiry(rno) if len(result) == 0: print("the reader hasn't borrowed a journal!") else: print("the borrow results are above.")
import json from time import sleep import blessed import requests from blessed.keyboard import Keystroke from modules.game import Game from modules.game_data import GameData Bounds = tuple[int, int, int, int] RenderableCoordinate = tuple[int, int, str] def _lies_within_bounds(bounds: Bounds, point: tuple[int, int]) -> bool: """Check whether the given point lies within the given bounds.""" start_i, end_i, start_j, end_j = bounds i, j = point return start_i < i < end_i and start_j < j < end_j def chunk(string: str, width: int) -> list[str]: """Split the given string into a list of lines, where the length of each line is less than the given width.""" lines = string.splitlines() chunked = [] for line in lines: chunked.append("") words = line.split() if any(len(word) >= width for word in words): raise ValueError("Insufficient width") for word in words: # If adding the current word to the current line would cause overflow, add a fresh string to the list. if len(f"{chunked[-1]} {word}") >= width: chunked.append("") # Add the current word to the current line, with a space. chunked[-1] += word + " " return [line.strip() for line in chunked] class GameScreen: """The class of the game screen""" def __init__(self, game_data: GameData): self.game_data = game_data self.game = Game(game_data) self.currently_rendered: set[RenderableCoordinate] = set() self.stories_id = 1 self.colors = self.game_data.data["game"]["colors"]["game"].copy() self.term_color = f"{self.colors['text']}_on_{self.colors['bg']}" self.sidebar_bounds: Bounds = ... self.scene_bounds: Bounds = ... self.message_bar_bounds: Bounds = ... with open("assets/questions.json") as file: self.room2_messages = json.load(file) def init_bound(self, term: blessed.Terminal) -> None: """Initialize the layout side and frame size+position""" width, height = term.width, term.height # The layout have to be fixed and the size of the scene # Top - Bottom - Left - Right self.sidebar_bounds = (1, height - 2, int(3 / 4 * width) + 1, width - 3) self.scene_bounds = (1, int(3 / 4 * height), 2, int(3 / 4 * width) - 1) self.message_bar_bounds = (int(3 / 4 * height) + 1, height - 2, 2, int(3 / 4 * width) - 1) # Render the screen border self._render_dict(term, self._make_border((0, height - 1, 0, width - 1), tuple("╔╗╚╝║═"))) def render(self, term: blessed.Terminal) -> None: """Renders the start screen in the terminal.""" self.init_bound(term) player_current_room = self.game_data.data["player"]["current_room"] room_data = self.game_data.data["room"][str(player_current_room)] with term.cbreak(), term.hidden_cursor(): self.render_layout(term) self.render_initial_story(term) self.render_sidebar_content(term) self.render_messagebar_content(term, "") while 1: player_will_move = False key_input = term.inkey() if key_input.is_sequence: if key_input.name in ["KEY_ESCAPE"]: self.render_messagebar_content(term, self.get_message("messages", "game", "actions", "esc")) while key_input.lower() not in ["q", "s", "c", "esc"]: key_input = term.inkey() if key_input == "s": self.game_data.save_game() self.render_messagebar_content(term, "Saving in progress") sleep(0.8) self.render_messagebar_content(term, "Saving is done") sleep(0.8) elif key_input.lower() == "q": self.game_data.save_game() self.render_messagebar_content(term, "bye ..") sleep(0.8) return self.render_messagebar_content(term, "") elif key_input.name in ["KEY_DOWN", "KEY_UP", "KEY_LEFT", "KEY_RIGHT"]: key_input = key_input.name player_will_move = True elif key_input in ["j", "k", "h", "l"]: player_will_move = True elif key_input == "e": try: joke = requests.get( "https://official-joke-api.appspot.com/jokes/programming/random", timeout=2 ).json()[0] except requests.exceptions.ReadTimeout: pass else: setup, punchline = joke["setup"], joke["punchline"] # Linux might display it wrong self.render_messagebar_content(term, f"{setup}\n\n{punchline}") if player_will_move: if player_current_room == 1: entity_meeted = self.game.move_player(key_input) self.render_scene(term) self.render_messagebar_content(term) if entity_meeted == "D": if not room_data["is_door_unlocked"]: if self.game_data.get_inventory_item_by_key("keys") > 0: self.game_data.unlock_door(player_current_room) self.game_data.dec_inventory_item_by_key("keys") self.render_sidebar_content(term) else: self.render_messagebar_content( term, self.get_message("messages", "story", "room_1", "6"), ) if room_data["is_door_unlocked"]: self.render_messagebar_content(term, self.get_message("entities", "door", "open")) sleep(0.8) self.stories_id = 7 while self.stories_id <= 8: self.render_messagebar_content( term, self.get_message("messages", "story", "room_1", str(self.stories_id)) + " [ENTER]", ) key_input = "" while key_input != "enter": key_input = term.inkey() if key_input.is_sequence and key_input.name == "KEY_ENTER": key_input = "enter" self.stories_id += 1 sleep(0.8) self.render_messagebar_content(term, "") player_current_room = 2 self.game_data.data["player"]["current_room"] = 2 # self.game_data.save_game() self.game.load_map(2) self.render_sidebar_content(term) # 2 times is normal self.render_scene(term) self.render_scene(term) self.render_initial_story(term, True) elif entity_meeted == "K": if not self.game_data.data["room"][str(self.game_data.data["player"]["current_room"])][ "is_key_found" ]: self.game_data.inc_inventory_item_by_key("keys") self.game_data.data["room"][str(self.game_data.data["player"]["current_room"])][ "is_key_found" ] = True self.render_sidebar_content(term) self.render_messagebar_content(term, self.get_message("entities", "key", "is_found")) else: self.render_messagebar_content(term, self.get_message("entities", "key", "already")) elif player_current_room == 2: entity_meeted = self.game.move_player(key_input) self.render_scene(term) if entity_meeted == "X": for message in self.room2_messages: if list(self.game.player.position) in message["coordinates"]: question_prompt = "\n".join( [ f"{message['question']}", self._make_question_template( term, message["template"], message["special index"] ), "Press [A] to attempt or any other key to cancel." if not message["solved"] else "You already found this one.", ] ) self.render_messagebar_content(term, question_prompt, 0) if message["solved"]: sleep(2) break if term.inkey().lower() != "a": break self.render_messagebar_content(term, "Enter guess:\n> ") guess = [] while True: letter = term.inkey() if isinstance(letter, Keystroke) and letter.name == "KEY_ENTER": break if isinstance(letter, Keystroke) and letter.name == "KEY_BACKSPACE": print(term.move_left + " " + term.move_left, end="", flush=True) guess.pop() continue print(letter, end="", flush=True) guess.append(letter) if "".join(guess).lower() != message["answer"].lower(): print(" Incorrect!") sleep(1) else: print(" Correct!") self.game_data.inc_nb_of_clue() message["solved"] = True message["template"] = message["answer"] sleep(1) self.render_sidebar_content(term) elif entity_meeted == "D": if self.game_data.get_nb_of_clue() < 6: self.render_messagebar_content(term, "Solve all questions first!") continue question_prompt = "\n".join( [ "Code Word:", f"{term.red}______{getattr(term, self.term_color)}", "Press [A] to attempt or any other key to cancel.", ] ) self.render_messagebar_content(term, question_prompt) if term.inkey().lower() == "a": self.render_messagebar_content(term, "Enter guess:\n>") guess = [] while True: letter = term.inkey() if isinstance(letter, Keystroke) and letter.name == "KEY_ENTER": break if isinstance(letter, Keystroke) and letter.name == "KEY_BACKSPACE": print(term.move_left + " " + term.move_left, end="", flush=True) guess.pop() continue print(letter, end="", flush=True) guess.append(letter) if "".join(guess).lower() != "python": print(" Incorrect!") sleep(2) else: print(" Correct!") self.render_messagebar_content(term, "Congratulations you can get out of the box!") sleep(2) return self.render_messagebar_content(term, "") def _make_question_template(self, term: blessed.Terminal, template: str, special_index: int) -> str: """Make a string from template with the character at special_index highlighted in red.""" return ( f"{template[:special_index]}" f"{term.red(template[special_index])}" f"{getattr(term, self.term_color)}" f"{template[special_index+1:]}" ) def get_message(self, *args) -> str: """Get the message translation from the file. It help to make the code shorter""" return self.game_data.get_str_in_language(*args) def render_layout(self, term: blessed.Terminal) -> None: """Render the 3 frames""" self._render_dict(term, self._make_border(self.scene_bounds, tuple("╭╮╰╯│─"))) self._render_dict(term, self._make_border(self.sidebar_bounds, tuple("╭╮╰╯│─"))) self._render_dict(term, self._make_border(self.message_bar_bounds, tuple("╭╮╰╯│─"))) # Render scene need to be pickup from a file def render_scene(self, term: blessed.Terminal) -> None: """Render the scene area. Design the level""" # Get the coordinates to be rendered in the scene panel. to_be_rendered = self._make_scene(self.scene_bounds, self.game.get_to_be_rendered()) # Render the coordinates self._render_dict(term, to_be_rendered) # Clear the coordinates that have been removed since the last frame self._render_dict( term, {(i, j, " ", color) for i, j, _, color in self.currently_rendered - to_be_rendered}, ) self.currently_rendered = to_be_rendered def render_sidebar_content(self, term: blessed.Terminal) -> None: """Render the content of the sidebar. Will display all the game data""" start_y, end_y, start_x, end_x = self.sidebar_bounds panel_width = end_x - start_x sidebar_content = self.game.get_sidebar_content() # Clear the previous content in the side bar self._render_dict( term, {(i, j, " ", "") for i in range(start_y + 1, end_y - 1) for j in range(start_x + 1, end_x - 1)} ) col, row = start_x + 2, start_y + 2 for data_key, data_obj in sidebar_content.items(): if data_key == "game_data": text = self.get_message("keys", "game_data") row = end_y - 6 print( term.move_xy(col, row) + getattr(term, self.colors["choice"]) + text + " " * (panel_width - (len(text) + 2)) + getattr(term, self.term_color), end="", ) elif data_key == "player_data": text = self.get_message("keys", "inventory") row = start_y + 2 print( term.move_xy(col, row) + getattr(term, self.colors["choice"]) + text + " " * (panel_width - (len(text) + 2)) + getattr(term, self.term_color), end="", ) for key, value in data_obj.items(): translated_key = self.get_message("keys", key) if isinstance(value, bool): value = self.get_message("keys", str(value).lower()) for line in chunk(f"{translated_key} : {value}", panel_width): row += 1 print(term.move_xy(col, row) + line, end="", flush=True) row += 1 print(term.move_yx(end_y - 1, start_x + 2), end="", flush=True) print(getattr(term, self.colors["choice"]) + "Menu <ESC>" + getattr(term, self.term_color), end="", flush=True) def render_messagebar_content( self, term: blessed.Terminal, message: str = "", writing_speed: float = 0.01 ) -> None: """Render the message bar content in a fixed position at a specified speed.""" start_y, end_y, start_x, end_x = self.message_bar_bounds panel_height = end_y - start_y panel_width = end_x - start_x col, row = start_x + 4, (start_y + round(panel_height / 2)) - 1 # Clear the box before rendering any new message. print(term.move_xy(col, row), end="") nb_of_line_to_clean = panel_height - 1 row_tmp = start_y + 1 for _ in range(nb_of_line_to_clean): print(term.move_xy(col - 2, row_tmp), end="") print(" " * (panel_width - 2), end="", flush=True) row_tmp += 1 print_enter = False if "ENTER" in message: print_enter = True message = message.replace("[ENTER]", "") make_it_faster = bool(writing_speed == 0.01) i = 0 for line in chunk(f"{message}", panel_width - 4): print(term.move_xy(col, row), end="", flush=True) for letter in line: print(letter, end="", flush=True) if make_it_faster and i % 2 or writing_speed > 0.01: sleep(writing_speed) i += 1 row += 1 if print_enter: row += 1 print(term.move_xy(col, row), end="", flush=True) print("press [ENTER] to continue", end="", flush=True) def render_initial_story(self, term: blessed.Terminal, force_story: bool = False) -> None: """It will display the first story to the user""" current_room = self.game_data.data["player"]["current_room"] if current_room == 1: max_story_id = 5 elif current_room == 2: self.stories_id = 1 max_story_id = 6 # Will display the story every run if not self.game_data.is_game_already_played() or force_story: self.game.load_map(current_room) self.render_scene(term) while self.game.story[str(self.stories_id)] != "": self.render_messagebar_content(term, self.game.story[str(self.stories_id)] + " [ENTER]", 0.03) key_input = "" while key_input != "enter": key_input = term.inkey() if key_input.is_sequence and key_input.name == "KEY_ENTER": key_input = "enter" if self.stories_id == 2: self.render_scene(term) elif self.stories_id == max_story_id: self.render_messagebar_content(term) break self.stories_id += 1 self.game_data.set_game_already_played(True) else: # Make all the render self.game.load_map(self.game_data.data["player"]["current_room"]) self.render_scene(term) @staticmethod def _make_border(bounds: Bounds, charset: tuple[str, str, str, str, str, str]) -> set[RenderableCoordinate]: """Create the border of the frame""" start_i, end_i, start_j, end_j = bounds top_left, top_right, bottom_left, bottom_right, vertical, horizontal = charset return ( # the corners: { (start_i, start_j, top_left, ""), (start_i, end_j, top_right, ""), (end_i, start_j, bottom_left, ""), (end_i, end_j, bottom_right, ""), } # the left and right vertical bars: | {(i, j, vertical, "") for i in range(start_i + 1, end_i) for j in (start_j, end_j)} # the top and bottom horizontal bars: | {(i, j, horizontal, "") for i in (start_i, end_i) for j in range(start_j + 1, end_j)} ) @staticmethod def _make_scene(bounds: Bounds, game_map: set[RenderableCoordinate]) -> set[RenderableCoordinate]: """Create a scene frame""" scene_panel_height = bounds[1] - bounds[0] # uppermost row - lowermost row scene_panel_width = bounds[3] - bounds[2] # rightmost column - leftmost column clipped_map = set() i_coordinates = [coordinate[0] for coordinate in game_map] j_coordinates = [coordinate[1] for coordinate in game_map] scene_height = max(i_coordinates) - min(i_coordinates) scene_width = max(j_coordinates) - min(j_coordinates) for i, j, char, color in game_map: # translate from in-game coordinates to main screen coordinates new_i = i - scene_height // 2 + scene_panel_height // 2 new_j = j - scene_width // 2 + scene_panel_width // 2 # filter the coordinates which lie outside the scene panel bounds if _lies_within_bounds(bounds, (new_i, new_j)): clipped_map.add((new_i, new_j, char, color)) return clipped_map def _render_dict( self, term: blessed.Terminal, data: set[RenderableCoordinate], ) -> None: """I will render the dict to the terminal""" for i, j, char, color in data: colored = f"{color}_on_{color}" if char in "KSDOX" else "" print( term.move_yx(i, j) + getattr(term, colored) + char + getattr(term, self.term_color), end="", flush=True, )
from .base import * DEBUG = True TEMPLATE_DEBUG = True ADMINS = () MANAGERS = ADMINS SECRET_KEY = 'TEST' COINS_BASE_URL = 'https://coins.ph' COINS_API_KEY = "09Wvsxce4IVBYfW1yIn4OnvlstObgTXNEeV0i7jY" COINS_SECRET = "8PLwxbZpB3nW2N7kqRaIfkgja5kLTMO6VYUaJMLQ3Aea2yfv4K" # For testing in sandbox # COINS_BASE_URL = 'https://coins.ph' # COINS_API_KEY = "09Wvsxce4IVBYfW1yIn4OnvlstObgTXNEeV0i7jY" # COINS_SECRET = "8PLwxbZpB3nW2N7kqRaIfkgja5kLTMO6VYUaJMLQ3Aea2yfv4K" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(PROJECT_ROOT, 'db.sqlite3'), }, # 'mambu': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'phillipines', # 'USER': 'root', # 'PASSWORD': 'password', # 'HOST': 'localhost', # 'PORT': '3306', # }, # 'mifosx': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': 'mifostenant-testing', # 'USER': 'root', # 'PASSWORD': 'password', # 'HOST': 'localhost', # 'PORT': '3306', # }, } INSTALLED_BACKENDS = { # "twilio-backend": { # "ENGINE": "rtwilio.outgoing.TwilioBackend", # 'config': { # 'account_sid': 'AC4f7dec744e3bcad378e19888b8213af3', # (required) # 'auth_token': '0c7b01582cbe2ce27123e2dc7ac983d6', # (required) # 'number': '(920) 645-2134', # your Twilio phone number (required) # # optional callback URL # # 'callback': 'http://<public-django-instance>/backend/twilio/status-callback/', # } # }, "telerivet": { "ENGINE": "rapidsms_telerivet.outgoing.TelerivetBackend", "project_id": "PJa61703ce18b3a11e", "phone_id": "PN50774ea8fb7cf4ca", "secret": "NQECMMP6W64LQNN7GKPZMUHQNL7PPP7E", "api_key": "SMLXzvuupVOtIP9SIOU5hdXRlSkRwvaM", }, } INSTALLED_APPS = INSTALLED_APPS + ('debug_toolbar', 'djcelery') STATICFILES_DIRS = STATICFILES_DIRS + ( os.path.join(PROJECT_ROOT, 'haedrian', 'static'), os.path.join(PROJECT_ROOT, 'dashboard', 'static'), ) GEM_API_TOKEN = "0QZLYNhs-2v3MsGwcFf-dJQsEoS9VSMV_8a59B_GnwU" GEM_ADMIN_TOKEN = "WdSRt2giHhuK13aicW173cgtcGV36TPm6uk1dOj9SJA" BROKER_URL = 'django://' CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' # MIFOSX_USER = "aquila" # MIFOSX_PASSWORD = "MifosxSaTeCoCeMuBu1" MIFOSX_USER = "mifos" MIFOSX_PASSWORD = "password" MIFOSX_TENANT = "default" MIFOSX_SERVER_URL = "https://{}.haedrian.io/fineract-provider/api/v1/"
''' This file provides a basic framework for a live demo. In this case the demo is for face and eye detection. Copyright David S. Bolme Created on Jul 9, 2011 @author: bolme ''' import pyvision as pv import cv from pyvision.face.CascadeDetector import CascadeDetector from pyvision.face.FilterEyeLocator import FilterEyeLocator def mouseCallback(event, x, y, flags, param): if event in [cv.CV_EVENT_LBUTTONDOWN,cv.CV_EVENT_LBUTTONUP]: print "Mouse Event:",event,x,y if __name__ == '__main__': # Setup the webcam webcam = pv.Webcam() # Setup the face and eye detectors cd = CascadeDetector(min_size=(100,100)) el = FilterEyeLocator() # Setup the mouse callback to handle mause events (optional) cv.NamedWindow("PyVision Live Demo") cv.SetMouseCallback("PyVision Live Demo", mouseCallback) while True: # Grab a frame from the webcam frame = webcam.query() # Run Face and Eye Detection rects = cd(frame) eyes = el(frame,rects) # Annotate the result for rect,leye,reye in eyes: frame.annotateThickRect(rect, 'green', width=3) frame.annotatePoint(leye, color='green') frame.annotatePoint(reye, color='green') # Annotate instructions frame.annotateLabel(pv.Point(10,10), "Press 'q' to quit.") # Show the frame (uses opencv highgui) key_press = frame.show("PyVision Live Demo") # Handle key press events. if key_press == ord('q'): break
# This class is used to implement a stack which in turn is used to implement LRU class Stack: # Default constructor def __init__(self): self.items = [] # Function used to push an item on to the stack def push(self, item): self.items.append(item) # Function used to remove the item from the top of the stack def pop(self): return self.items.pop() # Function used to return the position of the item at the top of the list def peek(self): return self.items[len(self.items) - 1] # Function used to return the size of the stack def size(self): return len(self.items) # Function used to find an item in the stack def find(self, item): return self.items.index(item) # Function to remove a page from the stack def remove(self, item): self.items.remove(item) # This class holds the attributes and methods for the least recently used page replacement class LeastRecentlyUsed: # Default constructor def __init__(self, page_sequence): # Initializing a sequence list filled with the pages self.sequence = page_sequence # Creating a stack that we have to use self.stack = Stack() # Setting the number of page faults to zero in the beginning self.page_fault = 0 # Function used to execute the logic for least recently used page replacement algorithm def run(self): # Iterating through the sequence of pages for i in self.sequence: # This variable tells us whether the page is present in the stack or not present_flag = False # First we check to see if page is present in the stack or not try: position = self.stack.find(i) # If the page is present in the stack we set the flag to true present_flag = True except ValueError: pass # If the page is already present if present_flag: # Then we remove the item from its position in the stack self.stack.remove(i) # Then we re insert the item to the stack again self.stack.push(i) # Display the current status of the stack self.display(i) # Else if the page is not present else: # We add the page to stack self.stack.push(i) # Display the current status of the stack self.display(i) # Increment the page fault by one self.page_fault += 1 # Function used to display the status of the frames and the pages in them def display(self, page): # The frames of pages into a string and removing the first and last square brackets current_stack_status = str(self.stack.items)[1:-1] # Printing the status of the stack print(page+": <"+current_stack_status+">")
from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAuthenticated from notifications.models import Notification from .serializers import NotificationSerializer class NotificationListAPIView(ListAPIView): """ View that returns notification list of a single user. """ serializer_class = NotificationSerializer permission_classes = [IsAuthenticated] def get_queryset(self, *args, **kwargs): queryset_list = Notification.get_user_notification(self.request.user) unread_notifications = queryset_list.filter(is_read=False) # Add celery or something to alter the is_read flag in background # So this flag could be used in front end for styling purposes for notification in unread_notifications: notification.is_read = True notification.save() return queryset_list
from maya import cmds from PySide2 import QtWidgets, QtGui, QtCore from ncachefactory.optionvars import ( RANGETYPE_OPTIONVAR, CACHE_BEHAVIOR_OPTIONVAR, VERBOSE_OPTIONVAR, VERBOSE_OPTIONVAR, SAMPLES_EVALUATED_OPTIONVAR, SAMPLES_SAVED_OPTIONVAR, ensure_optionvars_exists) BLENDMODE_LABELS = ( "Clear all existing cache nodes and blend \n" "nodes before the new cache. (default)", "Clear all existing cache nodes but blend \n" "the new caches if old ones are already \n" "connected to blend nodes.", "Doesn't clear anything and blend the \n" "new cache with all existing nodes.") class CacheOptions(QtWidgets.QWidget): def __init__(self, parent=None): super(CacheOptions, self).__init__(parent) self._verbose = QtWidgets.QCheckBox('Verbose') self._rangetype_timeline = QtWidgets.QRadioButton('Timeline') self._rangetype_custom = QtWidgets.QRadioButton('Custom range') self._rangetype = QtWidgets.QButtonGroup() self._rangetype.addButton(self._rangetype_timeline, 0) self._rangetype.addButton(self._rangetype_custom, 1) self._rangein = QtWidgets.QLineEdit('0') self._rangein.setMaxLength(5) self._rangein.setFixedWidth(60) self._rangein.setValidator(QtGui.QIntValidator()) self._rangeout = QtWidgets.QLineEdit('100') self._rangeout.setMaxLength(5) self._rangeout.setFixedWidth(60) self._rangeout.setValidator(QtGui.QIntValidator()) self._behavior_clear = QtWidgets.QRadioButton(BLENDMODE_LABELS[0]) self._behavior_blend = QtWidgets.QRadioButton(BLENDMODE_LABELS[1]) self._behavior_force_blend = QtWidgets.QRadioButton(BLENDMODE_LABELS[2]) self._behavior = QtWidgets.QButtonGroup() self._behavior.addButton(self._behavior_clear, 0) self._behavior.addButton(self._behavior_blend, 1) self._behavior.addButton(self._behavior_force_blend, 2) self._samples_evaluated = QtWidgets.QLineEdit() self._samples_evaluated.setValidator(QtGui.QDoubleValidator()) self._samples_evaluated.setFixedWidth(60) self._samples_recorded = QtWidgets.QLineEdit() self._samples_recorded.setValidator(QtGui.QIntValidator()) self._samples_recorded.setFixedWidth(60) self._custom_range = QtWidgets.QWidget() self._range_layout = QtWidgets.QHBoxLayout(self._custom_range) self._range_layout.addWidget(self._rangein) self._range_layout.addWidget(self._rangeout) self._range_layout.addStretch(1) self.layout = QtWidgets.QFormLayout(self) self.layout.setSpacing(0) self.layout.addRow("", self._verbose) self.layout.addItem(QtWidgets.QSpacerItem(10, 10)) self.layout.addRow("Range: ", self._rangetype_timeline) self.layout.addRow("", self._rangetype_custom) self.layout.addRow("", self._custom_range) self.layout.addItem(QtWidgets.QSpacerItem(10, 10)) self.layout.addRow("Attach method: ", self._behavior_clear) self.layout.addRow("", self._behavior_blend) self.layout.addRow("", self._behavior_force_blend) self.layout.addItem(QtWidgets.QSpacerItem(10, 10)) self.layout.addRow("Evaluation sample: ", self._samples_evaluated) self.layout.addRow("Save every evaluation(s): ", self._samples_recorded) self.set_optionvars() self.update_ui_states() self._verbose.stateChanged.connect(self.save_optionvars) self._rangetype.buttonToggled.connect(self.save_optionvars) self._rangetype.buttonToggled.connect(self.update_ui_states) self._behavior.buttonToggled.connect(self.save_optionvars) self._samples_evaluated.textEdited.connect(self.save_optionvars) self._samples_recorded.textEdited.connect(self.save_optionvars) def update_ui_states(self, *signals_args): self._custom_range.setEnabled(bool(self._rangetype.checkedId())) def set_optionvars(self): ensure_optionvars_exists() value = cmds.optionVar(query=VERBOSE_OPTIONVAR) self._verbose.setChecked(value) id_ = cmds.optionVar(query=RANGETYPE_OPTIONVAR) button = self._rangetype.button(id_) button.setChecked(True) id_ = cmds.optionVar(query=CACHE_BEHAVIOR_OPTIONVAR) button = self._behavior.button(id_) button.setChecked(True) value = cmds.optionVar(query=SAMPLES_EVALUATED_OPTIONVAR) self._samples_evaluated.setText(str(value)) value = cmds.optionVar(query=SAMPLES_SAVED_OPTIONVAR) self._samples_recorded.setText(str(value)) def save_optionvars(self, *signals_args): value = self._verbose.isChecked() cmds.optionVar(intValue=[VERBOSE_OPTIONVAR, value]) value = self._rangetype.checkedId() cmds.optionVar(intValue=[RANGETYPE_OPTIONVAR, value]) value = self._behavior.checkedId() cmds.optionVar(intValue=[CACHE_BEHAVIOR_OPTIONVAR, value]) value = float(self._samples_recorded.text()) cmds.optionVar(floatValue=[SAMPLES_EVALUATED_OPTIONVAR, value]) value = int(self._samples_recorded.text()) cmds.optionVar(intValue=[SAMPLES_SAVED_OPTIONVAR, value]) @property def range(self): if self._rangetype.checkedId() == 0: startframe = int(cmds.playbackOptions(minTime=True, query=True)) endframe = int(cmds.playbackOptions(maxTime=True, query=True)) else: startframe = int(self._rangein.text()) endframe = int(self._rangeout.text()) return startframe, endframe @property def behavior(self): return self._behavior.checkedId() @property def verbose(self): return self._verbose.isChecked() @property def samples_evaluated(self): return float(self._samples_evaluated.text()) @property def samples_recorded(self): return int(self._samples_recorded.text())
#import skimage.io as io #import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score def read_img(img_path): img = io.imread(img_path) return img def save_img(img_path, np_array): io.imsave(img_path, np_array) def extract_patches(output_folder, img_array, img_reference, stride): # Hint: create a rutine to extract patches from training image and training reference" # Create a tensor [rows, cols, R_G_B_Labels] # save patches to train folder np.save(output_folder + patch_name, patch_array_tensor) def normalize(im_patch_array): return np.array(im_patch_array)/127.5 - 1. def inverse_transform(images): return (images+1.)/2. def load_data(RGBLabel_patches_path_npy): RGBLabels = np.load(RGBLabel_patches_path_npy) rgb_patch = RGBLabels[:, :, :3] rgb_patch = normalize(rgb_patch) label_patch = RGBLabels[:, :, 3] return np.concatenate((rgb_patch, label_patch), axis=2) def compute_metrics(true_labels, predicted_labels): accuracy = accuracy_score(true_labels, predicted_labels) f1score = 100*f1_score(true_labels, predicted_labels, average=None) recall = 100*recall_score(true_labels, predicted_labels, average=None) prescision = 100*precision_score(true_labels, predicted_labels, average=None) return accuracy, f1score, recall, prescision
from transformers import RobertaTokenizer, RobertaModel, RobertaConfig import torch import os class EmbeddingGenerator: ''' A class which generates embeddings for text and saves them to data/tensors/ ''' def __init__(self): self.config = RobertaConfig.from_pretrained("roberta-base") self.config.output_hidden_states = True self.tok = RobertaTokenizer.from_pretrained("roberta-base") self.model = RobertaModel.from_pretrained("roberta-base", config=self.config) def get_embeddings(self, prompt, id=None, willSave=True): ''' Generates embeddings for a prompt based on roberta. :param prompt: The body of text to get embeddings from. :param id: The id of the bill, used to determine a filename for the tensor to be saved in. Only needed if willSave is True. :param willSave: Whether or not to save the embeddings generated for this prompt. Use True if you are creating tensors for bills and use false if it is a tensor for a prompt :return: ''' input_tensor = torch.tensor([self.tok.encode(prompt, max_length=512, padding="max_length", truncation=True)]) output = self.model(input_tensor) # returns a tuple(sequence_output, pooled_output, hidden_states) hidden_states = output[-1] embedding_output = hidden_states[0] if not os.path.isdir("../../data/tensors"): os.mkdir("../../data/tensors") if willSave: if id is None: raise ValueError('asked to save tensor but no id given') torch.save(embedding_output, '../../data/tensors/' + id + '.pt') return embedding_output
import asyncio import datetime import json import logging from pathlib import Path import discord from discord.ext import commands # https://discordapp.com/oauth2/authorize?client_id=500165490753404938&scope=bot&permissions=8 # APPROVED SERVERS: # Fooeyy Official - 476519720380792834 def config_load(): with open("data/config.json", "r", encoding="utf-8") as doc: # Please make sure encoding is correct, especially after editing the config file return json.load(doc) def guild_config_load(gid): with open(f"data/servers/{gid}/config.json", "r", encoding="utf-8") as doc: return json.load(doc) async def run(): """ Where the bot gets started. If you wanted to create an database connection pool or other session for the bot to use, it's recommended that you create it here and pass it to the bot as a kwarg. """ config = config_load() bot = Bot(config=config, description=config["description"] + config["prefix"]) try: await bot.start(config["token"]) except KeyboardInterrupt: await bot.logout() class Bot(commands.Bot): def __init__(self, **kwargs): super().__init__( command_prefix=self.get_prefix_, description=kwargs.pop("description") ) self.start_time = None self.app_info = None self.loop.create_task(self.track_start()) self.loop.create_task(self.load_all_extensions()) async def track_start(self): """ Waits for the bot to connect to discord and then records the time. Can be used to work out uptime. """ await self.wait_until_ready() self.start_time = datetime.datetime.utcnow() async def get_prefix_(self, bot, message): """ A coroutine that returns a prefix. I have made this a coroutine just to show that it can be done. If you needed async logic in here it can be done. A good example of async logic would be retrieving a prefix from a database. """ config = config_load() prefix = [config["prefix"]] return commands.when_mentioned_or(*prefix)(bot, message) async def load_all_extensions(self): """ Attempts to load all .py files in /cogs/ as cog extensions """ await self.wait_until_ready() await asyncio.sleep( 1 ) # ensure that on_ready has completed and finished printing cogs = [x.stem for x in Path("cogs").glob("*.py")] for extension in cogs: try: self.load_extension(f"cogs.{extension}") print(f"loaded {extension}") except Exception as e: error = f"{extension}\n {type(e).__name__} : {e}" print(f"failed to load extension {error}") print("-" * 10) async def on_ready(self): """ This event is called every time the bot connects or resumes connection. """ self.remove_command("help") # await self.change_presence(activity=discord.Game(name='Version 2.0')) print("-" * 10) self.app_info = await self.application_info() print( f"Logged in as: {self.user.name}\n" f"Using discord.py version: {discord.__version__}\n" f"Owner: {self.app_info.owner}" ) print("-" * 10) async def on_message(self, message): """ This event triggers on every message received by the bot. Including one's that it sent itself. If you wish to have multiple event listeners they can be added in other cogs. All on_message listeners should always ignore bots. """ config = config_load() if isinstance(message.channel, discord.TextChannel): guild_config = guild_config_load(message.guild.id) # print(guild_config) # print(guild_config['lockdownmode']) if ( guild_config["lockdownmode"] and not message.author.guild_permissions.administrator ): await message.delete() if message.author.id == 263_883_999_687_081_984 and config["fuck_with_gennate"]: await message.delete() return if message.author.bot and message.content != "Pong!": return # ignore all bots if not isinstance( message.channel, discord.TextChannel ) and message.content.startswith(config["prefix"]): return # ignore all private message commands if not isinstance(message.channel, discord.TextChannel): await self.process_commands(message) return with open( f"data/servers/{message.guild.id}/blacklist.txt", "r" ) as blacklistfile: blacklist = blacklistfile.read().splitlines() for line in blacklist: if ( line.lower() in message.content.lower() and message.author.id != 146_151_306_216_734_720 and not message.author.guild_permissions.administrator ): await message.delete() await message.channel.send( f"You said a blacklisted word/phrase/url, <@{message.author.id}>. Don't say it again." ) return if message.channel.id == 464_681_103_970_795_521 and not ( "youtube.com" in message.content or "youtu.be" in message.content ): await message.delete() await message.author.send( "Only youtube links are allowed in the youtube selfpromo channel." ) return if ( message.channel.id == 464_681_092_319_019_008 and not "twitch.tv" in message.content ): await message.delete() await message.author.send( "Only twitch links are allowed in the twitch selfpromo channel." ) return if message.guild.id == 476_519_720_380_792_834 and not ( message.channel != 477_682_348_880_560_128 and message.channel != 477_198_878_429_413_416 ): return if message.author.id == 146_151_306_216_734_720: if message.content.startswith("^reload "): extension = message.content[8:] try: self.unload_extension(f"cogs.{extension}") self.load_extension(f"cogs.{extension}") await message.channel.send(f"Succesfully reloaded `{extension}`") print(f"reloaded {extension}") print("-" * 10) except Exception as e: error = f"{extension}\n {type(e).__name__} : {e}" await message.channel.send(f"Failed to reload cog {error}") return if message.content.startswith("^load "): extension = message.content[6:] try: self.load_extension(f"cogs.{extension}") await message.channel.send(f"Succesfully loaded `{extension}`") print(f"loaded {extension}") print("-" * 10) except Exception as e: error = f"{extension}\n {type(e).__name__} : {e}" await message.channel.send(f"Failed to load cog {error}") return if message.content.startswith("^unload "): extension = message.content[8:] try: self.unload_extension(f"cogs.{extension}") await message.channel.send(f"Succesfully unloaded `{extension}`") print(f"unloaded {extension}") print("-" * 10) except Exception as e: error = f"{extension}\n {type(e).__name__} : {e}" await message.channel.send(f"Failed to unload cog {error}") return await self.process_commands(message) if __name__ == "__main__": logging.basicConfig(level=logging.INFO) loop = asyncio.get_event_loop() loop.run_until_complete(run())
def number_generator(): yield 0 yield 1 yield 2 # for i in number_generator(): # print(i) g = number_generator() # print(dir(g)) print(next(g)) print(next(g)) print(next(g)) def one_generator(): yield 1 return 'return에 지정한 값' try: g = one_generator() next(g) next(g) except StopIteration as e: print(e) # return에 지정한 값
# coding: utf-8 """Набор конструкция для работы с уровнем моделей.""" import os import simplejson as json import sqlalchemy from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.automap import automap_base from sqlalchemy.inspection import inspect from sqlalchemy.orm.properties import ColumnProperty from sqlalchemy.sql.schema import Table, MetaData, Column, Index import pynch.exceptions as exc class _BuildMapping: @classmethod def create_fk(cls, __name__, **kwargs): return __name__(**kwargs) @classmethod def create_column(cls, __name__, __type__, __fk__=None, **kwargs): args = [__name__, cls.create_type(**__type__)] if __fk__: args.append(cls.create_fk(**__fk__)) return Column(*args, **kwargs) @classmethod def create_type(cls, __name__, **kwargs): return __name__(**kwargs) @classmethod def load(cls, meta, fname): with open(fname, 'r') as f: cls.create_table( meta, json.loads(f.read(), object_hook=cls.cast_type)) @classmethod def create_table(cls, meta, tables): for table in tables: indices = [] if table.get('__indices__'): indices = [cls.create_indeces(**index) for index in table['__indices__']] Table( table['__name__'], meta, *([cls.create_column(**column) for column in table['__columns__']] + indices)) @classmethod def create_indeces(cls, __name__, __columns__, **kwargs): return Index(__name__, *__columns__, **kwargs) @classmethod def cast_type(cls, obj): items = [] for k, v in obj.items(): if isinstance(v, str) and v.startswith('$'): v = getattr(sqlalchemy, v[1:]) elif isinstance(v, dict): v = cls.cast_type(v) items.append((k, v)) return dict(items) class Model: """Реализация уровня модели.""" # Аналогично select * ASTERISK = "*" # Возможные операции соединения JOIN_CONDITIONS = { '==': 'join', '=': 'outerjoin' } def __init__(self, db_mapper, session, name, joins=None, select=ASTERISK): """. :param db_mapper: Ссылка на маппер :param session: Ссылка на сессию :param name: Название таблицы :param joins: Список таблиц для соединения :param select: Список полей для селекта или select * """ self._db_mapper = db_mapper self._name = name self._session = session self._labels = {} qs = self._create_select(session, select, [outher[0] for *_, outher in joins or []]) self._qs = self._create_joins(qs, joins or []) def _create_aliases(self, model_name=''): # Создание алиасов, чтобы джойны не пересекались model = getattr(self._db_mapper, model_name, self.current) for column in inspect(model).attrs: if isinstance(column, ColumnProperty): yield self._create_alias(column.key, model_name) def _create_alias(self, field, model_name=''): # Создание алиаса для конкретного поля в модели, # если модель не используется - предполагается текущая модель model = getattr(self._db_mapper, model_name, self.current) col = getattr(model, field) if model_name: key = '{0}.{1}'.format(model_name, field) else: key = field label = col.label(key) self._labels[key] = label return label def _create_select(self, session, select, models): # Создание полей в объекте select select_statement = [] if select == self.ASTERISK: # select * from ... select_statement.extend( self._create_aliases() ) # Нужно собрать информацию с джойнов for m in models: select_statement.extend(self._create_aliases(m)) else: # select id, foo, bar from baz for field in select: names = field.split('.') if len(names) == 2: model, column = names else: model, column = '', field select_statement.append( self._create_alias(column, model)) assert select_statement return session.query(*select_statement) def create_query(self): """Работа с запросами.""" return self._qs def create_object(self, **kwargs): """Операция создания объекта.""" obj = self.current() for item, value in kwargs.items(): if not hasattr(obj, item): raise exc.NameValidationError( item, obj ) setattr(obj, item, value) self._session.add(obj) try: self._session.flush() # Для получения id объекта except IntegrityError as e: # TODO: Перенести проверку на constraint-ов в NullValidationError raise exc.ValidationError( str(e.orig) ) return obj def get_field(self, field_name): """ Получение объекта поля по его наименованию. :param field_name: Наименование поля """ # Если есть джойны, тогда должны быть алиасы: # alias = self._labels.get(field_name, None) # if alias is not None: # return alias model_name = None if '.' in field_name: model_name, field_name = field_name.split('.') if model_name: model = getattr(self._db_mapper, model_name) else: model = self.current try: field = getattr(model, field_name) except AttributeError: raise exc.NameValidationError( field_name, model ) return field def _create_joins(self, qs, joins): # Создание join-ов for inner_field_name, condition, outher_field_name, outher in joins: # TODO: Реализовать вложенные джойны outer_model_name = outher[0] # operator = getattr(qs, self.JOIN_CONDITIONS[condition]) outer_model = getattr(self._db_mapper, outer_model_name) qs = operator( outer_model, self.get_field(inner_field_name) == self.get_field( '{0}.{1}'.format(outer_model_name, outher_field_name) )) return qs @property def current(self): """Возвращает текущую таблицу.""" return getattr(self._db_mapper, self._name) def exists(self, qs): """ Возвращает QS. C присоединенной информацией о проверки наличия объекта """ return self._session.query(qs.exists()) class DBMapper: """ Коллекция mappings для моделей из приложений. Которые указываются при вызове конструктора """ def __init__(self, config): """. :param config: Путь до конфигурации схемы :return: """ path = os.path.expandvars(config) if not os.path.isfile(path): raise ValueError( '$PYNCH_SCHEMA is not file - "{0}"'.format(path)) self._metadata = MetaData() _BuildMapping.load(self._metadata, path) self._base = automap_base(metadata=self._metadata) self._base.prepare() def __getattr__(self, attr): """ Прозрачная работа с данными таблиц. :param str attr: Наименование таблицы :return: """ return getattr(self._base.classes, attr) __all__ = ('DBMapper', 'Model')
from process import wordlist import itertools import time import os import re ALPHABET = '23456789abcdefghjkmnpqrstuvwxyz' def main(): blacklist_all = wordlist.dict_by_length() blacklist = blacklist_all[3].union(blacklist_all[4]).union(blacklist_all[5]) combinations = get_combinations(3) tick = time.time() bad_guids = generate_guids(blacklist, combinations=combinations) print('Time: {}, Length: {}'.format(time.time()-tick, len(bad_guids))) bad_guids.union(generate_69s(combinations)) with open('guid_blacklist.txt', 'w') as writer: for item in bad_guids: writer.write(item + os.linesep) def get_combinations(length, alphabet=ALPHABET): combinations = {} for x in range(length): combinations[x + 1] = list(itertools.product(alphabet, repeat=(x+1))) return combinations def generate_guids(words, combinations=None, length=5, alphabet=ALPHABET): guids = set() if not combinations: combinations = get_combinations(2, alphabet) n = 0 for word in words: if n % 1000 == 0: print(str(n)) if len(word) > length: raise Exception if len(word) == length: guids.add(word) else: positions = n_positions(word, length) n_random = length - len(word) for c in combinations[n_random]: for i in range(0, positions): word_list = create_word_list(word, i) available_indices = [i for i, x in enumerate(word_list) if not x] for idx in available_indices: index = available_indices.index(idx) word_list[idx] = c[index] result = ''.join(word_list) guids.add(result) n += 1 return guids def generate_69s(combinations): found = [] guids_with_69 = generate_guids(['69'], combinations=combinations) for word in guids_with_69: if re.search('[a-z]69[a-z]', word) or \ re.search('^69[a-z]', word) or \ re.search('[a-z]69$', word): found.append(word) return found def create_word_list(word, index): word_list = [None] * 5 for letter in word: word_list[index] = letter index += 1 return word_list def n_positions(word, length): return length - len(word) + 1 if __name__ == '__main__': main()
''' Created on 13.06.2016 @author: Fabian Reiber @version: 1.0 ''' class NoFingerprintException(Exception): def __str__(self, *args, **kwargs): return Exception.__str__(self, *args, **kwargs) # # a = NoFingerprintException('Blaa') # print('test:', a.args[0]) # raise a
#!/usr/bin/python import sys, os, platform import configparser from executely.constants import Java class AppConfiguration(object): def __init__(self, app_path): if (not os.path.exists(app_path)): raise Exception('The app folder "%s" does not exist!' % app_path) config = configparser.ConfigParser() config.read(os.path.join(app_path, 'app.cfg')) self.__main_class = AppConfiguration.parse_property(config, 'main_class') self.__jvm_args = AppConfiguration.parse_property(config, 'jvm_args') self.__command_line_args = AppConfiguration.parse_property(config, 'command_line_args') self.__classpath = AppConfiguration.parse_classpath(app_path, AppConfiguration.parse_classpath_from_config(config, 'classpath')) self.__app_path = app_path self.__stdout_path = os.path.join(app_path, AppConfiguration.parse_property(config, 'stdout_path', 'stdout.log')) self.__stderr_path = os.path.join(app_path, AppConfiguration.parse_property(config, 'stderr_path', 'stderr.log')) @property def main_class(self): return self.__main_class @property def jvm_args(self): return self.__jvm_args @property def command_line_args(self): return self.__command_line_args @property def classpath(self): return self.__classpath @property def app_path(self): return self.__app_path @property def stdout_path(self): return self.__stdout_path @property def stderr_path(self): return self.__stderr_path def get_command(self, java_command=Java.DEFAULT_COMMAND): args = self.command_line_args.split() command = [java_command, self.jvm_args, "-classpath", self.classpath, self.main_class] + args return [token for token in command if token] def is_valid(self): mandatory_fields = [self.main_class] if not all(mandatory_fields): print("Some mandatory fields are missing from configuration file!") return False return True @staticmethod def parse_classpath(app_path, app_classpath=''): non_posix_os_prefix = ['CYGWIN', 'WINDOWS'] classpath_separator = ':' for os in non_posix_os_prefix: if platform.platform().upper().startswith(os): classpath_separator = ';' break default_classpath = ['.', 'dependencies/*', 'target/*', 'target/dependency/*', ('%s/*' % app_path), ('%s/dependencies/*' % app_path)] classpath = classpath_separator.join(app_classpath + default_classpath) return classpath @staticmethod def parse_property(config, key, default=''): if config.has_option('defaults', key): return config.get('defaults', key) else: return default @staticmethod def parse_classpath_from_config(config, key): app_config_classpath_separator = "," classpath = AppConfiguration.parse_property(config, key, default='') if classpath: return [cp.strip() for cp in classpath.split(app_config_classpath_separator)] return []
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import pytest import torch from numba import cuda from warprnnt_numba.rnnt_loss import rnnt_numpy from warprnnt_numba.rnnt_loss.rnnt_pytorch import certify_inputs from warprnnt_numba.rnnt_loss.utils.cuda_utils import gpu_rnnt_kernel, reduce from warprnnt_numba import numba_utils from warprnnt_numba.numba_utils import __NUMBA_MINIMUM_VERSION__ def log_softmax(x, axis=-1): x = torch.from_numpy(x) # zero-copy x = torch.log_softmax(x, dim=axis) x = x.numpy() return x class TestRNNTCUDAKernels: @pytest.mark.skipif(not cuda.is_available(), reason="CUDA Reductions can only be run when CUDA is available") def test_compute_alphas_kernel(self): numba_utils.skip_numba_cuda_test_if_unsupported(__NUMBA_MINIMUM_VERSION__) random = np.random.RandomState(0) original_shape = [1, 5, 11, 3] B, T, U, V = original_shape # Numpy kernel x = random.randn(*original_shape) labels = np.array([[1, 1, 1, 2, 2, 2, 1, 2, 2, 1]]) # [1, 10] label_len = len(labels[0]) + 1 blank_idx = 0 x_np = log_softmax(x, axis=-1) ground_alphas, ground_log_likelihood = rnnt_numpy.forward_pass( x_np[0, :, :label_len, :], labels[0, : label_len - 1], blank_idx ) # Pytorch kernel device = torch.device('cuda') if hasattr(cuda, 'external_stream'): stream = cuda.external_stream(torch.cuda.current_stream(device).cuda_stream) else: stream = cuda.default_stream() x_c = torch.tensor(x, device=device, dtype=torch.float32) labels_c = torch.tensor(labels, device=device, dtype=torch.int32) # Allocate workspace memory denom = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) alphas = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) llForward = torch.zeros(B, device=device, dtype=x_c.dtype) input_lengths = torch.tensor([T], dtype=torch.int32, device=device) label_lengths = torch.tensor([len(labels[0])], dtype=torch.int32, device=device) # certify input data certify_inputs(x_c, labels_c, input_lengths, label_lengths) # flatten activation tensor (for pointer based indexing) x_c = x_c.view([-1]) # call kernel # log softmax reduction reduce.reduce_max(x_c, denom, rows=V, cols=B * T * U, minus=False, stream=stream) reduce.reduce_exp(x_c, denom, rows=V, cols=B * T * U, minus=True, stream=stream) # alpha kernel gpu_rnnt_kernel.compute_alphas_kernel[B, U, stream, 0]( x_c, denom, alphas, llForward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, ) # sync kernel stream.synchronize() # reshape alphas alphas = alphas.view([B, T, U]) diff = ground_alphas - alphas[0].cpu().numpy() assert np.abs(diff).mean() <= 1e-5 assert np.square(diff).mean() <= 1e-10 ll_diff = ground_log_likelihood - llForward[0].cpu().numpy() assert np.abs(ll_diff).mean() <= 1e-5 assert np.square(ll_diff).mean() <= 1e-10 @pytest.mark.skipif(not cuda.is_available(), reason="CUDA Reductions can only be run when CUDA is available") def test_compute_betas_kernel(self): numba_utils.skip_numba_cuda_test_if_unsupported(__NUMBA_MINIMUM_VERSION__) random = np.random.RandomState(0) original_shape = [1, 5, 11, 3] B, T, U, V = original_shape # Numpy kernel x = random.randn(*original_shape) labels = np.array([[1, 1, 1, 2, 2, 2, 1, 2, 2, 1]]) # [1, 10] label_len = len(labels[0]) + 1 blank_idx = 0 x_np = log_softmax(x, axis=-1) ground_alphas, ground_log_likelihood = rnnt_numpy.backward_pass( x_np[0, :, :label_len, :], labels[0, : label_len - 1], blank_idx ) # Pytorch kernel device = torch.device('cuda') if hasattr(cuda, 'external_stream'): stream = cuda.external_stream(torch.cuda.current_stream(device).cuda_stream) else: stream = cuda.default_stream() x_c = torch.tensor(x, device=device, dtype=torch.float32) labels_c = torch.tensor(labels, device=device, dtype=torch.int32) # Allocate workspace memory denom = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) betas = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) llBackward = torch.zeros(B, device=device, dtype=x_c.dtype) input_lengths = torch.tensor([T], dtype=torch.int32, device=device) label_lengths = torch.tensor([len(labels[0])], dtype=torch.int32, device=device) # certify input data certify_inputs(x_c, labels_c, input_lengths, label_lengths) # flatten activation tensor (for pointer based indexing) x_c = x_c.view([-1]) # call kernel # log softmax reduction reduce.reduce_max(x_c, denom, rows=V, cols=B * T * U, minus=False, stream=stream) reduce.reduce_exp(x_c, denom, rows=V, cols=B * T * U, minus=True, stream=stream) # beta kernel gpu_rnnt_kernel.compute_betas_kernel[B, U, stream, 0]( x_c, denom, betas, llBackward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, ) # sync kernel stream.synchronize() # reshape alphas betas = betas.view([B, T, U]) diff = ground_alphas - betas[0].cpu().numpy() assert np.abs(diff).mean() <= 1e-5 assert np.square(diff).mean() <= 1e-10 ll_diff = ground_log_likelihood - llBackward[0].cpu().numpy() assert np.abs(ll_diff).mean() <= 1e-5 assert np.square(ll_diff).mean() <= 1e-10 @pytest.mark.skipif(not cuda.is_available(), reason="CUDA Reductions can only be run when CUDA is available") @pytest.mark.unit def test_compute_grads_kernel(self): numba_utils.skip_numba_cuda_test_if_unsupported(__NUMBA_MINIMUM_VERSION__) fastemit_lambda = 0.0 clamp = 0.0 random = np.random.RandomState(0) original_shape = [1, 5, 11, 3] B, T, U, V = original_shape # Numpy kernel x = random.randn(*original_shape) labels = torch.from_numpy(np.array([[1, 1, 1, 2, 2, 2, 1, 2, 2, 1]], dtype=np.int32)) # [1, 10] audio_len = torch.from_numpy(np.array([T], dtype=np.int32)) label_len = torch.from_numpy(np.array([U - 1], dtype=np.int32)) blank_idx = 0 x_np = torch.from_numpy(x) x_np.requires_grad_(True) """ Here we will directly utilize the numpy variant of the loss without explicitly calling the numpy functions for alpha, beta and grads. This is because the grads returned by the rnnt_numpy.transduce_batch() are : d/dx (alpha + beta alignment)(log_softmax(x)). But according to the chain rule, we'd still need to compute the gradient of log_softmax(x) and update the alignments by hand. Instead, we will rely on pytorch to compute the gradient of the log_softmax(x) step and propagate it backwards. """ loss_func = rnnt_numpy.RNNTLoss(blank_idx, fastemit_lambda=fastemit_lambda, clamp=clamp) loss_val = loss_func(x_np, labels, audio_len, label_len) loss_val.sum().backward() true_grads = x_np.grad # Pytorch kernel device = torch.device('cuda') if hasattr(cuda, 'external_stream'): stream = cuda.external_stream(torch.cuda.current_stream(device).cuda_stream) else: stream = cuda.default_stream() x_c = torch.tensor(x, device=device, dtype=torch.float32) labels_c = torch.tensor(labels, device=device, dtype=torch.int32) # Allocate workspace memory denom = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) alphas = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) betas = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) llForward = torch.zeros(B, device=device, dtype=x_c.dtype) llBackward = torch.zeros(B, device=device, dtype=x_c.dtype) input_lengths = torch.tensor([T], dtype=torch.int32, device=device) label_lengths = torch.tensor([len(labels[0])], dtype=torch.int32, device=device) # certify input data certify_inputs(x_c, labels_c, input_lengths, label_lengths) # flatten activation tensor (for pointer based indexing) x_c = x_c.view([-1]) grads = torch.zeros_like(x_c, requires_grad=False) # call kernel # log softmax reduction reduce.reduce_max(x_c, denom, rows=V, cols=B * T * U, minus=False, stream=stream) reduce.reduce_exp(x_c, denom, rows=V, cols=B * T * U, minus=True, stream=stream) # alpha kernel gpu_rnnt_kernel.compute_alphas_kernel[B, U, stream, 0]( x_c, denom, alphas, llForward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, ) # beta kernel gpu_rnnt_kernel.compute_betas_kernel[B, U, stream, 0]( x_c, denom, betas, llBackward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, ) # gamma kernel grad_blocks_per_grid = B * T * U grad_threads_per_block = gpu_rnnt_kernel.GPU_RNNT_THREAD_SIZE gpu_rnnt_kernel.compute_grad_kernel[grad_blocks_per_grid, grad_threads_per_block, stream, 0]( grads, x_c, denom, alphas, betas, llForward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, fastemit_lambda, clamp, ) # sync kernel stream.synchronize() # reshape grads grads = grads.view([B, T, U, V]) diff = true_grads - grads[0].cpu().numpy() assert np.abs(diff).mean() <= 1e-5 assert np.square(diff).mean() <= 1e-10 @pytest.mark.skipif(not cuda.is_available(), reason="CUDA Reductions can only be run when CUDA is available") @pytest.mark.unit def test_compute_grads_kernel_fastemit(self): numba_utils.skip_numba_cuda_test_if_unsupported(__NUMBA_MINIMUM_VERSION__) fastemit_lambda = 0.001 clamp = 0.0 random = np.random.RandomState(0) original_shape = [1, 5, 11, 3] B, T, U, V = original_shape # Numpy kernel x = random.randn(*original_shape) labels = torch.from_numpy(np.array([[1, 1, 1, 2, 2, 2, 1, 2, 2, 1]], dtype=np.int32)) # [1, 10] audio_len = torch.from_numpy(np.array([T], dtype=np.int32)) label_len = torch.from_numpy(np.array([U - 1], dtype=np.int32)) blank_idx = 0 x_np = torch.from_numpy(x) x_np.requires_grad_(True) """ Here we will directly utilize the numpy variant of the loss without explicitly calling the numpy functions for alpha, beta and grads. This is because the grads returned by the rnnt_numpy.transduce_batch() are : d/dx (alpha + beta alignment)(log_softmax(x)). But according to the chain rule, we'd still need to compute the gradient of log_softmax(x) and update the alignments by hand. Instead, we will rely on pytorch to compute the gradient of the log_softmax(x) step and propagate it backwards. """ loss_func = rnnt_numpy.RNNTLoss(blank_idx, fastemit_lambda=fastemit_lambda, clamp=clamp) loss_val = loss_func(x_np, labels, audio_len, label_len) loss_val.sum().backward() true_grads = x_np.grad # Pytorch kernel device = torch.device('cuda') if hasattr(cuda, 'external_stream'): stream = cuda.external_stream(torch.cuda.current_stream(device).cuda_stream) else: stream = cuda.default_stream() x_c = torch.tensor(x, device=device, dtype=torch.float32) labels_c = torch.tensor(labels, device=device, dtype=torch.int32) # Allocate workspace memory denom = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) alphas = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) betas = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) llForward = torch.zeros(B, device=device, dtype=x_c.dtype) llBackward = torch.zeros(B, device=device, dtype=x_c.dtype) input_lengths = torch.tensor([T], dtype=torch.int32, device=device) label_lengths = torch.tensor([len(labels[0])], dtype=torch.int32, device=device) # certify input data certify_inputs(x_c, labels_c, input_lengths, label_lengths) # flatten activation tensor (for pointer based indexing) x_c = x_c.view([-1]) grads = torch.zeros_like(x_c, requires_grad=False) # call kernel # log softmax reduction reduce.reduce_max(x_c, denom, rows=V, cols=B * T * U, minus=False, stream=stream) reduce.reduce_exp(x_c, denom, rows=V, cols=B * T * U, minus=True, stream=stream) # alpha kernel gpu_rnnt_kernel.compute_alphas_kernel[B, U, stream, 0]( x_c, denom, alphas, llForward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, ) # beta kernel gpu_rnnt_kernel.compute_betas_kernel[B, U, stream, 0]( x_c, denom, betas, llBackward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, ) # gamma kernel grad_blocks_per_grid = B * T * U grad_threads_per_block = gpu_rnnt_kernel.GPU_RNNT_THREAD_SIZE gpu_rnnt_kernel.compute_grad_kernel[grad_blocks_per_grid, grad_threads_per_block, stream, 0]( grads, x_c, denom, alphas, betas, llForward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, fastemit_lambda, clamp, ) # sync kernel stream.synchronize() # reshape grads grads = grads.view([B, T, U, V]) diff = true_grads - grads[0].cpu().numpy() assert np.abs(diff).mean() <= 1e-5 assert np.square(diff).mean() <= 1e-10 @pytest.mark.skipif(not cuda.is_available(), reason="CUDA Reductions can only be run when CUDA is available") @pytest.mark.unit def test_compute_grads_kernel_clamp(self): numba_utils.skip_numba_cuda_test_if_unsupported(__NUMBA_MINIMUM_VERSION__) fastemit_lambda = 0.0 clamp = 0.1 random = np.random.RandomState(0) original_shape = [1, 5, 11, 3] B, T, U, V = original_shape # Numpy kernel x = random.randn(*original_shape) labels = torch.from_numpy(np.array([[1, 1, 1, 2, 2, 2, 1, 2, 2, 1]], dtype=np.int32)) # [1, 10] audio_len = torch.from_numpy(np.array([T], dtype=np.int32)) label_len = torch.from_numpy(np.array([U - 1], dtype=np.int32)) blank_idx = 0 x_np = torch.from_numpy(x) x_np.requires_grad_(True) """ Here we will directly utilize the numpy variant of the loss without explicitly calling the numpy functions for alpha, beta and grads. This is because the grads returned by the rnnt_numpy.transduce_batch() are : d/dx (alpha + beta alignment)(log_softmax(x)). But according to the chain rule, we'd still need to compute the gradient of log_softmax(x) and update the alignments by hand. Instead, we will rely on pytorch to compute the gradient of the log_softmax(x) step and propagate it backwards. """ loss_func = rnnt_numpy.RNNTLoss(blank_idx, fastemit_lambda=fastemit_lambda, clamp=clamp) loss_val = loss_func(x_np, labels, audio_len, label_len) loss_val.sum().backward() true_grads = x_np.grad # Pytorch kernel device = torch.device('cuda') if hasattr(cuda, 'external_stream'): stream = cuda.external_stream(torch.cuda.current_stream(device).cuda_stream) else: stream = cuda.default_stream() x_c = torch.tensor(x, device=device, dtype=torch.float32) labels_c = torch.tensor(labels, device=device, dtype=torch.int32) # Allocate workspace memory denom = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) alphas = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) betas = torch.zeros(B * T * U, device=device, dtype=x_c.dtype) llForward = torch.zeros(B, device=device, dtype=x_c.dtype) llBackward = torch.zeros(B, device=device, dtype=x_c.dtype) input_lengths = torch.tensor([T], dtype=torch.int32, device=device) label_lengths = torch.tensor([len(labels[0])], dtype=torch.int32, device=device) # certify input data certify_inputs(x_c, labels_c, input_lengths, label_lengths) # flatten activation tensor (for pointer based indexing) x_c = x_c.view([-1]) grads = torch.zeros_like(x_c, requires_grad=False) # call kernel # log softmax reduction reduce.reduce_max(x_c, denom, rows=V, cols=B * T * U, minus=False, stream=stream) reduce.reduce_exp(x_c, denom, rows=V, cols=B * T * U, minus=True, stream=stream) # alpha kernel gpu_rnnt_kernel.compute_alphas_kernel[B, U, stream, 0]( x_c, denom, alphas, llForward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, ) # beta kernel gpu_rnnt_kernel.compute_betas_kernel[B, U, stream, 0]( x_c, denom, betas, llBackward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, ) # gamma kernel grad_blocks_per_grid = B * T * U grad_threads_per_block = gpu_rnnt_kernel.GPU_RNNT_THREAD_SIZE gpu_rnnt_kernel.compute_grad_kernel[grad_blocks_per_grid, grad_threads_per_block, stream, 0]( grads, x_c, denom, alphas, betas, llForward, input_lengths, label_lengths, labels_c, B, T, U, V, blank_idx, fastemit_lambda, clamp, ) # sync kernel stream.synchronize() # reshape grads grads = grads.view([B, T, U, V]) diff = true_grads - grads[0].cpu().numpy() assert np.abs(diff).mean() <= 1e-5 assert np.square(diff).mean() <= 1e-10
#!/usr/bin/env python3 from pathlib import Path from typing import Any, Dict import jinja2 from aiohttp import web from aiohttp_jinja2 import setup as jinja2_setup, template from aiohttp_session import SimpleCookieStorage, get_session, setup as session_setup from aiohttp_oauth2.client.app import oauth2_app from functools import partial from aiohttp_oauth2.client.contrib import dataporten @template("index.html") async def index(request: web.Request) -> Dict[str, Any]: session = await get_session(request) return {"user": session.get("user")} async def logout(request: web.Request): session = await get_session(request) session.invalidate() return web.HTTPTemporaryRedirect(location="/") async def on_dataporten_login(request: web.Request, dataporten_token): session = await get_session(request) #https://docs.feide.no/developer_oauth/technical_details/oauth_scopes.html?highlight=openid%20userinfo async with request.app["session"].get( "https://auth.dataporten.no/openid/userinfo", headers={"Authorization": f"Bearer {dataporten_token['access_token']}"}, ) as r: session["user"] = await r.json() print(session["user"]) #https://docs.feide.no/developer_oauth/technical_details/groups_api.html?highlight=oauth%20authorization async with request.app["session"].get( "https://groups-api.dataporten.no/groups/me/groups", headers={"Authorization": f"Bearer {dataporten_token['access_token']}"}, ) as r: session["groups"] = await r.json() print(session["groups"]) return web.HTTPTemporaryRedirect(location="/") #make sure to define redirect uri in dataporten dashboard. FEIDE_CLIENT_ID = 'xxx' FEIDE_CLIENT_SECRET = 'xyx' def app_factory() -> web.Application: app = web.Application() jinja2_setup( app, loader=jinja2.FileSystemLoader([Path(__file__).parent / "templates"]) ) session_setup(app, SimpleCookieStorage()) app.add_subapp( "/auth/dataporten/", dataporten( FEIDE_CLIENT_ID, FEIDE_CLIENT_SECRET, on_login=on_dataporten_login, scopes = ['profile', 'userid', 'openid', 'groups', 'peoplesearch', 'email', 'userid-feide'], json_data=False, ), ) app.add_routes([web.get("/", index), web.get("/auth/logout", logout)]) return app if __name__ == "__main__": web.run_app(app_factory())
#!/usr/bin/python # -*- coding: utf-8 -*- # VideoColorSpace for Dreambox-Enigma2 # # Coded by cmikula (c)2012 # Support: www.i-have-a-dreambox.com # # This plugin is licensed under the Creative Commons # Attribution-NonCommercial-ShareAlike 3.0 Unported # License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc-sa/3.0/ or send a letter to Creative # Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. # # Alternatively, this plugin may be distributed and executed on hardware which # is licensed by Dream Multimedia GmbH. # # This plugin is NOT free software. It is open source, you are allowed to # modify it (if you keep the license), but it may not be commercially # distributed other than under the conditions noted above. # from __future__ import print_function from __future__ import absolute_import from .__init__ import _ from Components.config import config from Plugins.Plugin import PluginDescriptor from .VideoColorSpace import VideoColorSpace, initializeConfig from boxbranding import getImageDistro def autostart(reason, **kwargs): if reason == 0: print("[VideoColorSpace] startup...") initializeConfig() def pluginOpen(session, **kwargs): session.open(VideoColorSpace) def startSetup(menuid): if getImageDistro() in ('openhdf'): if menuid != "video_menu": return [] else: if menuid != "system": return [] return [(_("A/V-Color space settings"), pluginOpen, "av_colorspace_setup", 40)] def Plugins(**kwargs): descriptors = [] if config.usage.setup_level.index >= 2: descriptors.append(PluginDescriptor(name=_("Color space setup"), description=_("Setup color space for video"), where=PluginDescriptor.WHERE_SESSIONSTART, fnc=autostart)) descriptors.append(PluginDescriptor(name=_("Color space setup"), description=_("Setup color space for video"), where=PluginDescriptor.WHERE_MENU, fnc=startSetup)) return descriptors
from nextcord.ext.commands.errors import CheckFailure class NotConnectedToVoice(CheckFailure): """User not connected to any voice channel""" pass class PlayerNotConnected(CheckFailure): """Player not connected""" pass class MustBeSameChannel(CheckFailure): """Player and user not in same channel""" pass class NothingIsPlaying(CheckFailure): """Nothing is playing""" pass class NotEnoughSong(CheckFailure): """Not enough songs in queue""" pass class InvalidLoopMode(CheckFailure): """Invalid loop mode""" pass
import numpy as np from collections import defaultdict from formulagen.formula import as_str from formulagen.formula import as_tree from formulagen.formula import gen_formula_tree from formulagen.formula import Unit from formulagen.formula import Node def count(): return defaultdict(int) class TreeGram: def __init__(self, min_gram=1, max_gram=5): self.min_gram = min_gram self.max_gram = max_gram self._counts = defaultdict(count) self._nb_children = defaultdict(count) self.vocab_ = set() def fit(self, corpus): self.vocab_ = set() for doc in corpus: tree = as_tree(doc) _count(tree, counts=self._counts, vocab=self.vocab_, nb_children=self._nb_children, min_gram=self.min_gram, max_gram=self.max_gram) self.vocab_ = list(self.vocab_) def generate(self, rng, max_size=10): tree = _generate(self._counts, self.vocab_, self._nb_children, min_gram=self.min_gram, max_gram=self.max_gram, rng=rng) return as_str(tree) def _count(root, counts, vocab, nb_children, child_idx=None, min_gram=1, max_gram=5): def _tree_count(t, context=tuple(), child_idx=0): if len(context) == 0: counts[(None, context)][t.label] += 1 # root # others first = min_gram last = min(max_gram, len(context)) for i in range(first, last + 1): ctx = context[len(context) - i:] counts[(child_idx, ctx)][t.label] += 1 if t.left and t.right: children = [t.left, t.right] elif t.left: children = [t.left] else: children = [] nb_children[t.label][len(children)] += 1 vocab.add(t.label) for ic, c in enumerate(children): _tree_count(c, context=context + (t.label,), child_idx=ic) return _tree_count(root) def _generate(counts, vocab, nb_children, child_idx=None, min_gram=1, max_gram=2, rng=np.random): def _gen_tree(context=tuple(), child_idx=None): if child_idx is None: #root found = (None, context) in counts ctx = context else:#others first = min_gram last = min(max_gram, len(context)) degs = reversed(range(first, last + 1)) degs = list(degs) found = False for i in degs: ctx = context[len(context) - i:] if (child_idx, ctx) in counts: found = True break if found: cnt = counts[(child_idx, ctx)] label = _sample(cnt, rng) else: label = rng.choice(vocab) nb = _sample(nb_children[label], rng) children = [] for idx in range(nb): child = _gen_tree(context=context + (label,), child_idx=idx) children.append(child) if len(children) == 2: left, right = children elif len(children) == 1: left, = children right = None else: left = None right = None return Node(label=label, left=left, right=right, unit=None) return _gen_tree() def _sample(counts, rng): labels = list(counts.keys()) probas = list(counts.values()) probas = np.array(probas).astype(np.float32) probas /= probas.sum() label_idx = rng.multinomial(1, probas).argmax() label = labels[label_idx] return label if __name__ == '__main__': import pandas as pd df = pd.read_csv('instances/67e6bff2-4dd0-4d43-b140-b57f21e06c60/out/formulas.csv') corpus = df['formula'] print(sum(map(len, corpus)) / len(corpus)) model = TreeGram(min_gram=1, max_gram=10) model.fit(corpus) gen = [] for i in range(1000): gen.append(model.generate()) print(sum(map(len, gen)) / len(gen))
from data_detective_airflow.operators.extractors.db_dump import DBDump from data_detective_airflow.operators.extractors.python_dump import PythonDump from data_detective_airflow.operators.extractors.request_dump import RequestDump from data_detective_airflow.operators.extractors.s3_dump import S3Dump from data_detective_airflow.operators.extractors.s3_list_bucket import S3ListBucket from data_detective_airflow.operators.extractors.tsftpoperator import TSFTPOperator from data_detective_airflow.operators.sinks.pg_scd1 import PgSCD1 from data_detective_airflow.operators.sinks.pg_scd1_df_update_insert import PgSCD1DFUpdateInsert from data_detective_airflow.operators.sinks.pg_scd1 import LoadingMethod from data_detective_airflow.operators.sinks.pg_single_target_loader import PgSingleTargetLoader from data_detective_airflow.operators.sinks.pg_single_target_utils import filter_for_breadcrumb from data_detective_airflow.operators.sinks.pg_single_target_utils import filter_for_entity from data_detective_airflow.operators.sinks.pg_single_target_utils import filter_for_relation from data_detective_airflow.operators.sinks.s3_delete import S3Delete from data_detective_airflow.operators.sinks.s3_load import S3Load from data_detective_airflow.operators.transformers.append import Append from data_detective_airflow.operators.transformers.pg_sql import PgSQL from data_detective_airflow.operators.transformers.py_transform import PyTransform upload_mg_entity = PgSingleTargetLoader.upload_dds_entity upload_mg_relation = PgSingleTargetLoader.upload_dds_relation __all__ = ( 'DBDump', 'PythonDump', 'RequestDump', 'S3Dump', 'S3ListBucket', 'TSFTPOperator', 'Append', 'PgSCD1', 'LoadingMethod', 'PgSingleTargetLoader', 'PgSCD1DFUpdateInsert', 'filter_for_breadcrumb', 'filter_for_entity', 'filter_for_relation', 'S3Delete', 'S3Load', 'PgSQL', 'PyTransform', 'upload_mg_entity', 'upload_mg_relation', )
import os from pydub.utils import make_chunks from pydub import AudioSegment chunk_size = 60000 #millisecs ragas = ['Kapi', 'Mayamalavagowla', 'Harikambhoji', 'Kharaharapriya', 'Nattai', 'Bilahari', 'Charukesi', 'Abheri', 'Kamas', 'Behag'] def split_audio_files(): file_number = 0 for file in os.listdir(os.getcwd()): if file.endswith(".mp3"): file_number = file_number + 1 audio = AudioSegment.from_file(file, format="mp3") for i, chunk in enumerate(make_chunks(audio, chunk_size)): for j, ragam in enumerate(ragas): if ragam in file: filename = ragam + "-" + str(file_number) + "-" + str(i + 1) + ".wav" print("exporting " + filename) os.chdir(os.getcwd() + "/finaldata") chunk.export(filename, format="wav") os.chdir('../') if __name__ == "__main__": split_audio_files() else: print("Well, you are importing this, aren't you?")
# =============================================================================== # Program : iterative_vasp_run.py # Author : Hyeongseon Park # must be run in the main_dataset directory!! # This code iteratively runs "vasp_run.sh" using "qsub" command in super-computing # server in NURION (by KISTI) # =============================================================================== # ------------------ Library import ------------------------- import os import shutil import glob from tqdm import tqdm # ------------------ sub-directory list ------------------------- path = './*' file_list = glob.glob(path) dir_list = [element for element in file_list if os.path.isdir(element)] # 계산 디렉터리 리스트 추출 dir_list_sorted = sorted(dir_list) # 정렬 # ------------------ Calculation Number ------------------------- # Sub-Directory Number-Parameter : from START -> to END # 주의! 한번에 qsub 명령으로 제출할 수 있는 job의 수는 최대 40개! # 주의! 한번에 qsub 명령으로 연산할 수 있는 job의 수는 최대 20개! END = 40 START = END - 40 # ---------------------------------------------------------------- for each_dir in tqdm( dir_list_sorted[START:END] ): os.chdir(path = each_dir) # 계산 서브디렉터리 들어가고 os.system('qsub vasp_run.sh') # qsub 명령 실행 os.chdir(path = '../') # 이전 디렉터리로 다시 나옴. # 경고! : qsub 명령으로 연산실행되면, 그 디렉터리 위치를 함부로 바꿀 경우 경로를 찾지 못해 Error 발생! # 이전 단계인 3단계 코드 : prepare_sub_directory.py에서 미리 앞에 인덱스 붙이는 정도가 적당할 듯 하다... # ============================================ END ================================================
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """TensorFlow NMT model implementation.""" from __future__ import print_function import argparse import os import random import sys import subprocess # import matplotlib.image as mpimg import numpy as np import time import tensorflow as tf import estimator from utils import evaluation_utils from utils import iterator_utils from utils import misc_utils as utils from utils import vocab_utils from variable_mgr import constants utils.check_tensorflow_version() FLAGS = None # LINT.IfChange def add_arguments(parser): """Build ArgumentParser.""" parser.register("type", "bool", lambda v: v.lower() == "true") # NPU config parser.add_argument( "--use_npu", type=bool, default=True, help="whether to use NPU.") parser.add_argument( "--cast_output_layer", type=bool, default=True, help="whether to cast the last layer output_projection and beam search to fp16.") parser.add_argument( "--data_shuffle", type=bool, default=False, help="whether to shuffle data.") parser.add_argument( "--use_npu_distribution", type=bool, default=False, help="whether to use npu_distribution(8p).") # network parser.add_argument( "--num_units", type=int, default=1024, help="Network size.") parser.add_argument( "--num_layers", type=int, default=4, help="Network depth.") parser.add_argument("--num_encoder_layers", type=int, default=None, help="Encoder depth, equal to num_layers if None.") parser.add_argument("--num_decoder_layers", type=int, default=None, help="Decoder depth, equal to num_layers if None.") parser.add_argument( "--encoder_type", type=str, default="gnmt", help="""\ uni | bi | gnmt. For bi, we build num_encoder_layers/2 bi-directional layers. For gnmt, we build 1 bi-directional layer, and (num_encoder_layers - 1) uni-directional layers.\ """) parser.add_argument( "--residual", type="bool", nargs="?", const=True, default=True, help="Whether to add residual connections.") parser.add_argument("--time_major", type="bool", nargs="?", const=True, default=True, help="Whether to use time-major mode for dynamic RNN.") parser.add_argument("--num_embeddings_partitions", type=int, default=0, help="Number of partitions for embedding vars.") # attention mechanisms parser.add_argument( "--attention", type=str, default="normed_bahdanau", help="""\ luong | scaled_luong | bahdanau | normed_bahdanau or set to "" for no attention\ """) parser.add_argument( "--attention_architecture", type=str, default="gnmt_v2", help="""\ standard | gnmt | gnmt_v2. standard: use top layer to compute attention. gnmt: GNMT style of computing attention, use previous bottom layer to compute attention. gnmt_v2: similar to gnmt, but use current bottom layer to compute attention.\ """) parser.add_argument( "--output_attention", type="bool", nargs="?", const=True, default=True, help="""\ Only used in standard attention_architecture. Whether use attention as the cell output at each timestep. .\ """) parser.add_argument( "--pass_hidden_state", type="bool", nargs="?", const=True, default=True, help="""\ Whether to pass encoder's hidden state to decoder when using an attention based model.\ """) # optimizer parser.add_argument( "--optimizer", type=str, default="adam", help="sgd | adam") parser.add_argument( "--learning_rate", type=float, default=5e-4, help="Learning rate. Adam: 0.001 | 0.0001") parser.add_argument("--warmup_steps", type=int, default=200, help="How many steps we inverse-decay learning.") parser.add_argument("--warmup_scheme", type=str, default="t2t", help="""\ How to warmup learning rates. Options include: t2t: Tensor2Tensor's way, start with lr 100 times smaller, then exponentiate until the specified lr.\ """) parser.add_argument( "--decay_scheme", type=str, default="luong234", help="""\ How we decay learning rate. Options include: luong234: after 2/3 num train steps, we start halving the learning rate for 4 times before finishing. luong5: after 1/2 num train steps, we start halving the learning rate for 5 times before finishing.\ luong10: after 1/2 num train steps, we start halving the learning rate for 10 times before finishing.\ """) parser.add_argument( "--max_train_epochs", type=int, default=6, help="Max number of epochs.") parser.add_argument( "--target_bleu", type=float, default=None, help="Target bleu.") parser.add_argument("--colocate_gradients_with_ops", type="bool", nargs="?", const=True, default=True, help=("Whether try colocating gradients with " "corresponding op")) parser.add_argument("--label_smoothing", type=float, default=0.1, help=("If nonzero, smooth the labels towards " "1/num_classes.")) # initializer parser.add_argument("--init_op", type=str, default="uniform", help="uniform | glorot_normal | glorot_uniform") parser.add_argument("--init_weight", type=float, default=0.1, help=("for uniform init_op, initialize weights " "between [-this, this].")) # data parser.add_argument( "--src", type=str, default="en", help="Source suffix, e.g., en.") parser.add_argument( "--tgt", type=str, default="de", help="Target suffix, e.g., de.") parser.add_argument( "--data_dir", type=str, default="data/wmt16_de_en", help="Training/eval data directory.") parser.add_argument( "--train_prefix", type=str, default="train.tok.clean.bpe.32000", help="Train prefix, expect files with src/tgt suffixes.") parser.add_argument( "--test_prefix", type=str, default="newstest2014.tok.bpe.32000", help="Test prefix, expect files with src/tgt suffixes.") parser.add_argument( "--translate_file", default="file.txt", type=str, help="File to translate, works only with translate mode") parser.add_argument( "--output_dir", type=str, default="results", help="Store log/model files.") # Vocab parser.add_argument( "--vocab_prefix", type=str, default="vocab.bpe.32000", help="""\ Vocab prefix, expect files with src/tgt suffixes.\ """) parser.add_argument( "--embed_prefix", type=str, default=None, help="""\ Pretrained embedding prefix, expect files with src/tgt suffixes. The embedding files should be Glove formatted txt files.\ """) parser.add_argument("--sos", type=str, default="<s>", help="Start-of-sentence symbol.") parser.add_argument("--eos", type=str, default="</s>", help="End-of-sentence symbol.") parser.add_argument( "--share_vocab", type="bool", nargs="?", const=True, default=True, help="""\ Whether to use the source vocab and embeddings for both source and target.\ """) parser.add_argument("--check_special_token", type="bool", default=True, help="""\ Whether check special sos, eos, unk tokens exist in the vocab files.\ """) # Sequence lengths parser.add_argument( "--src_max_len", type=int, default=50, help="Max length of src sequences during training (including EOS).") parser.add_argument( "--tgt_max_len", type=int, default=50, help="Max length of tgt sequences during training (including BOS).") parser.add_argument("--src_max_len_infer", type=int, default=None, help="Max length of src sequences during inference (including EOS).") parser.add_argument("--tgt_max_len_infer", type=int, default=80, help="""\ Max length of tgt sequences during inference (including BOS). Also use to restrict the maximum decoding length.\ """) # Default settings works well (rarely need to change) parser.add_argument("--unit_type", type=str, default="lstm", help="lstm | gru | layer_norm_lstm | nas") parser.add_argument("--forget_bias", type=float, default=0.0, help="Forget bias for BasicLSTMCell.") parser.add_argument("--dropout", type=float, default=0.0, help="Dropout rate (not keep_prob)") parser.add_argument("--max_gradient_norm", type=float, default=5.0, help="Clip gradients to this norm.") parser.add_argument("--batch_size", type=int, default=1, help="Total batch size.") parser.add_argument( "--num_buckets", type=int, default=5, help="Put data into similar-length buckets (only for training).") # SPM parser.add_argument("--subword_option", type=str, default="bpe", choices=["", "bpe", "spm"], help="""\ Set to bpe or spm to activate subword desegmentation.\ """) # Experimental encoding feature. parser.add_argument("--use_char_encode", type="bool", default=False, help="""\ Whether to split each word or bpe into character, and then generate the word-level representation from the character reprentation. """) # Misc parser.add_argument( "--save_checkpoints_steps", type=int, default=6000, help="save_checkpoints_steps") parser.add_argument( "--log_step_count_steps", type=int, default=1, help=("The frequency, in number of global steps, that the global step " "and the loss will be logged during training")) parser.add_argument( "--num_gpus", type=int, default=1, help="Number of gpus in each worker.") parser.add_argument("--hparams_path", type=str, default=None, help=("Path to standard hparams json file that overrides" "hparams values from FLAGS.")) parser.add_argument( "--random_seed", type=int, default=1, help="Random seed (>0, set a specific seed).") parser.add_argument("--language_model", type="bool", nargs="?", const=True, default=False, help="True to train a language model, ignoring encoder") # Inference parser.add_argument("--ckpt", type=str, default=None, help="Checkpoint file to load a model for inference. (defaults to newest checkpoint)") parser.add_argument( "--infer_batch_size", type=int, default=128, help="Batch size for inference mode.") parser.add_argument("--detokenizer_file", type=str, default=None, help=("""Detokenizer script file. Default: DATA_DIR/mosesdecoder/scripts/tokenizer/detokenizer.perl""")) parser.add_argument("--tokenizer_file", type=str, default=None, help=("""Tokenizer script file. Default: DATA_DIR/mosesdecoder/scripts/tokenizer/tokenizer.perl""")) # Advanced inference arguments parser.add_argument("--infer_mode", type=str, default="beam_search", choices=["greedy", "beam_search"], help="Which type of decoder to use during inference.") parser.add_argument("--beam_width", type=int, default=5, help=("""\ beam width when using beam search decoder. If 0, use standard decoder with greedy helper.\ """)) parser.add_argument( "--length_penalty_weight", type=float, default=0.6, help="Length penalty for beam search.") parser.add_argument( "--coverage_penalty_weight", type=float, default=0.1, help="Coverage penalty for beam search.") # Job info parser.add_argument("--num_workers", type=int, default=1, help="Number of workers (inference only).") parser.add_argument("--use_amp", type="bool", default=True, help="use_amp for training and inference") parser.add_argument("--use_fastmath", type="bool", default=False, help="use_fastmath for training and inference") parser.add_argument("--use_fp16", type="bool", default=False, help="use_fp16 for training and inference") parser.add_argument( "--fp16_loss_scale", type=float, default=128, help="If fp16 is enabled, the loss is multiplied by this amount " "right before gradients are computed, then each gradient " "is divided by this amount. Mathematically, this has no " "effect, but it helps avoid fp16 underflow. Set to 1 to " "effectively disable.") parser.add_argument( "--enable_auto_loss_scale", type="bool", default=True, help="If True and use_fp16 is True, automatically adjust the " "loss scale during training.") parser.add_argument( "--fp16_inc_loss_scale_every_n", type=int, default=128, help="If fp16 is enabled and enable_auto_loss_scale is " "True, increase the loss scale every n steps.") parser.add_argument( "--check_tower_loss_numerics", type="bool", default=False, # Set to false for xla.compile() help="whether to check tower loss numerics") parser.add_argument( "--use_fp32_batch_matmul", type="bool", default=False, help="Whether to use fp32 batch matmul") # Performance # XLA parser.add_argument( "--force_inputs_padding", type="bool", default=False, help="Force padding input batch to src_max_len and tgt_max_len") parser.add_argument( "--use_xla", type="bool", default=False, help="Use xla to compile a few selected locations, mostly Defuns.") parser.add_argument( "--xla_compile", type="bool", default=False, help="Use xla.compile() for each tower's fwd and bak pass.") parser.add_argument( "--use_autojit_xla", type="bool", default=False, help="Use auto jit xla.") # GPU knobs parser.add_argument( "--use_pintohost_optimizer", type="bool", default=False, help="whether to use PinToHost optimizer") parser.add_argument( "--use_cudnn_lstm", type="bool", default=False, help="whether to use cudnn_lstm for encoder, non residual layers") parser.add_argument( "--use_loose_bidi_cudnn_lstm", type="bool", default=False, help="whether to use loose bidi cudnn_lstm") parser.add_argument( "--use_fused_lstm", type="bool", default=False, help="whether to use fused lstm and variant. If enabled, training will " "use LSTMBlockFusedCell, infer will use LSTMBlockCell when appropriate.") parser.add_argument( "--use_fused_lstm_dec", type="bool", default=False, help="whether to use fused lstm for decoder (training only).") parser.add_argument( "--gpu_indices", type=str, default="", help="Indices of worker GPUs in ring order") # Graph knobs parser.add_argument("--parallel_iterations", type=int, default=10, help="number of parallel iterations in dynamic_rnn") parser.add_argument("--use_dist_strategy", type="bool", default=False, help="whether to use distribution strategy") parser.add_argument( "--hierarchical_copy", type="bool", default=False, help="Use hierarchical copies. Currently only optimized for " "use on a DGX-1 with 8 GPUs and may perform poorly on " "other hardware. Requires --num_gpus > 1, and only " "recommended when --num_gpus=8") parser.add_argument( "--network_topology", type=constants.NetworkTopology, default=constants.NetworkTopology.DGX1, choices=list(constants.NetworkTopology)) parser.add_argument( "--use_block_lstm", type="bool", default=False, help="whether to use block lstm") parser.add_argument( "--use_defun", type="bool", default=False, help="whether to use Defun") # Gradient tricks parser.add_argument( "--gradient_repacking", type=int, default=0, help="Use gradient repacking. It" "currently only works with replicated mode. At the end of" "of each step, it repacks the gradients for more efficient" "cross-device transportation. A non-zero value specifies" "the number of split packs that will be formed.") parser.add_argument( "--compact_gradient_transfer", type="bool", default=True, help="Compact gradient as much as possible for cross-device transfer and " "aggregation.") parser.add_argument( "--all_reduce_spec", type=str, default="nccl", help="A specification of the all_reduce algorithm to be used " "for reducing gradients. For more details, see " "parse_all_reduce_spec in variable_mgr.py. An " "all_reduce_spec has BNF form:\n" "int ::= positive whole number\n" "g_int ::= int[KkMGT]?\n" "alg_spec ::= alg | alg#int\n" "range_spec ::= alg_spec | alg_spec/alg_spec\n" "spec ::= range_spec | range_spec:g_int:range_spec\n" "NOTE: not all syntactically correct constructs are " "supported.\n\n" "Examples:\n " "\"xring\" == use one global ring reduction for all " "tensors\n" "\"pscpu\" == use CPU at worker 0 to reduce all tensors\n" "\"nccl\" == use NCCL to locally reduce all tensors. " "Limited to 1 worker.\n" "\"nccl/xring\" == locally (to one worker) reduce values " "using NCCL then ring reduce across workers.\n" "\"pscpu:32k:xring\" == use pscpu algorithm for tensors of " "size up to 32kB, then xring for larger tensors.") parser.add_argument( "--agg_small_grads_max_bytes", type=int, default=0, help="If > 0, try to aggregate tensors of less than this " "number of bytes prior to all-reduce.") parser.add_argument( "--agg_small_grads_max_group", type=int, default=10, help="When aggregating small tensors for all-reduce do not " "aggregate more than this many into one new tensor.") parser.add_argument( "--allreduce_merge_scope", type=int, default=1, help="Establish a name scope around this many " "gradients prior to creating the all-reduce operations. " "It may affect the ability of the backend to merge " "parallel ops.") # Other knobs parser.add_argument( "--local_parameter_device", type=str, default="gpu", help="Device to use as parameter server: cpu or gpu. For " "distributed training, it can affect where caching of " "variables happens.") parser.add_argument( "--use_resource_vars", type="bool", default=False, help="Use resource variables instead of normal variables. " "Resource variables are slower, but this option is useful " "for debugging their performance.") parser.add_argument("--debug", type="bool", default=False, help="Debug train and eval") parser.add_argument( "--debug_num_train_steps", type=int, default=None, help="Num steps to train.") parser.add_argument("--show_metrics", type="bool", default=True, help="whether to show detailed metrics") parser.add_argument("--clip_grads", type="bool", default=True, help="whether to clip gradients") parser.add_argument("--profile", type="bool", default=False, help="If generate profile") parser.add_argument("--profile_save_steps", type=int, default=10, help="Save timeline every N steps.") parser.add_argument("--use_dynamic_rnn", type="bool", default=True) parser.add_argument("--use_synthetic_data", type="bool", default=False) parser.add_argument( "--mode", type=str, default="train_and_eval", choices=("train_and_eval", "infer", "translate")) def create_hparams(flags): """Create training hparams.""" return tf.contrib.training.HParams( # Data src=flags.src, tgt=flags.tgt, train_prefix=os.path.join(flags.data_dir, flags.train_prefix), test_prefix=os.path.join(flags.data_dir, flags.test_prefix), translate_file=flags.translate_file, vocab_prefix=os.path.join(flags.data_dir, flags.vocab_prefix), embed_prefix=flags.embed_prefix, output_dir=flags.output_dir, # Networks num_units=flags.num_units, num_encoder_layers=(flags.num_encoder_layers or flags.num_layers), num_decoder_layers=(flags.num_decoder_layers or flags.num_layers), dropout=flags.dropout, unit_type=flags.unit_type, encoder_type=flags.encoder_type, residual=flags.residual, time_major=flags.time_major, num_embeddings_partitions=flags.num_embeddings_partitions, # Attention mechanisms attention=flags.attention, attention_architecture=flags.attention_architecture, output_attention=flags.output_attention, pass_hidden_state=flags.pass_hidden_state, # Train optimizer=flags.optimizer, max_train_epochs=flags.max_train_epochs, target_bleu=flags.target_bleu, label_smoothing=flags.label_smoothing, batch_size=flags.batch_size, init_op=flags.init_op, init_weight=flags.init_weight, max_gradient_norm=flags.max_gradient_norm, learning_rate=flags.learning_rate, warmup_steps=flags.warmup_steps, warmup_scheme=flags.warmup_scheme, decay_scheme=flags.decay_scheme, colocate_gradients_with_ops=flags.colocate_gradients_with_ops, # Data constraints num_buckets=flags.num_buckets, src_max_len=flags.src_max_len, tgt_max_len=flags.tgt_max_len, # Inference src_max_len_infer=flags.src_max_len_infer, tgt_max_len_infer=flags.tgt_max_len_infer, ckpt=flags.ckpt, infer_batch_size=flags.infer_batch_size, detokenizer_file=flags.detokenizer_file if flags.detokenizer_file is not None \ else os.path.join(flags.data_dir, 'mosesdecoder/scripts/tokenizer/detokenizer.perl'), tokenizer_file=flags.tokenizer_file if flags.tokenizer_file is not None \ else os.path.join(flags.data_dir, 'mosesdecoder/scripts/tokenizer/tokenizer.perl'), # Advanced inference arguments infer_mode=flags.infer_mode, beam_width=flags.beam_width, length_penalty_weight=flags.length_penalty_weight, coverage_penalty_weight=flags.coverage_penalty_weight, # Vocab sos=flags.sos if flags.sos else vocab_utils.SOS, eos=flags.eos if flags.eos else vocab_utils.EOS, subword_option=flags.subword_option, check_special_token=flags.check_special_token, use_char_encode=flags.use_char_encode, # Misc forget_bias=flags.forget_bias, num_gpus=flags.num_gpus, save_checkpoints_steps=flags.save_checkpoints_steps, log_step_count_steps=flags.log_step_count_steps, epoch_step=0, # record where we were within an epoch. share_vocab=flags.share_vocab, random_seed=flags.random_seed, language_model=flags.language_model, use_amp=flags.use_amp, use_fastmath=flags.use_fastmath, use_fp16=flags.use_fp16, fp16_loss_scale=flags.fp16_loss_scale, enable_auto_loss_scale=flags.enable_auto_loss_scale, fp16_inc_loss_scale_every_n=flags.fp16_inc_loss_scale_every_n, check_tower_loss_numerics=flags.check_tower_loss_numerics, use_fp32_batch_matmul=flags.use_fp32_batch_matmul, # Performance # GPU knbs force_inputs_padding=flags.force_inputs_padding, use_xla=flags.use_xla, xla_compile=flags.xla_compile, use_autojit_xla=flags.use_autojit_xla, use_pintohost_optimizer=flags.use_pintohost_optimizer, use_cudnn_lstm=flags.use_cudnn_lstm, use_loose_bidi_cudnn_lstm=flags.use_loose_bidi_cudnn_lstm, use_fused_lstm=flags.use_fused_lstm, use_fused_lstm_dec=flags.use_fused_lstm_dec, gpu_indices=flags.gpu_indices, # Graph knobs parallel_iterations=flags.parallel_iterations, use_dynamic_rnn=flags.use_dynamic_rnn, use_dist_strategy=flags.use_dist_strategy, hierarchical_copy=flags.hierarchical_copy, network_topology=flags.network_topology, use_block_lstm=flags.use_block_lstm, # Grad tricks gradient_repacking=flags.gradient_repacking, compact_gradient_transfer=flags.compact_gradient_transfer, all_reduce_spec=flags.all_reduce_spec, agg_small_grads_max_bytes=flags.agg_small_grads_max_bytes, agg_small_grads_max_group=flags.agg_small_grads_max_group, allreduce_merge_scope=flags.allreduce_merge_scope, # Other knobs local_parameter_device=("cpu" if flags.num_gpus ==0 else flags.local_parameter_device), use_resource_vars=flags.use_resource_vars, debug=flags.debug, debug_num_train_steps=flags.debug_num_train_steps, clip_grads=flags.clip_grads, profile=flags.profile, profile_save_steps=flags.profile_save_steps, show_metrics=flags.show_metrics, use_synthetic_data=flags.use_synthetic_data, mode=flags.mode, ) def _add_argument(hparams, key, value, update=True): """Add an argument to hparams; if exists, change the value if update==True.""" if hasattr(hparams, key): if update: setattr(hparams, key, value) else: hparams.add_hparam(key, value) def extend_hparams(hparams): """Add new arguments to hparams.""" # Sanity checks if hparams.encoder_type == "bi" and hparams.num_encoder_layers % 2 != 0: raise ValueError("For bi, num_encoder_layers %d should be even" % hparams.num_encoder_layers) if (hparams.attention_architecture in ["gnmt"] and hparams.num_encoder_layers < 2): raise ValueError("For gnmt attention architecture, " "num_encoder_layers %d should be >= 2" % hparams.num_encoder_layers) if hparams.subword_option and hparams.subword_option not in ["spm", "bpe"]: raise ValueError("subword option must be either spm, or bpe") if hparams.infer_mode == "beam_search" and hparams.beam_width <= 0: raise ValueError("beam_width must greater than 0 when using beam_search" "decoder.") if hparams.mode == "translate" and not hparams.translate_file: raise ValueError("--translate_file flag must be specified in translate mode") # Different number of encoder / decoder layers assert hparams.num_encoder_layers and hparams.num_decoder_layers if hparams.num_encoder_layers != hparams.num_decoder_layers: hparams.pass_hidden_state = False utils.print_out("Num encoder layer %d is different from num decoder layer" " %d, so set pass_hidden_state to False" % ( hparams.num_encoder_layers, hparams.num_decoder_layers)) # Set residual layers num_encoder_residual_layers = 0 num_decoder_residual_layers = 0 if hparams.residual: if hparams.num_encoder_layers > 1: num_encoder_residual_layers = hparams.num_encoder_layers - 1 if hparams.num_decoder_layers > 1: num_decoder_residual_layers = hparams.num_decoder_layers - 1 if hparams.encoder_type == "gnmt": # The first unidirectional layer (after the bi-directional layer) in # the GNMT encoder can't have residual connection due to the input is # the concatenation of fw_cell and bw_cell's outputs. num_encoder_residual_layers = hparams.num_encoder_layers - 2 # Compatible for GNMT models if hparams.num_encoder_layers == hparams.num_decoder_layers: num_decoder_residual_layers = num_encoder_residual_layers _add_argument(hparams, "num_encoder_residual_layers", num_encoder_residual_layers) _add_argument(hparams, "num_decoder_residual_layers", num_decoder_residual_layers) # Language modeling if hparams.language_model: hparams.attention = "" hparams.attention_architecture = "" hparams.pass_hidden_state = False hparams.share_vocab = True hparams.src = hparams.tgt utils.print_out("For language modeling, we turn off attention and " "pass_hidden_state; turn on share_vocab; set src to tgt.") ## Vocab # Get vocab file names first if hparams.vocab_prefix: src_vocab_file = hparams.vocab_prefix + "." + hparams.src tgt_vocab_file = hparams.vocab_prefix + "." + hparams.tgt else: raise ValueError("hparams.vocab_prefix must be provided.") # Source vocab src_vocab_size, src_vocab_file = vocab_utils.check_vocab( src_vocab_file, hparams.output_dir, check_special_token=hparams.check_special_token, sos=hparams.sos, eos=hparams.eos, unk=vocab_utils.UNK, pad_vocab=True) # Target vocab if hparams.share_vocab: utils.print_out(" using source vocab for target") tgt_vocab_file = src_vocab_file tgt_vocab_size = src_vocab_size else: tgt_vocab_size, tgt_vocab_file = vocab_utils.check_vocab( tgt_vocab_file, hparams.output_dir, check_special_token=hparams.check_special_token, sos=hparams.sos, eos=hparams.eos, unk=vocab_utils.UNK) _add_argument(hparams, "src_vocab_size", src_vocab_size) _add_argument(hparams, "tgt_vocab_size", tgt_vocab_size) _add_argument(hparams, "src_vocab_file", src_vocab_file) _add_argument(hparams, "tgt_vocab_file", tgt_vocab_file) # Num embedding partitions _add_argument( hparams, "num_enc_emb_partitions", hparams.num_embeddings_partitions) _add_argument( hparams, "num_dec_emb_partitions", hparams.num_embeddings_partitions) # Pretrained Embeddings _add_argument(hparams, "src_embed_file", "") _add_argument(hparams, "tgt_embed_file", "") if hparams.embed_prefix: src_embed_file = hparams.embed_prefix + "." + hparams.src tgt_embed_file = hparams.embed_prefix + "." + hparams.tgt if tf.gfile.Exists(src_embed_file): utils.print_out(" src_embed_file %s exist" % src_embed_file) hparams.src_embed_file = src_embed_file utils.print_out( "For pretrained embeddings, set num_enc_emb_partitions to 1") hparams.num_enc_emb_partitions = 1 else: utils.print_out(" src_embed_file %s doesn't exist" % src_embed_file) if tf.gfile.Exists(tgt_embed_file): utils.print_out(" tgt_embed_file %s exist" % tgt_embed_file) hparams.tgt_embed_file = tgt_embed_file utils.print_out( "For pretrained embeddings, set num_dec_emb_partitions to 1") hparams.num_dec_emb_partitions = 1 else: utils.print_out(" tgt_embed_file %s doesn't exist" % tgt_embed_file) # Evaluation metric = "bleu" best_metric_dir = os.path.join(hparams.output_dir, "best_" + metric) tf.gfile.MakeDirs(best_metric_dir) _add_argument(hparams, "best_" + metric, 0, update=False) _add_argument(hparams, "best_" + metric + "_dir", best_metric_dir) return hparams def create_or_load_hparams(default_hparams, hparams_path): """Create hparams or load hparams from output_dir.""" hparams = utils.maybe_parse_standard_hparams(default_hparams, hparams_path) hparams = extend_hparams(hparams) # Print HParams utils.print_hparams(hparams) return hparams def run_main(flags, default_hparams, estimator_fn): """Run main.""" # Random random_seed = flags.random_seed if random_seed is not None and random_seed > 0: utils.print_out("# Set random seed to %d" % random_seed) random.seed(random_seed) np.random.seed(random_seed) tf.set_random_seed(random_seed) # Model output directory output_dir = flags.output_dir if output_dir and not tf.gfile.Exists(output_dir): utils.print_out("# Creating output directory %s ..." % output_dir) tf.gfile.MakeDirs(output_dir) # Load hparams. hparams = create_or_load_hparams(default_hparams, flags.hparams_path) # Train or Evaluation estimator_fn(hparams) return hparams def tokenize(hparams, file, tokenized_file): utils.print_out("tokenizing {} -> {}".format(file, tokenized_file)) with open(file, 'rb') as input_file: with open(tokenized_file, 'wb') as output_file: subprocess.run([hparams.tokenizer_file, '-l', hparams.src], stdin=input_file, stdout=output_file) def detokenize(hparams, file, detokenized_file): utils.print_out("detokenizing {} -> {}".format(file, detokenized_file)) with open(file, 'rb') as input_file: with open(detokenized_file, 'wb') as output_file: subprocess.run([hparams.detokenizer_file, '-l', hparams.tgt], stdin=input_file, stdout=output_file) def main(unused_argv): experiment_start = time.time() tf.logging.set_verbosity(tf.logging.INFO) if FLAGS.use_fp16 and FLAGS.use_dist_strategy: raise ValueError("use_fp16 and use_dist_strategy aren't compatible") if FLAGS.use_fp16 + FLAGS.use_amp + FLAGS.use_fastmath > 1: raise ValueError("Only one of use_fp16, use_amp, use_fastmath can be set") if FLAGS.use_amp: utils.print_out('Enabling TF-AMP') os.environ['TF_ENABLE_AUTO_MIXED_PRECISION'] = '1' if FLAGS.use_fastmath: utils.print_out('Enabling FastMath') os.environ["TF_ENABLE_CUBLAS_TENSOR_OP_MATH_FP32"] = '1' os.environ["TF_ENABLE_CUDNN_TENSOR_OP_MATH_FP32"] = '1' os.environ["TF_ENABLE_CUDNN_RNN_TENSOR_OP_MATH_FP32"] = '1' # Set up hacky envvars. # Hack that affects Defun in attention_wrapper.py active_xla_option_nums = np.sum([FLAGS.use_xla, FLAGS.use_autojit_xla, FLAGS.xla_compile]) if active_xla_option_nums > 1: raise ValueError( "Only one of use_xla, xla_compile, use_autojit_xla can be set") os.environ["use_npu"] = str(FLAGS.use_npu).lower() os.environ["cast_output_layer"] = str(FLAGS.cast_output_layer).lower() os.environ["data_shuffle"] = str(FLAGS.data_shuffle).lower() os.environ["use_npu_distribution"] = str(FLAGS.use_npu_distribution).lower() os.environ["use_xla"] = str(FLAGS.use_xla).lower() if FLAGS.use_xla: os.environ["use_defun"] = str(True).lower() else: os.environ["use_defun"] = str(FLAGS.use_defun).lower() utils.print_out("use_defun is %s for attention" % os.environ["use_defun"]) # TODO(jamesqin): retire this config after Cuda9.1 os.environ["use_fp32_batch_matmul"] = ("true" if FLAGS.use_fp32_batch_matmul else "false") os.environ["xla_compile"] = "true" if FLAGS.xla_compile else "false" os.environ["force_inputs_padding"] = ( "true" if FLAGS.force_inputs_padding else "false") if FLAGS.mode == "train": utils.print_out("Running training mode.") default_hparams = create_hparams(FLAGS) run_main(FLAGS, default_hparams, estimator.train_fn) elif FLAGS.mode == "infer" or FLAGS.mode == "translate": if FLAGS.mode == "infer": utils.print_out("Running inference mode.") translate_mode = False else: utils.print_out("Running translate mode on file {}.".format(FLAGS.translate_file)) translate_mode = True # Random random_seed = FLAGS.random_seed if random_seed is not None and random_seed > 0: utils.print_out("# Set random seed to %d" % random_seed) random.seed(random_seed) np.random.seed(random_seed) tf.set_random_seed(random_seed) # Model output directory output_dir = FLAGS.output_dir if output_dir and not tf.gfile.Exists(output_dir): utils.print_out("# Creating output directory %s ..." % output_dir) tf.gfile.MakeDirs(output_dir) # Load hparams. default_hparams = create_hparams(FLAGS) default_hparams.num_buckets = 1 # The estimator model_fn is written in a way allowing train hparams to be # passed in infer mode. hparams = create_or_load_hparams(default_hparams, FLAGS.hparams_path) utils.print_out("infer_hparams:") utils.print_hparams(hparams) if translate_mode: tokenize(hparams, hparams.translate_file, hparams.translate_file + ".tok") eval_sentences, eval_src_tokens, _ = iterator_utils.get_effective_epoch_size(hparams, train=False) # Run evaluation when there's a new checkpoint tf.logging.info("Starting to evaluate...") eval_start = time.time() _, (eval_speed, eval_latencies), eval_output_tokens = estimator.eval_fn(hparams, hparams.ckpt, only_translate=translate_mode) eval_end = time.time() eval_delta = eval_end - eval_start utils.print_out("eval time for ckpt: %.2f mins (%.2f sent/sec, %.2f tokens/sec)" % (eval_delta / 60., eval_speed, eval_speed * (eval_src_tokens + eval_output_tokens) / eval_sentences), f=sys.stderr) for lat in sorted(eval_latencies): utils.print_out("eval latency_%s for ckpt: %.2f ms" % (lat, eval_latencies[lat] * 1000)) if translate_mode: detokenize(hparams, hparams.translate_file + ".trans.tok", hparams.translate_file + ".trans") else: assert FLAGS.mode == "train_and_eval" utils.print_out("Running train and eval mode.") # Random random_seed = FLAGS.random_seed if random_seed is not None and random_seed > 0: utils.print_out("# Set random seed to %d" % random_seed) random.seed(random_seed) np.random.seed(random_seed) tf.set_random_seed(random_seed) # Model output directory output_dir = FLAGS.output_dir if output_dir and not tf.gfile.Exists(output_dir): utils.print_out("# Creating output directory %s ..." % output_dir) tf.gfile.MakeDirs(output_dir) # Load hparams. default_hparams = create_hparams(FLAGS) hparams = create_or_load_hparams(default_hparams, FLAGS.hparams_path) utils.print_out("training hparams:") utils.print_hparams(hparams) with tf.gfile.GFile(os.path.join(output_dir, "train_hparams.txt"), "w") as f: f.write(utils.serialize_hparams(hparams) + "\n") # The estimator model_fn is written in a way allowing train hparams to be # passed in infer mode. infer_hparams = tf.contrib.training.HParams(**hparams.values()) infer_hparams.num_buckets = 1 utils.print_out("infer_hparams:") utils.print_hparams(infer_hparams) with tf.gfile.GFile(os.path.join(output_dir, "infer_hparams.txt"), "w") as f: f.write(utils.serialize_hparams(infer_hparams) + "\n") epochs = 0 should_stop = epochs >= FLAGS.max_train_epochs train_sentences, train_src_tokens, train_tgt_tokens = iterator_utils.get_effective_epoch_size(hparams) eval_sentences, eval_src_tokens, _ = iterator_utils.get_effective_epoch_size(hparams, train=False) while not should_stop: utils.print_out("Starting epoch %d" % epochs) try: train_start = time.time() train_speed, _ = estimator.train_fn(hparams) except tf.errors.OutOfRangeError: utils.print_out("training hits OutOfRangeError", f=sys.stderr) train_end = time.time() train_delta = train_end - train_start utils.print_out("training time for epoch %d: %.2f mins (%.2f sent/sec, %.2f tokens/sec)" % (epochs + 1, train_delta / 60., train_speed, train_speed * (train_src_tokens + train_tgt_tokens) / train_sentences), f=sys.stderr) # This is probably sub-optimal, doing eval per-epoch #eval_start = time.time() #bleu_score, (eval_speed, eval_latencies), eval_output_tokens = estimator.eval_fn(infer_hparams) #eval_end = time.time() #eval_delta = eval_end - eval_start #utils.print_out("eval time for epoch %d: %.2f mins (%.2f sent/sec, %.2f tokens/sec)" % # (epochs + 1, eval_delta / 60., eval_speed, eval_speed * (eval_src_tokens + eval_output_tokens) / eval_sentences), f=sys.stderr) #for lat in sorted(eval_latencies): # utils.print_out("eval latency_%s for epoch %d: %.2f ms" % (lat, epochs + 1, eval_latencies[lat] * 1000)) #if FLAGS.debug or (FLAGS.target_bleu is not None and bleu_score > FLAGS.target_bleu): # should_stop = True # utils.print_out( # "Stop job since target bleu is reached at epoch %d ." % epochs, # f=sys.stderr) epochs += 1 if epochs >= FLAGS.max_train_epochs: should_stop = True utils.print_out("Stop job since max_train_epochs is reached.", f=sys.stderr) experiment_end = time.time() utils.print_out('Experiment took {} min'.format((experiment_end - experiment_start) / 60)) if __name__ == "__main__": nmt_parser = argparse.ArgumentParser() add_arguments(nmt_parser) FLAGS, unparsed = nmt_parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
# Copyright (c) 2015-2022 Vector 35 Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import abc import ctypes import dataclasses from json import dumps from typing import List, Tuple, Optional import sys import traceback # Binary Ninja Components import binaryninja import binaryninja._binaryninjacore as core from .settings import Settings from . import platform as _platform from . import types from . import function as _function from . import binaryview from .log import log_error from .enums import TokenEscapingType def to_bytes(field): if type(field) == bytes: return field if type(field) == str: return field.encode() return str(field).encode() class _TypePrinterMetaclass(type): def __iter__(self): binaryninja._init_plugins() count = ctypes.c_ulonglong() types = core.BNGetTypePrinterList(count) try: for i in range(0, count.value): yield CoreTypePrinter(types[i]) finally: core.BNFreeTypePrinterList(types) def __getitem__(self, value): binaryninja._init_plugins() handle = core.BNGetTypePrinterByName(str(value)) if handle is None: raise KeyError(f"'{value}' is not a valid TypePrinter") return CoreTypePrinter(handle) @property def default(self): name = binaryninja.Settings().get_string("analysis.types.printerName") return CoreTypePrinter[name] class TypePrinter(metaclass=_TypePrinterMetaclass): name = None _registered_printers = [] _cached_tokens = None _cached_string = None _cached_error = None def __init__(self, handle=None): if handle is not None: self.handle = core.handle_of_type(handle, core.BNTypePrinter) self.__dict__["name"] = core.BNGetTypePrinterName(handle) def register(self): assert self.__class__.name is not None self._cb = core.BNTypePrinterCallbacks() self._cb.context = 0 self._cb.getTypeTokens = self._cb.getTypeTokens.__class__(self._get_type_tokens) self._cb.getTypeTokensBeforeName = self._cb.getTypeTokensBeforeName.__class__(self._get_type_tokens_before_name) self._cb.getTypeTokensAfterName = self._cb.getTypeTokensAfterName.__class__(self._get_type_tokens_after_name) self._cb.getTypeString = self._cb.getTypeString.__class__(self._get_type_string) self._cb.getTypeStringBeforeName = self._cb.getTypeStringBeforeName.__class__(self._get_type_string_before_name) self._cb.getTypeStringAfterName = self._cb.getTypeStringAfterName.__class__(self._get_type_string_after_name) self._cb.getTypeLines = self._cb.getTypeLines.__class__(self._get_type_lines) self._cb.freeTokens = self._cb.freeTokens.__class__(self._free_tokens) self._cb.freeString = self._cb.freeString.__class__(self._free_string) self._cb.freeLines = self._cb.freeLines.__class__(self._free_lines) self.handle = core.BNRegisterTypePrinter(self.__class__.name, self._cb) self.__class__._registered_printers.append(self) def __str__(self): return f'<TypePrinter: {self.name}>' def __repr__(self): return f'<TypePrinter: {self.name}>' def _get_type_tokens(self, ctxt, type, platform, name, base_confidence, escaping, result, result_count): try: platform_py = None if platform: platform_py = _platform.Platform(handle=core.BNNewPlatformReference(platform)) result_py = self.get_type_tokens( types.Type(handle=core.BNNewTypeReference(type)), platform_py, types.QualifiedName._from_core_struct(name.contents), base_confidence, escaping) TypePrinter._cached_tokens = _function.InstructionTextToken._get_core_struct(result_py) result[0] = TypePrinter._cached_tokens result_count[0] = len(result_py) return True except: log_error(traceback.format_exc()) return False def _get_type_tokens_before_name(self, ctxt, type, platform, base_confidence, parent_type, escaping, result, result_count): try: platform_py = None if platform: platform_py = _platform.Platform(handle=core.BNNewPlatformReference(platform)) parent_type_py = None if parent_type: parent_type_py = types.Type(handle=core.BNNewTypeReference(parent_type)) result_py = self.get_type_tokens_before_name( types.Type(handle=core.BNNewTypeReference(type)), platform_py, base_confidence, parent_type_py, escaping) TypePrinter._cached_tokens = _function.InstructionTextToken._get_core_struct(result_py) result[0] = TypePrinter._cached_tokens result_count[0] = len(result_py) return True except: log_error(traceback.format_exc()) return False def _get_type_tokens_after_name(self, ctxt, type, platform, base_confidence, parent_type, escaping, result, result_count): try: platform_py = None if platform: platform_py = _platform.Platform(handle=core.BNNewPlatformReference(platform)) parent_type_py = None if parent_type: parent_type_py = types.Type(handle=core.BNNewTypeReference(parent_type)) result_py = self.get_type_tokens_after_name( types.Type(handle=core.BNNewTypeReference(type)), platform_py, base_confidence, parent_type_py, escaping) TypePrinter._cached_tokens = _function.InstructionTextToken._get_core_struct(result_py) result[0] = TypePrinter._cached_tokens result_count[0] = len(result_py) return True except: log_error(traceback.format_exc()) return False def _get_type_string(self, ctxt, type, platform, name, escaping, result): try: platform_py = None if platform: platform_py = _platform.Platform(handle=core.BNNewPlatformReference(platform)) result_py = self.get_type_string( types.Type(handle=core.BNNewTypeReference(type)), platform_py, types.QualifiedName._from_core_struct(name.contents), escaping) TypePrinter._cached_string = core.cstr(result_py) result[0] = TypePrinter._cached_string return True except: log_error(traceback.format_exc()) return False def _get_type_string_before_name(self, ctxt, type, platform, escaping, result): try: platform_py = None if platform: platform_py = _platform.Platform(handle=core.BNNewPlatformReference(platform)) result_py = self.get_type_string_before_name( types.Type(handle=core.BNNewTypeReference(type)), platform_py, escaping) TypePrinter._cached_string = core.cstr(result_py) result[0] = TypePrinter._cached_string return True except: log_error(traceback.format_exc()) return False def _get_type_string_after_name(self, ctxt, type, platform, escaping, result): try: platform_py = None if platform: platform_py = _platform.Platform(handle=core.BNNewPlatformReference(platform)) result_py = self.get_type_string_after_name( types.Type(handle=core.BNNewTypeReference(type)), platform_py, escaping) TypePrinter._cached_string = core.cstr(result_py) result[0] = TypePrinter._cached_string return True except: log_error(traceback.format_exc()) return False def _get_type_lines(self, ctxt, type, data, name, line_width, collapsed, escaping, result, result_count): try: result_py = self.get_type_lines( types.Type(handle=core.BNNewTypeReference(type)), binaryview.BinaryView(handle=core.BNNewViewReference(data)), types.QualifiedName._from_core_struct(name.contents), line_width, collapsed, escaping) TypePrinter._cached_lines = (core.BNTypeDefinitionLine * len(result_py))() for (i, line) in enumerate(result_py): TypePrinter._cached_lines[i] = line._to_core_struct() result[0] = TypePrinter._cached_lines result_count[0] = len(result_py) return True except: log_error(traceback.format_exc()) return False def _free_tokens(self, ctxt, tokens, count): try: TypePrinter._cached_tokens = None return True except: log_error(traceback.format_exc()) return False def _free_string(self, ctxt, string): try: TypePrinter._cached_string = None return True except: log_error(traceback.format_exc()) return False def _free_lines(self, ctxt, lines, count): try: for line in TypePrinter._cached_lines: core.BNFreeType(line.type) core.BNFreeType(line.rootType) TypePrinter._cached_lines = None return True except: log_error(traceback.format_exc()) return False def get_type_tokens(self, type: types.Type, platform: Optional[_platform.Platform] = None, name: types.QualifiedNameType = "", base_confidence: int = core.max_confidence, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> List[_function.InstructionTextToken]: raise NotImplementedError() def get_type_tokens_before_name(self, type: types.Type, platform: Optional[_platform.Platform] = None, base_confidence: int = core.max_confidence, parent_type: Optional[types.Type] = None, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> List[_function.InstructionTextToken]: raise NotImplementedError() def get_type_tokens_after_name(self, type: types.Type, platform: Optional[_platform.Platform] = None, base_confidence: int = core.max_confidence, parent_type: Optional[types.Type] = None, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> List[_function.InstructionTextToken]: raise NotImplementedError() def get_type_string(self, type: types.Type, platform: Optional[_platform.Platform] = None, name: types.QualifiedNameType = "", escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> str: raise NotImplementedError() def get_type_string_before_name(self, type: types.Type, platform: Optional[_platform.Platform] = None, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> str: raise NotImplementedError() def get_type_string_after_name(self, type: types.Type, platform: Optional[_platform.Platform] = None, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> str: raise NotImplementedError() def get_type_lines(self, type: types.Type, data: binaryview.BinaryView, name: types.QualifiedNameType, line_width = 80, collapsed = False, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> List[types.TypeDefinitionLine]: raise NotImplementedError() class CoreTypePrinter(TypePrinter): def get_type_tokens(self, type: types.Type, platform: Optional[_platform.Platform] = None, name: types.QualifiedNameType = "", base_confidence: int = core.max_confidence, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> List[ _function.InstructionTextToken]: if not isinstance(name, types.QualifiedName): name = types.QualifiedName(name) count = ctypes.c_ulonglong() name_cpp = name._to_core_struct() result_cpp = ctypes.POINTER(core.BNInstructionTextToken)() if not core.BNGetTypePrinterTypeTokens(self.handle, type.handle, None if platform is None else platform.handle, name_cpp, base_confidence, ctypes.c_int(escaping), result_cpp, count): raise RuntimeError("BNGetTypePrinterTypeTokens returned False") result = _function.InstructionTextToken._from_core_struct(result_cpp, count.value) core.BNFreeInstructionText(result_cpp.contents, count.value) return result def get_type_tokens_before_name(self, type: types.Type, platform: Optional[_platform.Platform] = None, base_confidence: int = core.max_confidence, parent_type: Optional[types.Type] = None, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> List[ _function.InstructionTextToken]: count = ctypes.c_ulonglong() result_cpp = ctypes.POINTER(core.BNInstructionTextToken)() parent_type_cpp = None if parent_type is not None: parent_type_cpp = parent_type.handle if not core.BNGetTypePrinterTypeTokensBeforeName(self.handle, type.handle, None if platform is None else platform.handle, base_confidence, parent_type_cpp, ctypes.c_int(escaping), result_cpp, count): raise RuntimeError("BNGetTypePrinterTypeTokensBeforeName returned False") result = _function.InstructionTextToken._from_core_struct(result_cpp, count.value) core.BNFreeInstructionText(result_cpp.contents, count.value) return result def get_type_tokens_after_name(self, type: types.Type, platform: Optional[_platform.Platform] = None, base_confidence: int = core.max_confidence, parent_type: Optional[types.Type] = None, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> List[ _function.InstructionTextToken]: count = ctypes.c_ulonglong() result_cpp = ctypes.POINTER(core.BNInstructionTextToken)() parent_type_cpp = None if parent_type is not None: parent_type_cpp = parent_type.handle if not core.BNGetTypePrinterTypeTokensAfterName(self.handle, type.handle, None if platform is None else platform.handle, base_confidence, parent_type_cpp, ctypes.c_int(escaping), result_cpp, count): raise RuntimeError("BNGetTypePrinterTypeTokensAfterName returned False") result = _function.InstructionTextToken._from_core_struct(result_cpp, count.value) core.BNFreeInstructionText(result_cpp.contents, count.value) return result def get_type_string(self, type: types.Type, platform: Optional[_platform.Platform] = None, name: types.QualifiedNameType = "", escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> str: if not isinstance(name, types.QualifiedName): name = types.QualifiedName(name) result_cpp = ctypes.c_char_p() if not core.BNGetTypePrinterTypeString(self.handle, type.handle, None if platform is None else platform.handle, name._to_core_struct(), ctypes.c_int(escaping), result_cpp): raise RuntimeError("BNGetTypePrinterTypeString returned False") result = core.pyNativeStr(result_cpp.value) core.free_string(result_cpp) return result def get_type_string_before_name(self, type: types.Type, platform: Optional[_platform.Platform] = None, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> str: result_cpp = ctypes.c_char_p() if not core.BNGetTypePrinterTypeStringBeforeName(self.handle, type.handle, None if platform is None else platform.handle, ctypes.c_int(escaping), result_cpp): raise RuntimeError("BNGetTypePrinterTypeStringBeforeName returned False") result = core.pyNativeStr(result_cpp.value) core.free_string(result_cpp) return result def get_type_string_after_name(self, type: types.Type, platform: Optional[_platform.Platform] = None, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType) -> str: result_cpp = ctypes.c_char_p() if not core.BNGetTypePrinterTypeStringAfterName(self.handle, type.handle, None if platform is None else platform.handle, ctypes.c_int(escaping), result_cpp): raise RuntimeError("BNGetTypePrinterTypeStringAfterName returned False") result = core.pyNativeStr(result_cpp.value) core.free_string(result_cpp) return result def get_type_lines(self, type: types.Type, data: binaryview.BinaryView, name: types.QualifiedNameType, line_width = 80, collapsed = False, escaping: TokenEscapingType = TokenEscapingType.BackticksTokenEscapingType ) -> List[types.TypeDefinitionLine]: if not isinstance(name, types.QualifiedName): name = types.QualifiedName(name) count = ctypes.c_ulonglong() core_lines = ctypes.POINTER(core.BNTypeDefinitionLine)() if not core.BNGetTypePrinterTypeLines(self.handle, type.handle, data.handle, name._to_core_struct(), line_width, collapsed, ctypes.c_int(escaping), core_lines, count): raise RuntimeError("BNGetTypePrinterTypeLines returned False") lines = [] for i in range(count.value): tokens = _function.InstructionTextToken._from_core_struct(core_lines[i].tokens, core_lines[i].count) type_ = types.Type.create(handle=core.BNNewTypeReference(core_lines[i].type), platform=data.platform) root_type = types.Type.create(handle=core.BNNewTypeReference(core_lines[i].rootType), platform=data.platform) root_type_name = core.pyNativeStr(core_lines[i].rootTypeName) line = types.TypeDefinitionLine(core_lines[i].lineType, tokens, type_, root_type, root_type_name, core_lines[i].offset, core_lines[i].fieldIndex) lines.append(line) core.BNFreeTypeDefinitionLineList(core_lines, count.value) return lines
from django.shortcuts import redirect from .models import HouseMembership def house_required(function=None): def wrapper(request, *args, **kwargs): user = request.user try: currentHouse = HouseMembership.objects.get(user=user, currentHouse=True) except HouseMembership.DoesNotExist: currentHouse = None if currentHouse is not None: return function(request) return redirect('join-house') return wrapper def house_admin_required(function=None): def wrapper(request, *args, **kwargs): user = request.user # Get the user's current house, only if they are an admin try: membership = HouseMembership.objects.get(user=user, currentHouse=True, admin=True) except HouseMembership.DoesNotExist: membership = None if membership is not None: return function(request) return redirect('dashboard') return wrapper
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os.path sys.path.append(os.path.join(os.getcwd(), '.')) sys.path.append(os.path.join(os.getcwd(), '..'))
import json import os import argparse from shutil import copy, SameFileError import logging from tqdm import tqdm from PIL import Image from pathlib import Path from odm_report_shot_coverage.models.reconstruction import parse_reconstruction from odm_report_shot_coverage.models.shot import Boundaries Image.MAX_IMAGE_PIXELS = 1000000000 def _copy_orthophoto(src_dir: str, target_dir: str) -> Boundaries: logging.info('Copying orthophoto') im = Image.open('%s/odm_orthophoto/odm_orthophoto.tif' % src_dir) im.save('%s/odm_orthophoto.png' % target_dir) def _copy_images(src_dir: str, target_dir: str): Path(target_dir).mkdir(parents=True, exist_ok=True) target_size = 400 image_files = os.listdir(src_dir) for file_name in tqdm(image_files, desc='Resizing images'): im = Image.open('%s/%s' % (src_dir, file_name)) width, height = im.size max_size = max(width, height) new_size = (int(width * target_size / max_size), int(height * target_size / max_size)) im = im.resize(new_size) im.save('%s/%s' % (target_dir, file_name)) def _copy_web_app(target_dir: str): logging.info('Copying web app') web_dir = os.path.dirname(__file__) + '/web' for file_name in os.listdir(web_dir): if file_name not in {'data', 'images'}: try: copy(web_dir + '/' + file_name, target_dir) except SameFileError: pass def main(): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description='Build an OpenDroneMap shot coverage report') parser.add_argument("project", help="the ODM project root folder", type=str) args = parser.parse_args() project_dir = args.project out_dir = project_dir + '/odm_report/shot_coverage' Path(out_dir + '/data').mkdir(parents=True, exist_ok=True) _copy_web_app(out_dir) _copy_images(project_dir + '/images', out_dir + '/images') _copy_orthophoto(project_dir, out_dir + '/data') logging.info('Parsing reconstruction') reconstruction = parse_reconstruction(project_dir) logging.info('Computing shot boundaries') reconstruction.compute_shot_boundaries() logging.info('Saving reconstruction_shots.json') with open('%s/data/reconstruction_shots.json' % out_dir, 'w') as fd_out: json.dump(reconstruction.to_json(), fd_out) print('Shot coverage completed') print('To open the results page, launch:') print('python -m http.server --directory %s 8001' % out_dir) print('And open http://localhost:8001 (or change port value if already taken)') if __name__ == '__main__': main()
class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: dic = {} for i, x in enumerate(nums): if x in dic: if abs(dic[x] - i) <= k: return True dic[x] = i return False
def main(parameters): ''' Gets al ist of users at a certain location NOTE: not implemented yet ''' answer = { 'text': 'This feature is not yet implemented.', 'markdown': 'This feature is not yet implemented.', 'file': None } return answer
from jinja2 import Environment, FileSystemLoader, select_autoescape, meta, Template from sql_gen.template_source import TemplateSource from sql_gen.prompter import Prompter from sql_gen.filter_loader import load_filters from sql_gen_app import run_app ##main def main(): run_app() if __name__ == '__main__': main()
from pymongo import MongoClient if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument( "-u", "--mongo_url", default="localhost", dest = "u" ) parser.add_argument( "-d", "--mongo_db", default="pmc", dest = "d" ) parser.add_argument( "-c", "--mongo_collection", default="articlesubset", dest = "c" ) args = parser.parse_args() print("Making connection.") articles = MongoClient(args.u)[args.d][args.c] print("Writing index field...") articles.update_many({'meta.article-type': 'research-article'}, {'$set': {'index.research': 1}}) print("Creating index...") articles.create_index("index.research") print("Done.")
from .python_package_template import PythonPackageTemplate
# -*- coding: utf-8 -*- from hcloud.core.domain import BaseDomain, DomainIdentityMixin class Location(BaseDomain, DomainIdentityMixin): """Location Domain :param id: int ID of location :param name: str Name of location :param description: str Description of location :param country: str ISO 3166-1 alpha-2 code of the country the location resides in :param city: str City the location is closest to :param latitude: float Latitude of the city closest to the location :param longitude: float Longitude of the city closest to the location :param network_zone: str Name of network zone this location resides in """ __slots__ = ( "id", "name", "description", "country", "city", "latitude", "longitude", "network_zone" ) def __init__( self, id=None, name=None, description=None, country=None, city=None, latitude=None, longitude=None, network_zone=None, ): self.id = id self.name = name self.description = description self.country = country self.city = city self.latitude = latitude self.longitude = longitude self.network_zone = network_zone
# import inspect # import os # # # def test_rules_imported(): # """ # Проверяем что все правила импортированны в __init__ # :return: # """ # import policy # # members = inspect.getmembers(policy, inspect.ismodule) # modules_imported = set(name for name, _ in members) # # # Берем все файлы с правилами и удаляем .py # repo_rules_folder = os.path.dirname(policy.__file__) # all_rule_files = set( # map(lambda x: x[:-3] if x.endswith(".py") else x, os.listdir(repo_rules_folder)) # ) # # # Удаляем специфичные файлы, которые не надо импортить # skip = { # "remove_empty_folder", # "common", # "__init__", # "__pycache__", # } # # modules = all_rule_files - skip # # not_imported = modules - modules_imported # assert len(not_imported) == 0, ( # "Некоторые модули не импортированы в repo/__init__.py: {}\n" # "Импортируйте их в ручную".format(not_imported) # )
class Piece: def __init__(self, name, *, is_white: bool = True): self.name = name self.is_white = is_white self.color = 'white' if is_white else 'black' self.has_moved = False def find_piece(self, board): position = None for row in board: for cell in row: if cell.piece == self: position = cell return position @property def image(self): return str(self)[:2] @staticmethod def _is_valid_position(position_x, position_y, board): index_x = position_x - 1 index_y = position_y - 1 return 0 <= index_x < len(board) and 0 <= index_y < len(board[index_x]) def _append_hint_if_valid(self, position_x, position_y, board, hints, *, can_attack=True): if self._is_valid_position(position_x, position_y, board) and \ (self._is_open(position_x, position_y, board) or ( can_attack and self._is_enemy(position_x, position_y, board))): hints.append([position_x, position_y]) def _is_open(self, position_x, position_y, board): index_x = position_x - 1 index_y = position_y - 1 return self._is_valid_position(position_x, position_y, board) and not board[index_x][index_y].piece def _is_enemy(self, position_x, position_y, board): index_x = position_x - 1 index_y = position_y - 1 if not self._is_valid_position(position_x, position_y, board): return False piece = board[index_x][index_y].piece return piece and not piece.color == self.color def __str__(self): move_indicator = 1 if self.has_moved else 0 return f'{self.color[0]}{self.name}{move_indicator}'
import re import os import json from ts import Simbolo from storageManager import jsonMode as jsonMode from tabla_errores import * from columna import * import math import numpy as np from random import random class TypeChecker(): 'Esta clase representa el type checker para la comprobación de tipos' def __init__(self, tabla_simbolos, tabla_errores, consola, salida): self.type_checker = {} self.actual_database = '' self.tabla_simbolos = tabla_simbolos self.tabla_errores = tabla_errores self.consola = consola self.salida = salida jsonMode.dropAll() self.initCheck() def createDatabase(self, database: str, line: int, mode: int = 1): # 0 -> operación exitosa, # 1 -> error en la operación, # 2 -> base de datos existente query_result = jsonMode.createDatabase(database) if query_result == 0: self.type_checker[database] = {} self.tabla_simbolos.agregar(Simbolo(database, 'DATABASE', '', line)) self.consola.append(Codigos().database_successful_completion(database)) self.saveTypeChecker() elif query_result == 1: self.addError(Codigos().database_internal_error(database), line) else: self.addError(Codigos().database_duplicate_database(database), line) def showDatabase(self, like: str = ''): query_result = jsonMode.showDatabases() if like == '': self.salida.append(query_result) else: pattern = '^' + like.replace('%','.+').replace('_','(.){0,1}') + '$' filtrada = [] for base in query_result: if re.match(pattern, base): filtrada.append(base) self.salida.append(filtrada) self.consola.append(Codigos().successful_completion('SHOW DATABASE')) def alterDatabase(self, databaseOld: str, databaseNew: str, line: int): # 0 -> operación exitosa # 1 -> error en la operación # 2 -> databaseOld no existente # 3 -> databaseNew existente query_result = jsonMode.alterDatabase(databaseOld, databaseNew) if query_result == 0: self.consola.append(Codigos().successful_completion('ALTER DATABASE')) self.type_checker[databaseNew] = self.type_checker.pop(databaseOld) self.tabla_simbolos.simbolos[databaseNew] = self.tabla_simbolos.simbolos.pop(databaseOld) self.saveTypeChecker() elif query_result == 1: self.addError(Codigos().database_internal_error(databaseOld), line) elif query_result == 2: self.addError(Codigos().database_undefined_object(databaseOld), line) else: self.addError(Codigos().database_duplicate_database(databaseNew), line) def dropDatabase(self, database: str, line: int): # 0 -> operación exitosa # 1 -> error en la operación # 2 -> base de datos no existente query_result = jsonMode.dropDatabase(database) if query_result == 0: self.consola.append(Codigos().successful_completion('DROP DATABASE «' + database + '»')) self.type_checker.pop(database) self.tabla_simbolos.simbolos.pop(database) if self.actual_database == database: self.actual_database = '' self.saveTypeChecker() elif query_result == 1: self.addError(Codigos().database_internal_error(database), line) else: self.addError(Codigos().database_undefined_object(database), line) def useDatabase(self, database: str, line: int): if database in self.type_checker: self.actual_database = database self.consola.append(Codigos().successful_completion('USE DATABASE')) else: self.addError(Codigos().database_undefined_object(database), line) def createTable(self, table: str, columns: [], line: int): # 0 -> operación exitosa # 1 -> error en la operación # 2 -> base de datos inexistente # 3 -> tabla existente query_result = jsonMode.createTable(self.actual_database, table, len(columns)) if query_result == 0: self.consola.append(Codigos().table_successful(table)) self.type_checker[self.actual_database][table] = {} for columna in columns: self.type_checker[self.actual_database][table][columna['nombre']] = columna['col'] self.saveTypeChecker() elif query_result == 1: self.addError(Codigos().database_internal_error(table), line) elif query_result == 2: self.addError(Codigos().database_undefined_object(self.actual_database), line) else: self.addError(Codigos().table_duplicate_table(table), line) def initCheck(self): if not os.path.exists('data'): os.makedirs('data') if not os.path.exists('data/json'): os.makedirs('data/json') if not os.path.exists('data/json/type_check'): data = {} with open('data/json/type_check', 'w') as file: json.dump(data, file) else: with open('data/json/type_check') as file: data = json.load(file) for database in data: for tabla in data[database]: for columna in data[database][tabla]: data[database][tabla][columna] = Columna( tipo = data[database][tabla][columna]['tipo'], default = data[database][tabla][columna]['default'], is_null = TipoNull[data[database][tabla][columna]['is_null']], is_primary = data[database][tabla][columna]['is_primary'], references = data[database][tabla][columna]['references'], is_unique = data[database][tabla][columna]['is_unique'], constraints = data[database][tabla][columna]['constraints'] ) print('!!!!!!!!!init\n') # data['MODELA']['Tobleta']['columna1'].printCol() def saveTypeChecker(self): with open('data/json/type_check', 'w') as file: data = self.type_checker for database in data: for tabla in data[database]: for columna in data[database][tabla]: data[database][tabla][columna] = data[database][tabla][columna].json() json.dump(data, file) def addError(self, error, line): self.consola.append(error) self.tabla_errores.agregar(Error('Semántico', error, line)) def Validando_Operaciones_Aritmeticas(self, valor1, valor2, operando): v1 = float(valor1) v2 = float(valor2) if operando == '+': val = v1 + v2 return val elif operando == '-': val = v1 - v2 return val elif operando == '*': val = v1 * v2 return val elif operando == '/': val = v1 / v2 return val elif operando == '%': val = v1 % v2 return val elif operando == '^': val = v1 ** v2 return val elif operando == 'NEGATIVO': val = -1 * v1 return val def Funciones_Trigonometricas_1(self, funcion, valor, line: int): val = float(valor) if funcion == 'ACOS': if val >=-1 and val <=1: self.consola.append(Codigos().successful_completion('SELECT ACOS(' + str(val) + ')')) return math.acos (val) else: return self.addError(Codigos().trigonometric_function_out_of_range('ACOS', str(val), '-1, 1'), line) elif funcion == 'ASIN': if val >=-1 and val <=1: self.consola.append(Codigos().successful_completion('SELECT ASIN(' + str(val) + ')')) return math.asin (val) else: return self.addError(Codigos().trigonometric_function_out_of_range('ACOS', str(val), '-1, 1'), line) elif funcion == 'ATAN': self.consola.append(Codigos().successful_completion('SELECT ASIN(' + str(val) + ')')) return math.asin (val) elif funcion == 'COS': self.consola.append(Codigos().successful_completion('SELECT COS(' + str(val) + ')')) return math.cos (val) elif funcion == 'COT': self.consola.append(Codigos().successful_completion('SELECT COT(' + str(val) + ')')) result = math.tan (val) ** -1 return result elif funcion == 'SIN': self.consola.append(Codigos().successful_completion('SELECT SIN(' + str(val) + ')')) return math.sin (val) elif funcion == 'TAN': self.consola.append(Codigos().successful_completion('SELECT TAN(' + str(val) + ')')) return math.tan (val) elif funcion == 'ASIND': if val >=-1 and val <=1: self.consola.append(Codigos().successful_completion('SELECT ASIND(' + str(val) + ')')) return math.asin(math.radians(val)) else: return self.addError(Codigos().trigonometric_function_out_of_range('ASIND', str(val), '-1, 1'), line) elif funcion == 'ACOSD': if val >=-1 and val <=1: self.consola.append(Codigos().successful_completion('SELECT ACOSD(' + str(val) + ')')) return math.acos(math.radians(val)) # <= no esta la funcion else: return self.addError(Codigos().trigonometric_function_out_of_range('ACOSD', str(val), '-1, 1'), line) elif funcion == 'ATAND': self.consola.append(Codigos().successful_completion('SELECT ATAND(' + str(val) + ')')) return math.atan(math.radians(val)) # <= no esta la funcion elif funcion == 'COSD': self.consola.append(Codigos().successful_completion('SELECT COSD(' + str(val) + ')')) return math.cos(math.radians(val)) # <= no esta la funcion elif funcion == 'COTD': self.consola.append(Codigos().successful_completion('SELECT COTD(' + str(val) + ')')) return math.tan (math.radians(val)) ** -1 # <= no esta la funcion elif funcion == 'SIND': self.consola.append(Codigos().successful_completion('SELECT SIND(' + str(val) + ')')) return math.sin (math.radians(val)) # <= no esta la funcion elif funcion == 'TAND': self.consola.append(Codigos().successful_completion('SELECT TAND(' + str(val) + ')')) return math.tan(math.radians(val)) # <= no esta la funcion elif funcion == 'SINH': self.consola.append(Codigos().successful_completion('SELECT SINH(' + str(val) + ')')) return math.sinh (val) elif funcion == 'COSH': self.consola.append(Codigos().successful_completion('SELECT COSH(' + str(val) + ')')) return math.cosh (val) elif funcion == 'TANH': self.consola.append(Codigos().successful_completion('SELECT TANH(' + str(val) + ')')) return math.tanh (val) elif funcion == 'ASINH': self.consola.append(Codigos().successful_completion('SELECT ASINH(' + str(val) + ')')) return math.asinh (val) elif funcion == 'ACOSH': if val >= 1: self.consola.append(Codigos().successful_completion('SELECT ACOSH(' + str(val) + ')')) return math.acosh (val) else: return self.addError(Codigos().trigonometric_function_out_of_range('ACOSH', str(val), '1, infinit'), line) elif funcion == 'ATANH': if val >-1 and val <1: self.consola.append(Codigos().successful_completion('SELECT ATANH(' + str(val) + ')')) return math.atanh (val) else: return self.addError(Codigos().trigonometric_function_out_of_range('ATANH', str(val), '-1, 1'), line) def Funciones_Trigonometricas_2(self, funcion, valor1, valor2, line: int): val1 = float(valor1) val2 = float(valor2) if funcion == 'ATAN2D': # <= 2 parametros return math.atan2 (math.radians(val1), math.radians(val2)) elif funcion == 'ATAN2': # <= 2 parametros return math.atan2 (val1, val2) def Funciones_Matematicas_1(self, funcion, valor, line: int): val = float(valor) if funcion == 'COUNT': # <= FALTA return 1 elif funcion == 'SUM': # <= FALTA return 1 elif funcion == 'AVG': # <= FALTA return 1 elif funcion == 'ABS': self.consola.append(Codigos().successful_completion('ABS (' + str(val) + ')')) return abs(val) elif funcion == 'CBRT': self.consola.append(Codigos().successful_completion('CBRT (' + str(val) + ')')) return val ** (1/3) elif funcion == 'CEIL': self.consola.append(Codigos().successful_completion('CEIL (' + str(val) + ')')) return round(val) elif funcion == 'CEILING': self.consola.append(Codigos().successful_completion('CEILING (' + str(val) + ')')) return math.ceil(val) elif funcion == 'DEGREES': self.consola.append(Codigos().successful_completion('DEGREES (' + str(val) + ')')) return math.degrees(val) elif funcion == 'EXP': self.consola.append(Codigos().successful_completion('EXP (' + str(val) + ')')) return math.e ** val elif funcion == 'FACTORIAL': self.consola.append(Codigos().successful_completion('FACTORIAL (' + str(val) + ')')) return math.factorial(val) elif funcion == 'FLOOR': self.consola.append(Codigos().successful_completion('FLOOR (' + str(val) + ')')) return math.floor(val) elif funcion == 'LN': self.consola.append(Codigos().successful_completion('LN (' + str(val) + ')')) return math.log(val) elif funcion == 'LOG': self.consola.append(Codigos().successful_completion('LOG (' + str(val) + ')')) return math.log(val) elif funcion == 'PI': self.consola.append(Codigos().successful_completion('PI ()')) return math.pi elif funcion == 'RADIANS': self.consola.append(Codigos().successful_completion('RADIANS (' + str(val) + ')')) return math.radians(val) elif funcion == 'ROUND': self.consola.append(Codigos().successful_completion('ROUND (' + str(val) + ')')) return round(val) elif funcion == 'SIGN': self.consola.append(Codigos().successful_completion('SIGN (' + str(val) + ')')) return np.sign(val) elif funcion == 'SQRT': if val >= 0: self.consola.append(Codigos().successful_completion('SQRT (' + str(val) + ')')) return val ** (1/2) else: return self.addError(Codigos().trigonometric_function_out_of_range('SQRT', str(val), '0, infinit'), line) elif funcion == 'TRUNC': self.consola.append(Codigos().successful_completion('TRUNC (' + str(val) + ')')) return math.trunc(val) elif funcion == 'RANDOM': self.consola.append(Codigos().successful_completion('RANDOM ()')) return random() def Funciones_Matematicas_2(self, funcion, valor1, valor2, line: int): val1 = float(valor1) val2 = float(valor2) if funcion == 'MOD': self.consola.append(Codigos().successful_completion('MOD ('+ str(val1) +',' + str(val2)+ ')')) return val1 % val2 elif funcion == 'POWER': self.consola.append(Codigos().successful_completion('POWER ('+ str(val1) +',' + str(val2)+ ')')) return math.pow(val1, val2) elif funcion == 'DIV': self.consola.append(Codigos().successful_completion('DIV ('+ str(val1) +',' + str(val2)+ ')')) return val1 // val2 elif funcion == 'GCD': self.consola.append(Codigos().successful_completion('GCD ('+ str(val1) +',' + str(val2)+ ')')) return math.gcd(val1, val2)
from django import forms from django.forms import formset_factory from .models import Category,Measure,IngPrice class RecipeForm(forms.Form): name = forms.CharField( label="Recipe name", required=True, widget=forms.TextInput( attrs={ 'placeholder':"Enter Recipe name" } ) ) description = forms.CharField( label="Recipe description", required=True, widget=forms.TextInput( attrs={ 'placeholder':"Enter recipe description" } ) ) category = forms.ModelChoiceField(queryset=Category.objects.all(),required=True,to_field_name='name') image = forms.ImageField() extra_category_count = forms.CharField(widget=forms.HiddenInput()) ingredients = forms.ModelChoiceField(queryset=IngPrice.objects.all(),required=True) def __init__(self,*args, **kwargs): extra_category = kwargs.pop('extra',0) ing = forms.ModelChoiceField(queryset=IngPrice.objects.all(),required=True) if not extra_category: extra_category=0 super(RecipeForm,self).__init__(*args, **kwargs) self.fields['extra_category_count'].initial = extra_category for i in range(int(extra_category)): self.fields[f'extra_category_{i}']=ing class IngredientForm(forms.Form): name = forms.CharField( label="Ingredient name", required=True, widget=forms.TextInput( attrs={ 'placeholder':"Enter ingredient name" } ) ) price = forms.DecimalField( required=True, min_value=1.00, decimal_places=2, max_digits=9, widget=forms.NumberInput( attrs={ 'placeholder':"Enter price" } ) ) quantity = forms.IntegerField( required=True, min_value=1, widget=forms.NumberInput( attrs={ 'placeholder':"Enter Amount" } ) ) measure = forms.ModelChoiceField(queryset=Measure.objects.all(),required=True,to_field_name='name') IngredientCreationFormSet = formset_factory(IngredientForm,extra=1)
import tensorflow as tf flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('hidden3', 64, 'Number of units in hidden layer 3.') flags.DEFINE_integer('discriminator_out', 0, 'discriminator_out.') flags.DEFINE_float('discriminator_learning_rate', 0.001, 'Initial learning rate.') flags.DEFINE_float('learning_rate', .5 * 0.001, 'Initial learning rate.') flags.DEFINE_integer('hidden1', 16, 'Number of units in hidden layer 1.') flags.DEFINE_integer('hidden2', 1, 'Number of units in hidden layer 2.') flags.DEFINE_integer('output_dimension', 35, 'Second dimension of output.') flags.DEFINE_integer('multi_view_K', 13, 'K param for multi-view') flags.DEFINE_integer('single_view_K', 7, 'K param for single-view') flags.DEFINE_float('weight_decay', 0., 'Weight for L2 loss on embedding matrix.') flags.DEFINE_float('dropout', 0., 'Dropout rate (1 - keep probability).') flags.DEFINE_integer('features', 1, 'Whether to use features (1) or not (0).') flags.DEFINE_integer('seed', 50, 'seed for fixing the results.') flags.DEFINE_integer('iterations', 30, 'number of iterations.') seed = 7 def get_settings_new(model, view): iterations = FLAGS.iterations if view == -1: FLAGS.output_dimension = 140 FLAGS.hidden1 = 70 re = {'iterations': iterations, 'model': model} return re
from django.db.models.signals import pre_save,post_save from .mysingal import action def pre_save_func(sender,**kwargs): print(sender) print(kwargs) print(kwargs.get("instance")) # pre_save.connect(pre_save_func) post_save.connect(pre_save_func) def my_action_func(sender,**kwargs): print(sender) print(kwargs) action.connect(my_action_func)
import os import shutil import hdbscan from math import isclose import numpy as np from sklearn.metrics import adjusted_rand_score from oolearning import * from tests.TestHelper import TestHelper from tests.TimerTestCase import TimerTestCase # noinspection PyMethodMayBeStatic, PyUnresolvedReferences class UnsupervisedTests(TimerTestCase): @classmethod def setUpClass(cls): pass def test_ModelTrainer_callback(self): # make sure that the ModelTrainer->train_callback works, other tests rely on it to work correctly. data = TestHelper.get_iris_data() # noinspection PyUnusedLocal def fit_callback(data_x, target, hyper_params): raise NotImplementedError() model_trainer = ModelTrainer(model=ClusteringKMeans(), model_transformations=[CenterScaleTransformer()], train_callback=fit_callback) # should raise an error from the callback definition above self.assertRaises(NotImplementedError, lambda: model_trainer.train_predict_eval(data=data, hyper_params=ClusteringKMeansHP())) def test_ModelTrainer_persistence(self): # make sure that the ModelTrainer->train_callback works, other tests rely on it to work correctly. data = TestHelper.get_iris_data() data = data.drop(columns='species') cache_directory = TestHelper.ensure_test_directory('temp') assert os.path.isdir(cache_directory) is False model_fitter = ModelTrainer(model=ClusteringKMeans(), model_transformations=[CenterScaleTransformer()], persistence_manager=LocalCacheManager(cache_directory=cache_directory)) clusters = model_fitter.train_predict_eval(data=data, hyper_params=ClusteringKMeansHP()) expected_file = os.path.join(cache_directory, 'ClusteringKMeans_num_clusters_8_init_method_k-means_num_different_seeds_10_max_iterations_300_precompute_distances_auto_algorithm_auto.pkl') # noqa assert os.path.isfile(expected_file) # use a different seed which was verified to produce different clusters, but since we are getting # the cached file, we should retrieve the model with the old seed which should produce the original # clusters (i.e. commenting out `persistence_manager=...` was verified to produce different # `new_clusters` new_model_fitter = ModelTrainer(model=ClusteringKMeans(seed=123), model_transformations=[CenterScaleTransformer()], persistence_manager=LocalCacheManager(cache_directory=cache_directory)) # noqa new_clusters = new_model_fitter.train_predict_eval(data=data, hyper_params=ClusteringKMeansHP()) shutil.rmtree(cache_directory) # noinspection PyTypeChecker assert all(new_clusters == clusters) def test_ModelTrainer_transformations(self): data = TestHelper.get_iris_data() data = data.drop(columns='species') transformations = [CenterScaleTransformer()] # noinspection PyUnusedLocal def fit_callback(transformed_data, target, hyper_params): # make sure the data that was trained was as expected center_scale = CenterScaleTransformer() transformed_local_data = center_scale.fit_transform(data_x=data) # noinspection PyTypeChecker assert all(transformed_data.columns.values == transformed_local_data .columns.values) assert all(transformed_data == transformed_local_data) # same holdout_ratio as above trainer = ModelTrainer(model=ClusteringKMeans(), model_transformations=transformations, train_callback=fit_callback) trainer.train_predict_eval(data=data, hyper_params=ClusteringKMeansHP()) def test_ClusteringKMeansHP(self): hyper_params = ClusteringKMeansHP() assert hyper_params.params_dict == {'num_clusters': 8, 'init_method': 'k-means++', 'num_different_seeds': 10, 'max_iterations': 300, 'precompute_distances': 'auto', 'algorithm': 'auto'} def test_KMeans(self): data = TestHelper.get_iris_data() cluster_data = data.drop(columns='species') trainer = ModelTrainer(model=ClusteringKMeans(evaluate_bss_tss=True), model_transformations=[CenterScaleTransformer()], scores=[SilhouetteScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringKMeansHP(num_clusters=3)) assert trainer.model.model_object.n_clusters == 3 # make sure Score object, when manually calculated, is the expected value, # then verify trainer.training_score score = SilhouetteScore().calculate(clustered_data=CenterScaleTransformer().fit_transform(cluster_data), # noqa clusters=clusters) assert isclose(score, 0.45994823920518646) assert isclose(score, trainer.training_scores[0].value) assert isclose(trainer.model.score, -139.82049635974977) assert isclose(trainer.model.bss_tss_ratio, 0.7669658394004155) assert isclose(adjusted_rand_score(data.species, clusters), 0.6201351808870379) num_cached = trainer.model.data_x_trained_head.shape[0] assert all(data.drop(columns='species').iloc[0:num_cached] == trainer.model.data_x_trained_head) # setosa == 1 # versicolor == 0 # virginica == 2 lookup = ['virginica', 'setosa', 'versicolor'] predicted_clusters = [lookup[x] for x in clusters] # noinspection PyTypeChecker confusion_matrix = ConfusionMatrix(actual_classes=data['species'].values, predicted_classes=predicted_clusters) assert all(confusion_matrix.matrix.setosa.values == [50, 0, 0, 50]) assert all(confusion_matrix.matrix.versicolor.values == [0, 39, 14, 53]) assert all(confusion_matrix.matrix.virginica.values == [0, 11, 36, 47]) assert all(confusion_matrix.matrix.Total.values == [50, 50, 50, 150]) def test_silhouette_stats(self): data = TestHelper.get_iris_data() cluster_data = data.drop(columns='species') cluster_data = CenterScaleTransformer().fit_transform(cluster_data) trainer = ModelTrainer(model=ClusteringKMeans(evaluate_bss_tss=True), model_transformations=None, scores=[SilhouetteScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringKMeansHP(num_clusters=3)) assert trainer.model.model_object.n_clusters == 3 # make sure Score object, when manually calculated, is the expected value, # then verify trainer.training_score score = SilhouetteScore().calculate( clustered_data=CenterScaleTransformer().fit_transform(cluster_data), # noqa clusters=clusters) assert isclose(score, 0.45994823920518646) assert isclose(score, trainer.training_scores[0].value) assert isclose(trainer.model.score, -139.82049635974977) assert isclose(trainer.model.bss_tss_ratio, 0.7669658394004155) assert isclose(adjusted_rand_score(data.species, clusters), 0.6201351808870379) silhouette_stats = Clustering.silhouette_stats(clustered_data=cluster_data, clusters=clusters) file = os.path.join(os.getcwd(), TestHelper.ensure_test_directory('data/test_unsupervised/test_silhouette_stats.pkl')) # noqa TestHelper.ensure_all_values_equal_from_file(file=file, expected_dataframe=silhouette_stats) def test_silhouette_plot(self): data = TestHelper.get_iris_data() cluster_data = data.drop(columns='species') cluster_data = CenterScaleTransformer().fit_transform(cluster_data) trainer = ModelTrainer(model=ClusteringKMeans(evaluate_bss_tss=True), model_transformations=None, scores=[SilhouetteScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringKMeansHP(num_clusters=3)) assert trainer.model.model_object.n_clusters == 3 # make sure Score object, when manually calculated, is the expected value, # then verify trainer.training_score score = SilhouetteScore().calculate( clustered_data=CenterScaleTransformer().fit_transform(cluster_data), # noqa clusters=clusters) assert isclose(score, 0.45994823920518646) assert isclose(score, trainer.training_scores[0].value) assert isclose(trainer.model.score, -139.82049635974977) assert isclose(trainer.model.bss_tss_ratio, 0.7669658394004155) assert isclose(adjusted_rand_score(data.species, clusters), 0.6201351808870379) TestHelper.check_plot('data/test_unsupervised/test_silhouette_plot.png', lambda: Clustering.silhouette_plot(clustered_data=cluster_data, clusters=clusters), set_size_w_h=None) TestHelper.check_plot('data/test_unsupervised/test_silhouette_plot_size.png', lambda: Clustering.silhouette_plot(clustered_data=cluster_data, clusters=clusters, figure_size=(8, 6)), set_size_w_h=None) def test_KMeans_elbow_sse(self): data = TestHelper.get_iris_data() TestHelper.check_plot('data/test_unsupervised/test_kmeans_elbow_plot.png', lambda: Clustering.kmeans_elbow_sse_plot(data=data.drop(columns='species'), num_clusters=list(range(1, 9)), transformations=[CenterScaleTransformer()]), # noqa set_size_w_h=None) data = TestHelper.get_iris_data() TestHelper.check_plot('data/test_unsupervised/test_kmeans_elbow_plot_not_parallelized.png', lambda: Clustering.kmeans_elbow_sse_plot(data=data.drop(columns='species'), num_clusters=list(range(1, 9)), transformations=[CenterScaleTransformer()], # noqa parallelization_cores=0), set_size_w_h=None) def test_KMeans_elbow_bss_tss(self): data = TestHelper.get_iris_data() TestHelper.check_plot('data/test_unsupervised/test_kmeans_elbow_plot_bss_tss.png', lambda: Clustering.kmeans_elbow_bss_tss_plot(data=data.drop(columns='species'), num_clusters=list(range(1, 9)), transformations=[CenterScaleTransformer()]), # noqa set_size_w_h=None) # noinspection SpellCheckingInspection def test_KMeans_heatmap(self): data = TestHelper.get_iris_data() # remove setosa, in order to test 2 clusters with same amount of data, so we can verify axis on graph num_drop = 3 data = data.drop(index=list(range(num_drop))) data.loc[num_drop, 'sepal_length'] = np.nan data.loc[num_drop+1, 'petal_length'] = np.nan assert data.isnull().sum().sum() == 2 # impute missing values by species, then center/scale, then remove the species column transformations = [ImputationTransformer(group_by_column='species'), RemoveColumnsTransformer(columns=['species']), CenterScaleTransformer()] trainer = ModelTrainer(model=ClusteringKMeans(seed=199), model_transformations=transformations) clusters = trainer.train_predict_eval(data=data, hyper_params=ClusteringKMeansHP(num_clusters=3)) assert data.isnull().sum().sum() == 2 # make sure original data wasn't transformed assert all(np.bincount(np.array(clusters)) == [53, 47, 47]) # make sure 2 clusters are same size assert len(clusters) == len(data) # CENTER/SCALE TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_strategy_mean.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=30)) # test rounding specific features/row rounding TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_strategy_mean_round_by_3.png', # noqa lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=30, round_by=3, )) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_strategy_mean_round_by_custom.png', # noqa lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=30, round_by=1, round_by_custom={'sepal_width': 0, 'petal_length': 2} )) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_strategy_mean_font_size.png', # noqa lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=0, plot_size=(8, 4), axis_font_size=5, annotation_font_size=5) ) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_strategy_mean_min_max.png', # noqa lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=30, color_scale_min=-3, color_scale_max=3)) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_strategy_mean_min_max_colormap.png', # noqa lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=30, color_scale_min=-1, color_scale_max=2, color_map='Reds') ) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_actual_mean.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, # noqa trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.ACTUAL, y_axis_rotation=30)) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_actual_median.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, # noqa trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEDIAN, display_values=ClusteringHeatmapValues.ACTUAL, y_axis_rotation=30)) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_centerscale_strategy_median.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, # noqa trans_strategy=ClusteringHeatmapTransStrategy.CENTER_SCALE, agg_strategy=ClusteringHeatmapAggStrategy.MEDIAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=30)) # PERCENTILES TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_percentiles_strategy_mean.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=ClusteringHeatmapTransStrategy.PERCENTILES, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=30)) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_percentiles_actual_mean.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, # noqa trans_strategy=ClusteringHeatmapTransStrategy.PERCENTILES, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.ACTUAL, y_axis_rotation=30)) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_percentiles_actual_median.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, # noqa trans_strategy=ClusteringHeatmapTransStrategy.PERCENTILES, agg_strategy=ClusteringHeatmapAggStrategy.MEDIAN, display_values=ClusteringHeatmapValues.ACTUAL, y_axis_rotation=30)) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_percentiles_strategy_median.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, # noqa trans_strategy=ClusteringHeatmapTransStrategy.PERCENTILES, agg_strategy=ClusteringHeatmapAggStrategy.MEDIAN, display_values=ClusteringHeatmapValues.STRATEGY, y_axis_rotation=30)) # NO transformations TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_no_trans_actual_mean.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=None, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.ACTUAL, )) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_no_trans_actual_mean_min_max.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=None, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.ACTUAL, color_scale_min=-5, color_scale_max=10, )) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_no_trans_strategy_mean.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=None, agg_strategy=ClusteringHeatmapAggStrategy.MEAN, display_values=ClusteringHeatmapValues.STRATEGY, )) TestHelper.check_plot('data/test_unsupervised/test_KMeans_heatmap_no_trans_actual_median.png', lambda: Clustering.cluster_heatmap( data=data.drop(columns='species'), clusters=clusters, trans_strategy=None, agg_strategy=ClusteringHeatmapAggStrategy.MEDIAN, display_values=ClusteringHeatmapValues.ACTUAL, )) assert 'cluster' not in data.columns.values # make sure we are not changing the dataset def test_hierarchical_dendogram_plot(self): data = TestHelper.get_iris_data() cluster_data = data.drop(columns='species') TestHelper.check_plot('data/test_unsupervised/test_hierarchical_dendogram_plot.png', lambda: Clustering.hierarchical_dendogram_plot(data=cluster_data, transformations=[NormalizationVectorSpaceTransformer()], # noqa linkage=ClusteringHierarchicalLinkage.WARD), # noqa set_size_w_h=None) TestHelper.check_plot('data/test_unsupervised/test_hierarchical_dendogram_plot_threshold.png', lambda: Clustering.hierarchical_dendogram_plot(data=cluster_data, transformations=[NormalizationVectorSpaceTransformer()], # noqa linkage=ClusteringHierarchicalLinkage.WARD, # noqa color_threshold=0.5), set_size_w_h=None) def test_Hierarchical_sklearn_normalization(self): data = TestHelper.get_iris_data() cluster_data = data.drop(columns='species') trainer = ModelTrainer(model=ClusteringHierarchical(), model_transformations=[NormalizationVectorSpaceTransformer()], scores=[SilhouetteScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringHierarchicalHP(num_clusters=3)) score = SilhouetteScore().calculate( clustered_data=NormalizationVectorSpaceTransformer().fit_transform(cluster_data), clusters=clusters) assert isclose(score, 0.5562322357473719) assert isclose(score, trainer.training_scores[0].value) assert isclose(adjusted_rand_score(data.species, clusters), 0.8856970310281228) def test_Hierarchical(self): data = TestHelper.get_iris_data() cluster_data = data.drop(columns='species') trainer = ModelTrainer(model=ClusteringHierarchical(), model_transformations=[NormalizationTransformer()], scores=[SilhouetteScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringHierarchicalHP(num_clusters=3)) assert trainer.model.model_object.n_clusters == 3 score = SilhouetteScore().calculate( clustered_data=NormalizationTransformer().fit_transform(cluster_data), clusters=clusters) assert isclose(score, 0.5047999262278894) assert isclose(score, trainer.training_scores[0].value) assert isclose(adjusted_rand_score(data.species, clusters), 0.7195837484778037) num_cached = trainer.model.data_x_trained_head.shape[0] assert all(data.drop(columns='species').iloc[0:num_cached] == trainer.model.data_x_trained_head) # setosa == 1 # versicolor == 0 # virginica == 2 lookup = ['versicolor', 'setosa', 'virginica'] predicted_clusters = [lookup[x] for x in clusters] # noinspection PyTypeChecker confusion_matrix = ConfusionMatrix(actual_classes=data['species'].values, predicted_classes=predicted_clusters) assert all(confusion_matrix.matrix.setosa.values == [50, 0, 0, 50]) assert all(confusion_matrix.matrix.versicolor.values == [0, 50, 17, 67]) assert all(confusion_matrix.matrix.virginica.values == [0, 0, 33, 33]) assert all(confusion_matrix.matrix.Total.values == [50, 50, 50, 150]) def test_Hierarchical_string_index(self): # noinspection SpellCheckingInspection data = TestHelper.get_iris_data() data.index = data.index.astype(str) assert all([isinstance(x, str) for x in data.index.values]) cluster_data = data.drop(columns='species') trainer = ModelTrainer(model=ClusteringHierarchical(), model_transformations=[NormalizationTransformer()], scores=[SilhouetteScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringHierarchicalHP(num_clusters=3)) score = SilhouetteScore().calculate( clustered_data=NormalizationTransformer().fit_transform(cluster_data), clusters=clusters) assert isclose(score, 0.5047999262278894) assert isclose(score, trainer.training_scores[0].value) assert isclose(adjusted_rand_score(data.species, clusters), 0.7195837484778037) num_cached = trainer.model.data_x_trained_head.shape[0] assert all(data.drop(columns='species').iloc[0:num_cached] == trainer.model.data_x_trained_head) # setosa == 1 # versicolor == 0 # virginica == 2 lookup = ['versicolor', 'setosa', 'virginica'] predicted_clusters = [lookup[x] for x in clusters] # noinspection PyTypeChecker confusion_matrix = ConfusionMatrix(actual_classes=data['species'].values, predicted_classes=predicted_clusters) assert all(confusion_matrix.matrix.setosa.values == [50, 0, 0, 50]) assert all(confusion_matrix.matrix.versicolor.values == [0, 50, 17, 67]) assert all(confusion_matrix.matrix.virginica.values == [0, 0, 33, 33]) assert all(confusion_matrix.matrix.Total.values == [50, 50, 50, 150]) def test_DBSCAN(self): # after normalization, default epsilon of 0.5 is too small data = TestHelper.get_iris_data() cluster_data = data.drop(columns='species') trainer = ModelTrainer(model=ClusteringDBSCAN(), model_transformations=[NormalizationTransformer()], scores=[SilhouetteScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringDBSCANHP()) transformed_cluster_data = NormalizationTransformer().fit_transform(cluster_data) score = SilhouetteScore().calculate( clustered_data=transformed_cluster_data, clusters=clusters) assert isclose(score, -1) assert isclose(score, trainer.training_scores[0].value) assert isclose(adjusted_rand_score(data.species, clusters), 0) # try smaller epsilon trainer = ModelTrainer(model=ClusteringDBSCAN(), model_transformations=[NormalizationTransformer()], scores=[SilhouetteScore(), DensityBasedClusteringValidationScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringDBSCANHP(epsilon=0.25, min_samples=4)) assert trainer.model.model_object.eps == 0.25 assert trainer.model.model_object.min_samples == 4 score = SilhouetteScore().calculate( clustered_data=transformed_cluster_data, clusters=clusters) assert isclose(score, 0.5765941443131803) assert isclose(score, trainer.training_scores[0].value) assert isclose(adjusted_rand_score(data.species, clusters), 0.5557898627256278) assert isclose(trainer.training_scores[1].value, hdbscan.validity.validity_index(X=transformed_cluster_data.values, labels=clusters)) num_cached = trainer.model.data_x_trained_head.shape[0] assert all(data.drop(columns='species').iloc[0:num_cached] == trainer.model.data_x_trained_head) lookup = {0: 'setosa', 1: 'versicolor', -1: 'virginica'} predicted_clusters = [lookup[x] for x in clusters] # noinspection PyTypeChecker confusion_matrix = ConfusionMatrix(actual_classes=data['species'].values, predicted_classes=predicted_clusters) assert all(confusion_matrix.matrix.setosa.values == [49, 0, 0, 49]) assert all(confusion_matrix.matrix.versicolor.values == [0, 50, 49, 99]) assert all(confusion_matrix.matrix.virginica.values == [1, 0, 1, 2]) assert all(confusion_matrix.matrix.Total.values == [50, 50, 50, 150]) def test_HDBSCAN(self): data = TestHelper.get_iris_data() cluster_data = data.drop(columns='species') trainer = ModelTrainer(model=ClusteringHDBSCAN(), model_transformations=[NormalizationTransformer()], scores=[SilhouetteScore(), DensityBasedClusteringValidationScore()]) clusters = trainer.train_predict_eval(data=cluster_data, hyper_params=ClusteringHDBSCANHP(min_cluster_size=2, min_samples=5)) assert trainer.model.model_object.min_cluster_size == 2 assert trainer.model.model_object.min_samples == 5 transformed_cluster_data = NormalizationTransformer().fit_transform(cluster_data) score = SilhouetteScore().calculate( clustered_data=transformed_cluster_data, clusters=clusters) assert isclose(score, 0.630047128435471) assert isclose(score, trainer.training_scores[0].value) assert trainer.training_scores[0].name == Metric.SILHOUETTE.value assert isclose(adjusted_rand_score(data.species, clusters), 0.5681159420289855) # validity_index assert trainer.training_scores[1].name == Metric.DENSITY_BASED_CLUSTERING_VALIDATION.value assert isclose(trainer.training_scores[1].value, hdbscan.validity.validity_index(X=transformed_cluster_data.values, labels=clusters)) # noinspection SpellCheckingInspection def test_ClusteringSearcher(self): data = TestHelper.get_iris_data() center_scaled_data = CenterScaleTransformer().fit_transform(data.drop(columns='species')) normalized_data = NormalizationTransformer().fit_transform(data.drop(columns='species')) model_infos = [ ModelInfo(model=ClusteringKMeans(), description='KMeans - CenterScale', transformations=[CenterScaleTransformer()], hyper_params=ClusteringKMeansHP(), hyper_params_grid=HyperParamsGrid(params_dict={'num_clusters': [2, 3, 4, 5, 6, 7]})), ModelInfo(model=ClusteringDBSCAN(), description='DBSCAN - Normalization', transformations=[NormalizationTransformer()], hyper_params=ClusteringDBSCANHP(), hyper_params_grid=HyperParamsGrid(params_dict={'epsilon': [0.1, 0.15, 0.2, 0.25, 0.3], 'min_samples': [3, 4, 5, 6]})), ] searcher = ClusteringSearcher( model_infos=model_infos, scores=[SilhouetteScore(), DensityBasedClusteringValidationScore()], global_transformations=[RemoveColumnsTransformer(columns=['species'])], ) results = searcher.search(data=data) assert results.score_names == [Metric.SILHOUETTE.value, Metric.DENSITY_BASED_CLUSTERING_VALIDATION.value] # noqa ###################################################################################################### # verify k-means scores ###################################################################################################### silhouettes = [] dbcvs = [] kmeans_num_clusters = model_infos[0].hyper_params_grid.params_grid.num_clusters for num_clusters in kmeans_num_clusters: trainer = ModelTrainer(model=ClusteringKMeans(), scores=[SilhouetteScore(), DensityBasedClusteringValidationScore()]) trainer.train_predict_eval(center_scaled_data, hyper_params=ClusteringKMeansHP(num_clusters=num_clusters)) silhouettes.append(trainer.training_scores[0].value) dbcvs.append(trainer.training_scores[1].value) for index in range(len(model_infos[0].hyper_params_grid.params_grid)): assert isclose(results.results.iloc[index].silhouette, silhouettes[index]) assert isclose(results.results.iloc[index].DBCV, dbcvs[index]) ###################################################################################################### # verify DBSCAN scores ###################################################################################################### silhouettes = [] dbcvs = [] starting_index = len(kmeans_num_clusters) dbscan_params_grid = model_infos[1].hyper_params_grid.params_grid for index in range(len(dbscan_params_grid)): epsilon = dbscan_params_grid.iloc[index].epsilon min_samples = dbscan_params_grid.iloc[index].min_samples trainer = ModelTrainer(model=ClusteringDBSCAN(), scores=[SilhouetteScore(), DensityBasedClusteringValidationScore()]) trainer.train_predict_eval(normalized_data, hyper_params=ClusteringDBSCANHP(epsilon=epsilon, min_samples=min_samples)) silhouettes.append(trainer.training_scores[0].value) dbcvs.append(trainer.training_scores[1].value) for index in range(len(dbscan_params_grid)): assert isclose(results.results.iloc[starting_index + index].silhouette, silhouettes[index]) assert isclose(results.results.iloc[starting_index + index].DBCV, dbcvs[index]) file = os.path.join(os.getcwd(), TestHelper.ensure_test_directory('data/test_unsupervised/UnsupervisedSearcher.pkl')) # noqa TestHelper.ensure_all_values_equal_from_file(file=file, expected_dataframe=results.results) def test_ClusteringSearcher_duplicate_descriptions(self): model_infos = [ ModelInfo(model=ClusteringKMeans(), description='1', transformations=[CenterScaleTransformer()], hyper_params=ClusteringKMeansHP(), hyper_params_grid=HyperParamsGrid(params_dict={'num_clusters': [2, 3, 4, 5, 6, 7]})), ModelInfo(model=ClusteringDBSCAN(), description='1', transformations=[NormalizationTransformer()], hyper_params=ClusteringDBSCANHP(), hyper_params_grid=HyperParamsGrid(params_dict={'epsilon': [0.1, 0.15, 0.2, 0.25, 0.3], 'min_samples': [3, 4, 5, 6]})), ] self.assertRaises(AssertionError, lambda: ClusteringSearcher(model_infos=model_infos, scores=[SilhouetteScore(), DensityBasedClusteringValidationScore()], global_transformations=[RemoveColumnsTransformer(columns=['species'])]) # noqa ) def test_ClusteringSearcher_plots(self): data = TestHelper.get_iris_data() model_infos = [ ModelInfo(model=ClusteringKMeans(), description='KMeans - CenterScale', transformations=[CenterScaleTransformer()], hyper_params=ClusteringKMeansHP(), hyper_params_grid=HyperParamsGrid(params_dict={'num_clusters': [2, 3, 4, 5, 6, 7]})), ModelInfo(model=ClusteringDBSCAN(), description='DBSCAN - Normalization', transformations=[NormalizationTransformer()], hyper_params=ClusteringDBSCANHP(), hyper_params_grid=HyperParamsGrid(params_dict={'epsilon': [0.1, 0.15, 0.2, 0.25, 0.3], 'min_samples': [3, 4, 5, 6]})), ModelInfo(model=ClusteringDBSCAN(), description='DBSCAN - Normalization - VC', transformations=[NormalizationVectorSpaceTransformer()], hyper_params=ClusteringDBSCANHP(), hyper_params_grid=HyperParamsGrid(params_dict={'epsilon': [0.1, 0.15, 0.2, 0.25, 0.3], 'min_samples': [3, 4, 5, 6]})), ModelInfo(model=ClusteringHDBSCAN(), description='HDBSCAN - Normalization', transformations=[NormalizationTransformer()], hyper_params=ClusteringHDBSCANHP(), hyper_params_grid=HyperParamsGrid(params_dict={'min_cluster_size': [2, 3, 4, 5, 6], 'min_samples': [3, 4, 5, 6]})), ] searcher = ClusteringSearcher( model_infos=model_infos, scores=[SilhouetteScore(), DensityBasedClusteringValidationScore()], global_transformations=[RemoveColumnsTransformer(columns=['species'])], ) results = searcher.search(data=data) TestHelper.check_plot('data/test_unsupervised/ClusteringSearcher_heatmap.png', lambda: results.heatmap(), set_size_w_h=None)
# 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 base64 import datetime import struct import uuid from cryptography import fernet import msgpack from oslo_log import log from oslo_utils import timeutils import six from six.moves import map from keystone.auth import plugins as auth_plugins from keystone.common import fernet_utils as utils from keystone.common import utils as ks_utils import keystone.conf from keystone import exception from keystone.i18n import _ CONF = keystone.conf.CONF LOG = log.getLogger(__name__) # Fernet byte indexes as computed by pypi/keyless_fernet and defined in # https://github.com/fernet/spec TIMESTAMP_START = 1 TIMESTAMP_END = 9 class TokenFormatter(object): """Packs and unpacks payloads into tokens for transport.""" @property def crypto(self): """Return a cryptography instance. You can extend this class with a custom crypto @property to provide your own token encoding / decoding. For example, using a different cryptography library (e.g. ``python-keyczar``) or to meet arbitrary security requirements. This @property just needs to return an object that implements ``encrypt(plaintext)`` and ``decrypt(ciphertext)``. """ fernet_utils = utils.FernetUtils( CONF.fernet_tokens.key_repository, CONF.fernet_tokens.max_active_keys, 'fernet_tokens' ) keys = fernet_utils.load_keys() if not keys: raise exception.KeysNotFound() fernet_instances = [fernet.Fernet(key) for key in keys] return fernet.MultiFernet(fernet_instances) def pack(self, payload): """Pack a payload for transport as a token. :type payload: six.binary_type :rtype: six.text_type """ # base64 padding (if any) is not URL-safe return self.crypto.encrypt(payload).rstrip(b'=').decode('utf-8') def unpack(self, token): """Unpack a token, and validate the payload. :type token: six.text_type :rtype: six.binary_type """ token = TokenFormatter.restore_padding(token) try: return self.crypto.decrypt(token.encode('utf-8')) except fernet.InvalidToken: raise exception.ValidationError( _('Could not recognize Fernet token')) @classmethod def restore_padding(cls, token): """Restore padding based on token size. :param token: token to restore padding on :type token: six.text_type :returns: token with correct padding """ # Re-inflate the padding mod_returned = len(token) % 4 if mod_returned: missing_padding = 4 - mod_returned token += '=' * missing_padding return token @classmethod def creation_time(cls, fernet_token): """Return the creation time of a valid Fernet token. :type fernet_token: six.text_type """ fernet_token = TokenFormatter.restore_padding(fernet_token) # fernet_token is six.text_type # Fernet tokens are base64 encoded, so we need to unpack them first # urlsafe_b64decode() requires six.binary_type token_bytes = base64.urlsafe_b64decode(fernet_token.encode('utf-8')) # slice into the byte array to get just the timestamp timestamp_bytes = token_bytes[TIMESTAMP_START:TIMESTAMP_END] # convert those bytes to an integer # (it's a 64-bit "unsigned long long int" in C) timestamp_int = struct.unpack(">Q", timestamp_bytes)[0] # and with an integer, it's trivial to produce a datetime object issued_at = datetime.datetime.utcfromtimestamp(timestamp_int) return issued_at def create_token(self, user_id, expires_at, audit_ids, payload_class, methods=None, system=None, domain_id=None, project_id=None, trust_id=None, federated_group_ids=None, identity_provider_id=None, protocol_id=None, access_token_id=None, app_cred_id=None): """Given a set of payload attributes, generate a Fernet token.""" version = payload_class.version payload = payload_class.assemble( user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id ) versioned_payload = (version,) + payload serialized_payload = msgpack.packb(versioned_payload) token = self.pack(serialized_payload) # NOTE(lbragstad): We should warn against Fernet tokens that are over # 255 characters in length. This is mostly due to persisting the tokens # in a backend store of some kind that might have a limit of 255 # characters. Even though Keystone isn't storing a Fernet token # anywhere, we can't say it isn't being stored somewhere else with # those kind of backend constraints. if len(token) > 255: LOG.info('Fernet token created with length of %d ' 'characters, which exceeds 255 characters', len(token)) return token def validate_token(self, token): """Validate a Fernet token and returns the payload attributes. :type token: six.text_type """ serialized_payload = self.unpack(token) versioned_payload = msgpack.unpackb(serialized_payload) version, payload = versioned_payload[0], versioned_payload[1:] for payload_class in _PAYLOAD_CLASSES: if version == payload_class.version: (user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id) = payload_class.disassemble(payload) break else: # If the token_format is not recognized, raise ValidationError. raise exception.ValidationError(_( 'This is not a recognized Fernet payload version: %s') % version) # FIXME(lbragstad): Without this, certain token validation tests fail # when running with python 3. Once we get further along in this # refactor, we should be better about handling string encoding/types at # the edges of the application. if isinstance(system, bytes): system = system.decode('utf-8') # rather than appearing in the payload, the creation time is encoded # into the token format itself issued_at = TokenFormatter.creation_time(token) issued_at = ks_utils.isotime(at=issued_at, subsecond=True) expires_at = timeutils.parse_isotime(expires_at) expires_at = ks_utils.isotime(at=expires_at, subsecond=True) return (user_id, methods, audit_ids, system, domain_id, project_id, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id, issued_at, expires_at) class BasePayload(object): # each payload variant should have a unique version version = None @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): """Assemble the payload of a token. :param user_id: identifier of the user in the token request :param methods: list of authentication methods used :param system: a string including system scope information :param project_id: ID of the project to scope to :param domain_id: ID of the domain to scope to :param expires_at: datetime of the token's expiration :param audit_ids: list of the token's audit IDs :param trust_id: ID of the trust in effect :param federated_group_ids: list of group IDs from SAML assertion :param identity_provider_id: ID of the user's identity provider :param protocol_id: federated protocol used for authentication :param access_token_id: ID of the secret in OAuth1 authentication :param app_cred_id: ID of the application credential in effect :returns: the payload of a token """ raise NotImplementedError() @classmethod def disassemble(cls, payload): """Disassemble an unscoped payload into the component data. The tuple consists of:: (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id,` access_token_id, app_cred_id) * ``methods`` are the auth methods. Fields will be set to None if they didn't apply to this payload type. :param payload: this variant of payload :returns: a tuple of the payloads component data """ raise NotImplementedError() @classmethod def convert_uuid_hex_to_bytes(cls, uuid_string): """Compress UUID formatted strings to bytes. :param uuid_string: uuid string to compress to bytes :returns: a byte representation of the uuid """ uuid_obj = uuid.UUID(uuid_string) return uuid_obj.bytes @classmethod def convert_uuid_bytes_to_hex(cls, uuid_byte_string): """Generate uuid.hex format based on byte string. :param uuid_byte_string: uuid string to generate from :returns: uuid hex formatted string """ uuid_obj = uuid.UUID(bytes=uuid_byte_string) return uuid_obj.hex @classmethod def _convert_time_string_to_float(cls, time_string): """Convert a time formatted string to a float. :param time_string: time formatted string :returns: a timestamp as a float """ time_object = timeutils.parse_isotime(time_string) return (timeutils.normalize_time(time_object) - datetime.datetime.utcfromtimestamp(0)).total_seconds() @classmethod def _convert_float_to_time_string(cls, time_float): """Convert a floating point timestamp to a string. :param time_float: integer representing timestamp :returns: a time formatted strings """ time_object = datetime.datetime.utcfromtimestamp(time_float) return ks_utils.isotime(time_object, subsecond=True) @classmethod def attempt_convert_uuid_hex_to_bytes(cls, value): """Attempt to convert value to bytes or return value. :param value: value to attempt to convert to bytes :returns: tuple containing boolean indicating whether user_id was stored as bytes and uuid value as bytes or the original value """ try: return (True, cls.convert_uuid_hex_to_bytes(value)) except ValueError: # this might not be a UUID, depending on the situation (i.e. # federation) return (False, value) @classmethod def base64_encode(cls, s): """Encode a URL-safe string. :type s: six.text_type :rtype: six.text_type """ # urlsafe_b64encode() returns six.binary_type so need to convert to # six.text_type, might as well do it before stripping. return base64.urlsafe_b64encode(s).decode('utf-8').rstrip('=') @classmethod def random_urlsafe_str_to_bytes(cls, s): """Convert a string from :func:`random_urlsafe_str()` to six.binary_type. :type s: six.text_type :rtype: six.binary_type """ # urlsafe_b64decode() requires str, unicode isn't accepted. s = str(s) # restore the padding (==) at the end of the string return base64.urlsafe_b64decode(s + '==') class UnscopedPayload(BasePayload): version = 0 @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) return (b_user_id, methods, expires_at_int, b_audit_ids) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) expires_at_str = cls._convert_float_to_time_string(payload[2]) audit_ids = list(map(cls.base64_encode, payload[3])) system = None project_id = None domain_id = None trust_id = None federated_group_ids = None identity_provider_id = None protocol_id = None access_token_id = None app_cred_id = None return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id) class DomainScopedPayload(BasePayload): version = 1 @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) try: b_domain_id = cls.convert_uuid_hex_to_bytes(domain_id) except ValueError: # the default domain ID is configurable, and probably isn't a UUID if domain_id == CONF.identity.default_domain_id: b_domain_id = domain_id else: raise expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) return (b_user_id, methods, b_domain_id, expires_at_int, b_audit_ids) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) try: domain_id = cls.convert_uuid_bytes_to_hex(payload[2]) except ValueError: # the default domain ID is configurable, and probably isn't a UUID if six.PY3 and isinstance(payload[2], six.binary_type): payload[2] = payload[2].decode('utf-8') if payload[2] == CONF.identity.default_domain_id: domain_id = payload[2] else: raise expires_at_str = cls._convert_float_to_time_string(payload[3]) audit_ids = list(map(cls.base64_encode, payload[4])) system = None project_id = None trust_id = None federated_group_ids = None identity_provider_id = None protocol_id = None access_token_id = None app_cred_id = None return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id) class ProjectScopedPayload(BasePayload): version = 2 @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) b_project_id = cls.attempt_convert_uuid_hex_to_bytes(project_id) expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) return (b_user_id, methods, b_project_id, expires_at_int, b_audit_ids) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) (is_stored_as_bytes, project_id) = payload[2] if is_stored_as_bytes: project_id = cls.convert_uuid_bytes_to_hex(project_id) expires_at_str = cls._convert_float_to_time_string(payload[3]) audit_ids = list(map(cls.base64_encode, payload[4])) system = None domain_id = None trust_id = None federated_group_ids = None identity_provider_id = None protocol_id = None access_token_id = None app_cred_id = None return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id) class TrustScopedPayload(BasePayload): version = 3 @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) b_project_id = cls.attempt_convert_uuid_hex_to_bytes(project_id) b_trust_id = cls.convert_uuid_hex_to_bytes(trust_id) expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) return (b_user_id, methods, b_project_id, expires_at_int, b_audit_ids, b_trust_id) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) (is_stored_as_bytes, project_id) = payload[2] if is_stored_as_bytes: project_id = cls.convert_uuid_bytes_to_hex(project_id) expires_at_str = cls._convert_float_to_time_string(payload[3]) audit_ids = list(map(cls.base64_encode, payload[4])) trust_id = cls.convert_uuid_bytes_to_hex(payload[5]) system = None domain_id = None federated_group_ids = None identity_provider_id = None protocol_id = None access_token_id = None app_cred_id = None return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id) class FederatedUnscopedPayload(BasePayload): version = 4 @classmethod def pack_group_id(cls, group_dict): return cls.attempt_convert_uuid_hex_to_bytes(group_dict['id']) @classmethod def unpack_group_id(cls, group_id_in_bytes): (is_stored_as_bytes, group_id) = group_id_in_bytes if is_stored_as_bytes: group_id = cls.convert_uuid_bytes_to_hex(group_id) return {'id': group_id} @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) b_group_ids = list(map(cls.pack_group_id, federated_group_ids)) b_idp_id = cls.attempt_convert_uuid_hex_to_bytes(identity_provider_id) expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) return (b_user_id, methods, b_group_ids, b_idp_id, protocol_id, expires_at_int, b_audit_ids) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) group_ids = list(map(cls.unpack_group_id, payload[2])) (is_stored_as_bytes, idp_id) = payload[3] if is_stored_as_bytes: idp_id = cls.convert_uuid_bytes_to_hex(idp_id) else: idp_id = idp_id.decode('utf-8') protocol_id = payload[4] if isinstance(protocol_id, six.binary_type): protocol_id = protocol_id.decode('utf-8') expires_at_str = cls._convert_float_to_time_string(payload[5]) audit_ids = list(map(cls.base64_encode, payload[6])) system = None project_id = None domain_id = None trust_id = None access_token_id = None app_cred_id = None return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, group_ids, idp_id, protocol_id, access_token_id, app_cred_id) class FederatedScopedPayload(FederatedUnscopedPayload): version = None @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) b_scope_id = cls.attempt_convert_uuid_hex_to_bytes( project_id or domain_id) b_group_ids = list(map(cls.pack_group_id, federated_group_ids)) b_idp_id = cls.attempt_convert_uuid_hex_to_bytes(identity_provider_id) expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) return (b_user_id, methods, b_scope_id, b_group_ids, b_idp_id, protocol_id, expires_at_int, b_audit_ids) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) (is_stored_as_bytes, scope_id) = payload[2] if is_stored_as_bytes: scope_id = cls.convert_uuid_bytes_to_hex(scope_id) else: # NOTE(lbragstad): We assembled the token payload scope as a tuple # (False, domain_id) for cases like (False, 'default'), since the # default domain ID isn't converted to a byte string when it's not # in UUID format. Despite the boolean indicator in the tuple that # denotes if the value is stored as a byte string or not, msgpack # apparently returns the serialized input as byte strings anyway. # For example, this means what we though we were passing in as # (False, 'default') during token creation actually comes out as # (False, b'default') in token validation through msgpack, which # clearly isn't correct according to our boolean indicator. This # causes comparison issues due to different string types (e.g., # b'default' != 'default') with python 3. See bug 1813085 for # details. We use this pattern for other strings in the payload # like idp_id and protocol_id for the same reason. if six.PY3 and isinstance(scope_id, six.binary_type): scope_id = scope_id.decode('utf-8') project_id = ( scope_id if cls.version == FederatedProjectScopedPayload.version else None) domain_id = ( scope_id if cls.version == FederatedDomainScopedPayload.version else None) group_ids = list(map(cls.unpack_group_id, payload[3])) (is_stored_as_bytes, idp_id) = payload[4] if is_stored_as_bytes: idp_id = cls.convert_uuid_bytes_to_hex(idp_id) else: if six.PY3 and isinstance(idp_id, six.binary_type): idp_id = idp_id.decode('utf-8') protocol_id = payload[5] if six.PY3 and isinstance(protocol_id, six.binary_type): protocol_id = protocol_id.decode('utf-8') expires_at_str = cls._convert_float_to_time_string(payload[6]) audit_ids = list(map(cls.base64_encode, payload[7])) system = None trust_id = None access_token_id = None app_cred_id = None return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, group_ids, idp_id, protocol_id, access_token_id, app_cred_id) class FederatedProjectScopedPayload(FederatedScopedPayload): version = 5 class FederatedDomainScopedPayload(FederatedScopedPayload): version = 6 class OauthScopedPayload(BasePayload): version = 7 @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) b_project_id = cls.attempt_convert_uuid_hex_to_bytes(project_id) expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) b_access_token_id = cls.attempt_convert_uuid_hex_to_bytes( access_token_id) return (b_user_id, methods, b_project_id, b_access_token_id, expires_at_int, b_audit_ids) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) (is_stored_as_bytes, project_id) = payload[2] if is_stored_as_bytes: project_id = cls.convert_uuid_bytes_to_hex(project_id) (is_stored_as_bytes, access_token_id) = payload[3] if is_stored_as_bytes: access_token_id = cls.convert_uuid_bytes_to_hex(access_token_id) expires_at_str = cls._convert_float_to_time_string(payload[4]) audit_ids = list(map(cls.base64_encode, payload[5])) system = None domain_id = None trust_id = None federated_group_ids = None identity_provider_id = None protocol_id = None app_cred_id = None return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id) class SystemScopedPayload(BasePayload): version = 8 @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) return (b_user_id, methods, system, expires_at_int, b_audit_ids) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) system = payload[2] expires_at_str = cls._convert_float_to_time_string(payload[3]) audit_ids = list(map(cls.base64_encode, payload[4])) project_id = None domain_id = None trust_id = None federated_group_ids = None identity_provider_id = None protocol_id = None access_token_id = None app_cred_id = None return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id) class ApplicationCredentialScopedPayload(BasePayload): version = 9 @classmethod def assemble(cls, user_id, methods, system, project_id, domain_id, expires_at, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id): b_user_id = cls.attempt_convert_uuid_hex_to_bytes(user_id) methods = auth_plugins.convert_method_list_to_integer(methods) b_project_id = cls.attempt_convert_uuid_hex_to_bytes(project_id) expires_at_int = cls._convert_time_string_to_float(expires_at) b_audit_ids = list(map(cls.random_urlsafe_str_to_bytes, audit_ids)) b_app_cred_id = cls.attempt_convert_uuid_hex_to_bytes(app_cred_id) return (b_user_id, methods, b_project_id, expires_at_int, b_audit_ids, b_app_cred_id) @classmethod def disassemble(cls, payload): (is_stored_as_bytes, user_id) = payload[0] if is_stored_as_bytes: user_id = cls.convert_uuid_bytes_to_hex(user_id) methods = auth_plugins.convert_integer_to_method_list(payload[1]) (is_stored_as_bytes, project_id) = payload[2] if is_stored_as_bytes: project_id = cls.convert_uuid_bytes_to_hex(project_id) expires_at_str = cls._convert_float_to_time_string(payload[3]) audit_ids = list(map(cls.base64_encode, payload[4])) system = None domain_id = None trust_id = None federated_group_ids = None identity_provider_id = None protocol_id = None access_token_id = None (is_stored_as_bytes, app_cred_id) = payload[5] if is_stored_as_bytes: app_cred_id = cls.convert_uuid_bytes_to_hex(app_cred_id) return (user_id, methods, system, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_group_ids, identity_provider_id, protocol_id, access_token_id, app_cred_id) _PAYLOAD_CLASSES = [ UnscopedPayload, DomainScopedPayload, ProjectScopedPayload, TrustScopedPayload, FederatedUnscopedPayload, FederatedProjectScopedPayload, FederatedDomainScopedPayload, OauthScopedPayload, SystemScopedPayload, ApplicationCredentialScopedPayload, ]
from .module import Module from .pipeline import Pipeline from .pipeline import PipelineNode from .module import Module2 from .pipeline import Pipeline2 from .pipeline import Node
# CloudKit Helper # # # Based off the following # - CloudKitCatalog (c) 2016, Apple # - PyCloudKit. Created on 09.02.2016 (c) 2015 Andreas Schulz # - requests-cloudkit Copyright 2016 Lionheart Software LLC from __future__ import print_function import ecdsa import base64 import hashlib import datetime import sys import json import urllib.parse import urllib.request import urllib.response KEY_ID = '99e04a281f141f4bce822833bd8e87827b91489f1f0601a721eb0c3adf788681' CONTAINER = 'iCloud.mobi.uchicago.twenty-nineteen-cloudkit' def cloudkit_request(cloudkit_resource_url, data): """Uses HTTP GET or POST to interact with CloudKit. If data is empty, Uses GET, else, POSTs the data. """ # Get ISO 8601 date, cut milliseconds. date = datetime.datetime.utcnow().isoformat()[:-7] + 'Z' # Load JSON request from config. _hash = hashlib.sha256(data.encode('utf-8')).digest() body = base64.b64encode(_hash).decode('utf-8') # Construct URL to CloudKit container. web_service_url = '/database/1/' + CONTAINER + cloudkit_resource_url # Load API key from config. key_id = KEY_ID # Read out certificate file corresponding to API key. with open('eckey.pem', 'r') as pem_file: signing_key = ecdsa.SigningKey.from_pem(pem_file.read()) # Construct payload. unsigned_data = ':'.join([date, body, web_service_url]).encode('utf-8') # Sign payload via certificate. signed_data = signing_key.sign(unsigned_data, hashfunc=hashlib.sha256, sigencode=ecdsa.util.sigencode_der) signature = base64.b64encode(signed_data).decode('utf-8') headers = { 'X-Apple-CloudKit-Request-KeyID': key_id, 'X-Apple-CloudKit-Request-ISO8601Date': date, 'X-Apple-CloudKit-Request-SignatureV1': signature } if data: req_type = 'POST' else: req_type = 'GET' result = curl('https://api.apple-cloudkit.com' + web_service_url, req_type=req_type, data=data, headers=headers) return result def curl(url, params=None, auth=None, req_type='GET', data=None, headers=None): """Provides HTTP interaction like curl.""" print("URL: ", url) print("Data: ", data) print("Headers: ", headers) print("Params: ", params) post_req = ['POST', 'PUT'] get_req = ['GET', 'DELETE'] if params is not None: url += '?' + urllib.parse.urlencode(params) if req_type not in post_req + get_req: raise IOError('Wrong request type "%s" passed' % req_type) _headers = {} handler_chain = [] if auth is not None: manager = urllib.request.HTTPPasswordMgrWithDefaultRealm() manager.add_password(None, url, auth['user'], auth['pass']) handler_chain.append(urllib.request.HTTPBasicAuthHandler(manager)) if req_type in post_req and data is not None: _headers['Content-Length'] = len(data) if headers is not None: _headers.update(headers) director = urllib.request.build_opener(*handler_chain) if req_type in post_req: if sys.version_info.major < 3: _data = bytes(data) else: _data = bytes(data, encoding='utf8') req = urllib.request.Request(url, headers=_headers, data=_data) else: req = urllib.request.Request(url, headers=_headers) req.get_method = lambda: req_type result = director.open(req) return { 'httpcode': result.code, 'headers': result.info(), 'content': result.read().decode('utf-8') } def query_records(record_type): """Queries CloudKit for all records of type record_type.""" json_query = { 'query': { 'recordType': record_type } } records = [] while True: result_query_authors = cloudkit_request( '/development/public/records/query', json.dumps(json_query)) result_query_authors = json.loads(result_query_authors['content']) records += result_query_authors['records'] if 'continuationMarker' in result_query_authors.keys(): json_query['continuationMarker'] = \ result_query_authors['continuationMarker'] else: break return records def write_json_to_file(json_data, file_name="results.json"): """Write JSON to file in pretty notation for debugging""" print(json_data) with open('data/'+file_name, 'w') as outfile: json.dump(json_data, outfile, sort_keys = True, indent = 4,ensure_ascii = False) def dump_zones(): """Print out the zones""" print('Requesting list of zones...') result_zones = cloudkit_request('/development/public/zones/list', '') print("Zones: ", result_zones['content'])
#!/usr/bin/env python import sys from PyQt5 import QtGui, QtWidgets, QtCore #create class for QPix map that just changes picture based on button pressest class WindowScreen(QtWidgets.QWidget): def __init__(self): super().__init__() self.string_of_commands = '' self.setWindowTitle("Trajectory Planner") self.setGeometry(500, 500, 900, 500) self.start_button_settings() self.stop_button_settings() self.clear_button_settings() self.line_edit = QtWidgets.QLineEdit() self.line_edit.setReadOnly(True) window_horiz = self.init_ui() self.setLayout(window_horiz) self.show() def start_button_settings(self): self.start_button = QtWidgets.QPushButton("Start") self.start_button.setStyleSheet("background-color: green") self.start_button.setFixedHeight(70) self.start_button.clicked.connect(self.button_click) def stop_button_settings(self): self.stop_button = QtWidgets.QPushButton("Stop") self.stop_button.setStyleSheet("background-color: red") self.stop_button.setFixedHeight(70) self.stop_button.clicked.connect(self.button_click) def clear_button_settings(self): self.clear_button = QtWidgets.QPushButton("Clear") self.clear_button.setFixedHeight(70) self.clear_button.clicked.connect(self.button_click) def horizontal_lay(self): horizontal = QtWidgets.QHBoxLayout() horizontal.stretch(1) horizontal.addWidget(self.start_button) horizontal.addWidget(self.stop_button) horizontal.addWidget(self.clear_button) return horizontal def image_viewer(self): hoops_visual = QtGui.QPixmap("hooplayout.PNG") hoops_visual = hoops_visual.scaled(512, 512, QtCore.Qt.KeepAspectRatio) label_hoops = QtWidgets.QLabel(self) label_hoops.setPixmap(hoops_visual) return label_hoops def button_click(self): sender = self.sender() if sender.text() == "Clear": self.line_edit.clear() self.string_of_commands = '' def command_click(self, button_list): sender = self.sender() if sender.text() in button_list: self.string_of_commands = self.string_of_commands + sender.text() self.line_edit.setText(str(self.string_of_commands)) def init_ui(self): grid = QtWidgets.QGridLayout() horizontal_layout = self.horizontal_lay() button_items = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2', 'E1', 'E2'] positions = [(i, j) for i in range(3) for j in range(4)] for button_name, position in zip(button_items, positions): button = QtWidgets.QPushButton(button_name) button.setFixedHeight(50) button.clicked.connect(lambda: self.command_click(button_items)) grid.addWidget(button, *position) label_hoops = self.image_viewer() vertical_layout_1 = QtWidgets.QVBoxLayout() vertical_layout_1.addWidget(label_hoops) vertical_layout_1.addWidget(self.line_edit) vertical_layout_2 = QtWidgets.QVBoxLayout() vertical_layout_2.addLayout(grid) vertical_layout_2.addLayout(horizontal_layout) window_horizontal = QtWidgets.QHBoxLayout() window_horizontal.addLayout(vertical_layout_1) window_horizontal.addLayout(vertical_layout_2) return window_horizontal if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = WindowScreen() sys.exit(app.exec_())
# automatically generated by the FlatBuffers compiler, do not modify # namespace: graph class ExecutionMode(object): SEQUENTIAL = 0 STRICT = 1 AUTO = 2
import sys from setuptools import setup VERSION = '0.0.1' DESCRIPTION = 'WRITE SOMETHING INTELLIGENT HERE!' CLASSIFIERS = ['Development status :: 3 - Alpha', 'Intended Audience :: Ay250 grader', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.9'] setup(name='calcalc', version=VERSION, description=DESCRIPTION, long_description=DESCRIPTION, long_description_content_type='text/x-rst', classifiers=CLASSIFIERS, author='Casey Lam', author_email='casey_lam@berkeley.edu', url='http://github.com/caseylam/calcalc', python_requires='>=3', license='BSD', keywords='homework', packages=['calcalc'], platforms=['any'], setup_requires=['pytest_runner'], tests_require=['pytest'])
from dataclasses import dataclass from enum import Enum from typing import Optional, List, Sequence, Any import numpy as np from tabulate import tabulate from pyqumo.matrix import str_array from pyqumo.random import CountableDistribution, Distribution from pyqumo.sim.helpers import build_statistics, FiniteFifoQueue, \ InfiniteFifoQueue, Server, Queue, TimeSizeRecords, Statistics @dataclass class Packet: """ Packet representation for G/G/1/N model. Stores timestamps: when the packet arrived (created_at), started serving (service_started_at) and finished serving (departed_at). Also stores flags, indicating whether the packet was dropped or was completely served. Packets arrived in the end of the modeling, may not be served, as well as dropped packets. """ created_at: float service_started_at: Optional[float] = None departed_at: Optional[float] = None dropped: bool = False served: bool = False class Records: """ Records for G/G/1/N statistical analysis. """ def __init__(self): self._packets: List[Packet] = [] self._system_size = TimeSizeRecords() def add_packet(self, packet: Packet): self._packets.append(packet) @property def system_size(self): return self._system_size @property def packets(self): return self._packets @dataclass class Params: """ Model parameters: arrival and service processes, queue capacity and limits. """ arrival: Any service: Any queue_capacity: int max_packets: int = 1000000 max_time: float = np.inf @dataclass class Results: """ Results returned from G/G/1/N model simulation. """ system_size: Optional[CountableDistribution] = None queue_size: Optional[CountableDistribution] = None busy: Optional[CountableDistribution] = None loss_prob: float = 0.0 departures: Optional[Statistics] = None response_time: Optional[Statistics] = None wait_time: Optional[Statistics] = None real_time: Optional[float] = 0.0 @property def utilization(self) -> float: """ Get utilization coefficient, that is `Busy = 1` probability. """ return self.busy.pmf(1) def tabulate(self) -> str: """ Build a pretty formatted table with all key properties. """ system_size_pmf = [ self.system_size.pmf(x) for x in range(self.system_size.truncated_at + 1)] queue_size_pmf = [ self.queue_size.pmf(x) for x in range(self.queue_size.truncated_at + 1)] items = [ ('System size PMF', str_array(system_size_pmf)), ('System size average', self.system_size.mean), ('System size std.dev.', self.system_size.std), ('Queue size PMF', str_array(queue_size_pmf)), ('Queue size average', self.queue_size.mean), ('Queue size std.dev.', self.queue_size.std), ('Utilization', self.utilization), ('Loss probability', self.loss_prob), ('Departures, average', self.departures.avg), ('Departures, std.dev.', self.departures.std), ('Response time, average', self.response_time.avg), ('Response time, std.dev.', self.response_time.std), ('Wait time, average', self.wait_time.avg), ('Wait time, std.dev.', self.wait_time.std), ("Execution time, ms.", self.real_time), ] return tabulate(items, headers=('Param', 'Value')) class Event(Enum): STOP = 0 ARRIVAL = 1 SERVICE_END = 2 class System: """ System state representation. This object takes care of the queue, current time, next arrival and service end time, server status and any other kind of dynamic information, except for internal state of arrival or service processes. """ def __init__(self, params: Params): """ Constructor. Parameters ---------- params : Params Model parameters """ if params.queue_capacity < np.inf: self._queue = FiniteFifoQueue(params.queue_capacity) else: self._queue = InfiniteFifoQueue() self._time: float = 0.0 self._service_end: Optional[float] = None self._next_arrival: Optional[float] = 0.0 self._server: Server[Packet] = Server() self._stopped: bool = False @property def server(self) -> Server[Packet]: return self._server @property def queue(self) -> Queue[Packet]: return self._queue @property def time(self) -> float: return self._time @property def stopped(self): return self._stopped @property def size(self) -> int: """ Get system size, that is queue size plus one (busy) or zero (empty). """ return self.server.size + self.queue.size def schedule(self, event: Event, interval: float) -> None: """ Schedule next event. Parameters ---------- event : Event interval : float Non-negative interval, after which the event will be fired. """ if interval < 0: raise ValueError(f"expected non-negative interval, but " f"{interval} found") if event == Event.ARRIVAL: self._next_arrival = self._time + interval elif event == Event.SERVICE_END: self._service_end = self._time + interval else: raise ValueError(f"unexpected event {event}") def stop(self) -> None: self._stopped = True def next_event(self) -> Event: """ Get next event type and move time to it. Returns ------- event : Event """ ts = self._service_end ta = self._next_arrival if ts is None and ta is None: return Event.STOP if ts is not None and (ta is None or ta > ts): self._time = ts self._service_end = None return Event.SERVICE_END # If we are here, TS is None, or TS is not None and NOT (ta > ts): # this means, that arrival happens self._time = self._next_arrival self._next_arrival = None return Event.ARRIVAL def simulate( arrival: Distribution, service: Distribution, queue_capacity: int = np.inf, max_time: float = np.inf, max_packets: int = 1000000 ) -> Results: """ Run simulation model of G/G/1/N system. Simulation can be stopped in two ways: by reaching maximum simulation time, or by reaching the maximum number of generated packets. By default, simulation is limited with the maximum number of packets only (1 million). Queue is expected to have finite capacity. Arrival and service time processes can be of any kind, including Poisson or MAP. To use a PH or normal distribution, a GenericIndependentProcess model with the corresponding distribution may be used. Parameters ---------- arrival : RandomProcess Arrival random process. service : RandomProcess Service time random process. queue_capacity : int Queue capacity. max_time : float, optional Maximum simulation time (default: infinity). max_packets Maximum number of simulated packets (default: 1'000'000) Returns ------- results : Results Simulation results. """ params = Params( arrival=arrival.rnd, service=service.rnd, queue_capacity=queue_capacity, max_packets=max_packets, max_time=max_time) system = System(params) records = Records() # Initialize model: records.system_size.add(0.0, system.size) system.schedule(Event.ARRIVAL, params.arrival.eval()) # Run simulation: max_time = params.max_time while not system.stopped: event = system.next_event() # Check whether event is scheduled too late, and we need to stop: if system.time > max_time: system.stop() continue # Process event # print(f"{system.time:.3f} [{event.name:5s}] " # f"server: {system.server.size}, " # f"queue: {system.queue.size}") if event == Event.ARRIVAL: _handle_arrival(system, params, records) elif event == Event.SERVICE_END: _handle_service_end(system, params, records) elif event == Event.STOP: system.stop() return _build_results(records) def _handle_arrival(system: System, params: Params, records: Records): """ Handle new packet arrival event. First of all, a new packet is created. Then we check whether the system is empty. If it is, this new packet starts serving immediately. Otherwise, it is added to the queue. If the queue was full, the packet is dropped. To mark this, we set `dropped` flag in the packet to `True`. In the end we schedule the next arrival. We also check whether the we have already generated enough packets. If so, `system.stopped` flag is set to `True`, so on the next main loop iteration the simulation will be stopped. Parameters ---------- system : System params : Params records : Records """ num_packets_built = len(records.packets) # If too many packets were generated, ask to stop: if num_packets_built >= params.max_packets: system.stop() time_now = system.time packet = Packet(created_at=time_now) records.add_packet(packet) # If server is ready, start serving. Otherwise, push the packet into # the queue. If the queue was full, mark the packet is being dropped # for further analysis. server = system.server if server.ready: # start serving immediately server.serve(packet) system.schedule(Event.SERVICE_END, params.service.eval()) packet.service_started_at = time_now records.system_size.add(time_now, system.size) elif system.queue.push(packet): # packet was queued records.system_size.add(time_now, system.size) else: # mark packet as being dropped packet.dropped = True # Schedule next arrival: system.schedule(Event.ARRIVAL, params.arrival.eval()) def _handle_service_end(system: System, params: Params, records: Records): """ Handle end of the packet service. If the queue is empty, the server becomes idle. Otherwise, it starts serving the next packet from the queue. The packet that left the server is marked as `served = True`. Parameters ---------- system : System params : Params records : Records """ time_now = system.time server = system.server queue = system.queue packet = server.pop() packet.served = True packet.departed_at = time_now # Start serving next packet, if exists: packet = queue.pop() if packet is not None: server.serve(packet) packet.service_started_at = time_now system.schedule(Event.SERVICE_END, params.service.eval()) # Anyway, system size has changed - record it! records.system_size.add(time_now, system.size) def _get_departure_intervals(packets_list: Sequence[Packet]) -> List[float]: """ Build departures intervals sequence. Parameters ---------- packets_list : sequence of Packet Returns ------- intervals : sequence of float """ prev_time = 0.0 intervals = [] for packet in packets_list: if packet.served: intervals.append(packet.departed_at - prev_time) prev_time = packet.departed_at return intervals def _build_results(records: Records) -> Results: """ Create results from the records. Parameters ---------- records : Records """ ret = Results() # # 1) Build system size, queue size and busy (server size) # distributions. To do this, we need PMFs. Queue size # PMF and busy PMF can be computed from system size PMF. # system_size_pmf = list(records.system_size.pmf) num_states = len(system_size_pmf) p0 = system_size_pmf[0] p1 = system_size_pmf[1] if num_states > 1 else 0.0 queue_size_pmf = [p0 + p1] + system_size_pmf[2:] server_size_pmf = [p0, sum(system_size_pmf[1:])] ret.system_size = CountableDistribution(system_size_pmf) ret.queue_size = CountableDistribution(queue_size_pmf) ret.busy = CountableDistribution(server_size_pmf) # # 2) For future estimations, we need packets and some filters. # Group all of them here. # all_packets = records.packets served_packets = [packet for packet in all_packets if packet.served] dropped_packets = [packet for packet in all_packets if packet.dropped] # # 3) Build scalar statistics. # ret.loss_prob = len(dropped_packets) / len(all_packets) # # 4) Build various intervals statistics: departures, waiting times, # response times. # departure_intervals = _get_departure_intervals(served_packets) ret.departures = build_statistics(np.asarray(departure_intervals)) ret.response_time = build_statistics([ pkt.departed_at - pkt.created_at for pkt in served_packets ]) ret.wait_time = build_statistics([ pkt.service_started_at - pkt.created_at for pkt in served_packets ]) return ret
import logging from .traderbot import TraderBot import json import config class MockMarket(object): def __init__(self, name, fee=0, cny_balance=3000., btc_balance=10., persistent=True): self.name = name self.filename = "traderbot-sim-" + name + ".json" self.cny_balance = cny_balance self.btc_balance = btc_balance self.cny_frozen = 0 self.btc_frozen = 0 self.cny_total = 0 self.btc_total = 0 self.fee = fee self.persistent = persistent if self.persistent: try: self.load() except IOError: pass def buy(self, volume, price): logging.info("execute buy %f BTC @ %f on %s" % (volume, price, self.name)) self.cny_balance -= price * volume self.btc_balance += volume - volume * self.fee if self.persistent: self.save() def sell(self, volume, price): logging.info("execute sell %f BTC @ %f on %s" % (volume, price, self.name)) self.btc_balance -= volume self.cny_balance += price * volume - price * volume * self.fee if self.persistent: self.save() def load(self): data = json.load(open(self.filename, "r")) self.cny_balance = data["cny"] self.btc_balance = data["btc"] def save(self): data = {'cny': self.cny_balance, 'btc': self.btc_balance} json.dump(data, open(self.filename, "w")) def balance_total(self, price): return self.cny_balance + self.btc_balance * price def get_info(self): pass class TraderBotSim(TraderBot): def __init__(self): self.kraken = MockMarket("kraken", 0.005, 5000) # 0.5% fee self.paymium = MockMarket("paymium", 0.005, 5000) # 0.5% fee self.bitstamp = MockMarket("bitstamp", 0.005, 5000) # 0.5% fee self.btcc = MockMarket("btcc", 0.005, 5000) # 0.5% fee self.haobtc = MockMarket("haobtc", 0.002, 5000) # 0.2% fee self.okcoin = MockMarket("okcoin", 0.000, 5000) # 0.0% fee self.huobi = MockMarket("huobi", 0.000, 5000) # 0.0% fee self.broker = MockMarket("broker", 0.000, 5000) # 0.0% fee self.reverse_profit_thresh = config.reverse_profit_thresh self.clients = { "KrakenEUR": self.kraken, "PaymiumEUR": self.paymium, "BitstampUSD": self.bitstamp, "BTCCCNY": self.btcc, "HaobtcCNY": self.haobtc, "OKCoinCNY": self.okcoin, "HuobiCNY": self.huobi, "BrokerCNY": self.broker, } self.profit_thresh = 0.1 # in CNY self.perc_thresh = 0.01 # in % self.trade_wait = 60 self.last_trade = 0 self.orders = [] def total_balance(self, price): market_balances = [i.balance_total( price) for i in set(self.clients.values())] return sum(market_balances) def total_cny_balance(self): return sum([i.cny_balance for i in set(self.clients.values())]) def total_usd_balance(self): return sum([i.usd_balance for i in set(self.clients.values())]) def total_btc_balance(self): return sum([i.btc_balance for i in set(self.clients.values())]) if __name__ == "__main__": t = TraderBotSim() print("Total BTC: %f" % t.total_btc_balance()) print("Total CNY: %f" % t.total_cny_balance()) print("Total USD: %f" % t.total_usd_balance())
import numpy as np import cv2 camera = cv2.VideoCapture(0) # determine upper and lower HSV limits for (my) skin tones lower = np.array([0, 100, 0], dtype="uint8") upper = np.array([50,255,255], dtype="uint8") while (True): ret, frame = camera.read() if not ret: continue # switch to HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # find mask of pixels within HSV range skinMask = cv2.inRange(hsv, lower, upper) # denoise skinMask = cv2.GaussianBlur(skinMask, (9, 9), 0) # kernel for morphology operation kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4)) # CLOSE (dilate / erode) skinMask = cv2.morphologyEx(skinMask, cv2.MORPH_CLOSE, kernel, iterations = 3) # denoise the mask skinMask = cv2.GaussianBlur(skinMask, (9, 9), 0) # only display the masked pixels skin = cv2.bitwise_and(frame, frame, mask = skinMask) cv2.imshow("HSV", skin) # quit or save frame key = cv2.waitKey(1000 // 12) & 0xff if key == ord("q"): break if key == ord("p"): cv2.imwrite("skin.jpg", skin) cv2.destroyAllWindows()
"""3. Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring """ class Solution: def length_of_longest_substring_1(self, s: str) -> int: """ time complexity: O(N^2) space complexity: O(N) """ n = len(s) store = {} max_len = 0 for i in range(n): if n - i <= max_len: break cur_len = 0 for j in range(i, n): key = s[j] if key in store: store.clear() break store[key] = 1 cur_len += 1 max_len = max(max_len, cur_len) return max_len def length_of_longest_substring_2(self, s: str) -> int: n = len(s) max_len = 0 for i in range(n): if n - i <= max_len: break store = '' for j in range(i, n): if s[j] in store: break store += s[j] max_len = max(max_len, len(store)) return max_len def length_of_longest_substring_3(self, s: str) -> int: i, n = 0, len(s) if n <= 1: return n store = {} max_len = 0 while i < n - 1: j = i while j < n and s[j] not in store: store[s[j]] = j j += 1 max_len = max(max_len, j - i) if j == n: break i = store[s[j]] + 1 store.clear() return max_len def length_of_longest_substring_4(self, s: str) -> int: store = [] max_len = 0 i, j, n = 0, 0, len(s) while i < n and j < n: if s[j] not in store: store.append(s[j]) j += 1 max_len = max(max_len, j - i) else: store.remove(s[i]) i += 1 return max_len def length_of_longest_substring_5(self, s: str) -> int: store = {} i, j, n, max_len = 0, 0, len(s), 0 while i < n and j < n: if s[j] not in store: store[s[j]] = j j += 1 max_len = max(max_len, j - i) else: temp = store[s[j]] + 1 for k in range(i, temp): store.pop(s[k]) i = temp return max_len
import os import pickle import operator from . import config from . import lib from .profanity_rater import profanity_severity_rating from .spam_rater import spam_severity_rating from .short_content_rater import short_content_severity_rating from .keyword_stuffing_rater import keyword_stuffing_severity_rating, find_stuffed_keywords # Import the trained svm and vectorizer trained_data_folder = os.path.join(os.path.dirname(__file__), '..', '..', 'algorithms') with open(os.path.join(trained_data_folder, 'spam_model.pkl'), 'rb') as f: svm = pickle.load(f) with open(os.path.join(trained_data_folder, 'spam_model_vectorizer.pkl'), 'rb') as f: vectorizer = pickle.load(f) class SpamTracker: """Spam Tracker Class""" content = "" word_count = 0 # Ratings profanity_rating = 0 spam_rating = 0 short_rating = 0 keyword_stuffing_rating = 0 spam_prediction = 0 # Default to ham (0 - ham; 1 - spam;) spam_prediction_confidence = 0 severity_type = None keywords = [] def __init__(self): pass def set_content(self, text): self.content = text self.word_count = lib.word_count(self.content) def reset(self): content = "" word_count = 0 profanity_rating = 0 spam_rating = 0 short_rating = 0 keyword_stuffing_rating = 0 spam_prediction = 0 spam_prediction_confidence = 0 severity_type = None keywords = [] def predict(self): self.predict_spam() self.short_rating = short_content_severity_rating(self.word_count) self.profanity_rating = profanity_severity_rating(self.content) self.keywords = find_stuffed_keywords(self.content) stuffed_keyword = None for k in self.keywords: if stuffed_keyword is None: stuffed_keyword = k self.keywords[k] = float(self.keywords[k]) self.keyword_stuffing_rating = keyword_stuffing_severity_rating(self.content, stuffed_keyword) def final_rating(self): ratings = { "profanity": self.profanity_rating, "spam": self.spam_rating, "short_content": self.short_rating, "keyword_stuffing": self.keyword_stuffing_rating } self.severity_type = max(ratings.items(), key=operator.itemgetter(1))[0] highest_rating = ratings[self.severity_type] if self.short_rating > 5: self.severity_type = "short_content" highest_rating = ratings[self.severity_type] if highest_rating == 0: self.severity_type = None return highest_rating def predict_spam(self): msg = vectorizer.transform([self.content]) prediction = svm.predict(msg) self.spam_prediction = prediction[0] self.spam_prediction_confidence = svm.predict_proba(msg)[0] self.spam_rating = spam_severity_rating(self.spam_prediction, self.spam_prediction_confidence[1]) return self.spam_prediction def get_ratings(self): return { "profanity_rating": self.profanity_rating, "spam_rating": self.spam_rating, "short_rating": self.short_rating, "keyword_stuffing_rating": self.keyword_stuffing_rating, "spam": { "spam_prediction": int(self.spam_prediction), "spam_prediction_confidence": [float(self.spam_prediction_confidence[0]), float(self.spam_prediction_confidence[1])], }, "keywords": self.keywords }
from solutions.CHK import checkout_solution from unittest import TestCase class TestSum(TestCase): def test_chkE(self): self.assertEqual(checkout_solution.checkout('BBE'), 85) def test_chkEE(self): self.assertEqual(checkout_solution.checkout('BBEE'), 110) def test_chkABCDE(self): self.assertEqual(checkout_solution.checkout('ABCDE'), 155) def test_chk5A(self): self.assertEqual(checkout_solution.checkout('AAAAA'), 200) def test_chk6A(self): self.assertEqual(checkout_solution.checkout('AAAAAA'), 250) def test_chk2F(self): self.assertEqual(checkout_solution.checkout('FF'), 20) def test_chk3F(self): self.assertEqual(checkout_solution.checkout('FFF'), 20) def test_chk4F(self): self.assertEqual(checkout_solution.checkout('FFFF'), 30) def test_chk5F(self): self.assertEqual(checkout_solution.checkout('FFFFF'), 40) def test_chkSTX(self): self.assertEqual(checkout_solution.checkout('STX'), 45) def test_chkST2X(self): self.assertEqual(checkout_solution.checkout('STXX'), 62) def test_chk3SZ(self): self.assertEqual(checkout_solution.checkout('SSSZ'), 65) def test_chk3ZS(self): self.assertEqual(checkout_solution.checkout('ZZZS'), 65) def test_chkSTXS(self): self.assertEqual(checkout_solution.checkout('STXS'), 62)
# -*- coding: utf-8 -*- """Synteny (genome order) operations.""" # standard library imports import sys from itertools import combinations # from os.path import commonprefix as prefix from pathlib import Path # third-party imports import dask.bag as db import networkx as nx import numpy as np import pandas as pd from dask.diagnostics import ProgressBar # module imports from .common import AMBIGUOUS_CODE from .common import ANCHOR_HIST_FILE from .common import ANCHORS_FILE from .common import CLUSTERS_FILE from .common import CLUSTERSYN_FILE from .common import CODE_DICT from .common import DISAMBIGUATED_CODE from .common import HOMOLOGY_FILE from .common import INDIRECT_CODE from .common import LOCALLY_UNAMBIGUOUS_CODE from .common import NON_AMBIGUOUS_CODE from .common import PROTEOMOLOGY_FILE from .common import PROTEOSYN_FILE from .common import SPINNER_UPDATE_PERIOD from .common import SYNTENY_FILE from .common import SYNTENY_FILETYPE from .common import UNAMBIGUOUS_CODE from .common import calculate_adjacency_group from .common import dotpath_to_path from .common import hash_array from .common import log_and_add_to_stats from .common import logger from .common import read_tsv_or_parquet from .common import write_tsv_or_parquet from .hash import SyntenyBlockHasher from .mailboxes import DataMailboxes from .mailboxes import ExternalMerge from .merger import AmbiguousMerger # global constants __ALL__ = ["synteny_anchors"] CLUSTER_COLS = ["syn.anchor.id", "syn.anchor.count", "syn.anchor.direction"] JOIN_COLS = [ "member_ids", "syn.anchor.sub_id", "syn.anchor.id", "syn.anchor.count", "syn.code", "frag.idx", ] ANCHOR_COLS = [ "path", "syn.code", "syn.anchor.count", "hom.cluster", "frag.id", "frag.pos", "hom.cl_size", "frag.direction", "frag.idx", "frag.is_chr", "frag.is_plas", "frag.is_scaf", "frag.prot_count", "frag.start", "prot.len", "prot.m_start", "prot.n_ambig", "prot.no_stop", ] MAILBOX_SUBDIR = "mailboxes" # CLI function def synteny_anchors( k, peatmer, setname, click_loguru=None, write_ambiguous=True, thorny=True, disambig_adj_only=True, ): """Calculate synteny anchors.""" # # Marshal input arguments # if k < 2: logger.error("k must be at least 2.") sys.exit(1) options = click_loguru.get_global_options() user_options = click_loguru.get_user_global_options() set_path = Path(setname) file_stats_path = set_path / PROTEOMOLOGY_FILE proteomes = read_tsv_or_parquet(file_stats_path) n_proteomes = len(proteomes) clusters = read_tsv_or_parquet(set_path / CLUSTERS_FILE) n_clusters = len(clusters) hasher = SyntenyBlockHasher( k=k, peatmer=peatmer, thorny=thorny, disambig_adj_only=disambig_adj_only, ) logger.info( f"Calculating {hasher.hash_name(no_prefix=True)} synteny anchors" + f" for {n_proteomes} proteomes" ) # durable argument list for passes arg_list = [ ( idx, row["path"], ) for idx, row in proteomes.iterrows() ] runner = PassRunner( { "n_proteomes": n_proteomes, "set_path": set_path, "hasher": hasher, "quiet": options.quiet, "parallel": user_options["parallel"], "bag": db.from_sequence(arg_list), "merge_args": arg_list, "click_loguru": click_loguru, } ) # # Make first three passes: # 1. hash and find unambiguous anchors # 2. disambiguate ambiguous anchors adjacent to unambiguous ones # 3. find non-ambiguous hashes uncovered by 2) # for pass_code in [ UNAMBIGUOUS_CODE, DISAMBIGUATED_CODE, NON_AMBIGUOUS_CODE, ]: proteomes = runner.make_pass(pass_code, proteomes) runner.add_ambig_to_total_assigned() n_anchors = runner.get_total_assigned() # # Fourth pass -- merge, write anchor and homology info # join_mb = DataMailboxes( n_boxes=n_proteomes, mb_dir_path=(set_path / MAILBOX_SUBDIR / "join"), file_extension="tsv", ) join_mb.write_tsv_headers(JOIN_COLS) cluster_mb = DataMailboxes( n_boxes=n_clusters, mb_dir_path=(set_path / MAILBOX_SUBDIR / "clusters"), file_extension="tsv", ) cluster_mb.write_tsv_headers(CLUSTER_COLS) anchor_mb = DataMailboxes( n_boxes=n_anchors, mb_dir_path=(set_path / MAILBOX_SUBDIR / "anchors"), file_extension="tsv", ) anchor_mb.write_tsv_headers(ANCHOR_COLS) proteomes = runner.make_pass( INDIRECT_CODE, proteomes, extra_kwargs={ "join_mb": join_mb, "cluster_mb": cluster_mb, "anchor_mb": anchor_mb, "n_proteomes": n_proteomes, "write_ambiguous": write_ambiguous, }, ) write_tsv_or_parquet( proteomes, set_path / PROTEOSYN_FILE, remove_tmp=False ) adjacency_stats = anchors_to_adjacency( set_path, n_proteomes, join_mb.open_then_delete ) logger.info(f"adjacency_stats: {adjacency_stats}") return # # Write anchors # click_loguru.elapsed_time("Anchor writing") arg_list = [(i,) for i in range(n_anchors)] anchor_path = set_path / "synteny" anchor_path.mkdir(exist_ok=True) logger.info(f"Writing {n_anchors} synteny anchors to {anchor_path}:") if not options.quiet: ProgressBar(dt=SPINNER_UPDATE_PERIOD).register() if parallel: bag = db.from_sequence(arg_list) anchor_stats = bag.map( write_anchor, mailbox_reader=anchor_mb.open_then_delete, synteny_parent=anchor_path, ).compute() else: anchor_stats = [] for args in arg_list: anchor_stats.append( write_anchor( args, mailbox_reader=anchor_mb.open_then_delete, synteny_parent=anchor_path, ) ) anchor_mb.delete() anchor_stat_list = [] for results in anchor_stats: if results is not None: anchor_stat_list += results anchor_frame = pd.DataFrame.from_dict(results) write_tsv_or_parquet( anchor_frame, set_path / ANCHORS_FILE, sort_cols=False, ) # # Merge synteny into clusters # arg_list = [(i,) for i in range(n_clusters)] click_loguru.elapsed_time("Synteny joining") homology_path = set_path / "homology" logger.info( f"Joining synteny info to {n_clusters} clusters in {homology_path}:" ) if not options.quiet: ProgressBar(dt=SPINNER_UPDATE_PERIOD).register() if parallel: bag = db.from_sequence(arg_list) cluster_stats = bag.map( join_synteny_to_clusters, mailbox_reader=cluster_mb.open_then_delete, cluster_parent=homology_path, ).compute() else: cluster_stats = [] for args in arg_list: cluster_stats.append( join_synteny_to_clusters( args, mailbox_reader=cluster_mb.open_then_delete, cluster_parent=homology_path, ) ) cluster_mb.delete() cluster_frame = pd.DataFrame.from_dict(cluster_stats) cluster_frame.set_index(["clust_id"], inplace=True) cluster_frame.sort_index(inplace=True) clusters = _concat_without_overlap(clusters, cluster_frame) write_tsv_or_parquet( clusters, set_path / CLUSTERSYN_FILE, float_format="%5.2f" ) mean_gene_synteny = ( clusters["in_synteny"].sum() * 100.0 / clusters["size"].sum() ) mean_clust_synteny = clusters["synteny_pct"].mean() logger.info( f"Mean anchor coverage: {mean_gene_synteny: .1f}% (on proteins)" ) logger.info( f"Mean cluster anchor coverage: {mean_clust_synteny:.1f}% (on clusters)" ) click_loguru.elapsed_time(None) class PassRunner: """Run a pass over all proteomes.""" def __init__(self, std_kwargs): """Save initial pass info""" self.std_kwargs = std_kwargs self.last_code = None self.pass_name = "Hashing" self.merger_kw_dict = { UNAMBIGUOUS_CODE: { "count_key": "syn.anchor.count", "ordinal_key": "syn.anchor.id", "ambig_ordinal_key": "tmp.ambig.id", }, DISAMBIGUATED_CODE: { "count_key": "tmp.disambig.anchor.count", "ordinal_key": "tmp.disambig.anchor.id", "alt_hash": True, }, NON_AMBIGUOUS_CODE: { "count_key": "tmp.nonambig.anchor.count", "ordinal_key": "tmp.nonambig.anchor.id", "ambig_count_key": "tmp.ambig.anchor.count", "ambig_ordinal_key": "tmp.ambig.anchor.id", }, } self.merge_function_dict = { UNAMBIGUOUS_CODE: calculate_synteny_hashes, DISAMBIGUATED_CODE: merge_unambig_hashes, NON_AMBIGUOUS_CODE: merge_disambig_hashes, INDIRECT_CODE: merge_nonambig_hashes, } self.n_assigned_list = [] self.ambig = None self.unambig = None self.log_ambig = False def make_pass( self, code, proteomes, extra_kwargs=None, ): """Make a calculate-merge pass over each proteome.""" self.std_kwargs["click_loguru"].elapsed_time(self.pass_name) if self.unambig is not None: if self.log_ambig: ambig_msg = f" and {len(self.ambig)} ambiguous" else: ambig_msg = "" logger.info( f"Merging {len(self.unambig)} {CODE_DICT[self.last_code]}" + f"({self.last_code}){ambig_msg} synteny anchors into proteomes" ) if extra_kwargs is None: extra_kwargs = {} kwargs = { "unambig": self.unambig, "ambig": self.ambig, "hasher": self.std_kwargs["hasher"], } if code in self.merger_kw_dict: mailboxes = DataMailboxes( n_boxes=self.std_kwargs["n_proteomes"], mb_dir_path=( self.std_kwargs["set_path"] / MAILBOX_SUBDIR / CODE_DICT[code] ), ) mailboxes.write_headers("hash\n") kwargs["mailboxes"] = mailboxes merge_func = self.merge_function_dict[code] if not self.std_kwargs["quiet"]: ProgressBar(dt=SPINNER_UPDATE_PERIOD).register() if self.std_kwargs["parallel"]: stats_list = ( self.std_kwargs["bag"] .map(merge_func, **kwargs, **extra_kwargs) .compute() ) else: stats_list = [] for args in self.std_kwargs["merge_args"]: stats_list.append(merge_func(args, **kwargs, **extra_kwargs)) stats = ( pd.DataFrame.from_dict(stats_list).set_index("idx").sort_index() ) proteomes = log_and_add_to_stats(proteomes, stats) if code in self.merger_kw_dict: merger = ExternalMerge( file_path_func=mailboxes.path_to_mailbox, n_merge=self.std_kwargs["n_proteomes"], ) merger.init("hash") merge_counter = AmbiguousMerger( start_base=sum(self.n_assigned_list), **self.merger_kw_dict[code], ) self.unambig, self.ambig = merger.merge(merge_counter) mailboxes.delete() self.n_assigned_list.append(len(self.unambig)) self.last_code = code self.pass_name = CODE_DICT[code] return proteomes def add_ambig_to_total_assigned(self): """Include the most recent ambiguous assignment in the total.""" self.n_assigned_list.append(len(self.ambig)) self.log_ambig = True def get_total_assigned(self): """Return the total assigned anchors.""" return sum(self.n_assigned_list) def calculate_synteny_hashes( args, mailboxes=None, hasher=None, unambig=None, ambig=None ): """Calculate synteny hashes for proteins per-genome.""" idx, dotpath = args outpath = dotpath_to_path(dotpath) hom = read_tsv_or_parquet(outpath / HOMOLOGY_FILE) hom["tmp.nan_group"] = ( (hom["hom.cluster"].isnull()).astype(int).cumsum() + 1 ) * (~hom["hom.cluster"].isnull()) hom.replace(to_replace={"tmp.nan_group": 0}, value=pd.NA, inplace=True) hash_name = hasher.hash_name() syn_list = [] if hasher.thorny: # drop rows hom = hom[hom["hom.cluster"].notna()] for unused_id_tuple, subframe in hom.groupby( by=["frag.id", "tmp.nan_group"] ): syn_list.append(hasher.calculate(subframe["hom.cluster"])) del hom["tmp.nan_group"] syn = hom.join( pd.concat([df for df in syn_list if df is not None], axis=0) ) del syn_list write_tsv_or_parquet(syn, outpath / SYNTENY_FILE, remove_tmp=False) syn["tmp.self_count"] = pd.array( syn[hash_name].map(syn[hash_name].value_counts()), dtype=pd.UInt32Dtype(), ) unique_hashes = ( syn[[hash_name, "tmp.self_count"]] .drop_duplicates(subset=[hash_name]) .dropna(how="any") ) unique_hashes = unique_hashes.set_index(hash_name).sort_index() with mailboxes.locked_open_for_write(idx) as file_handle: unique_hashes.to_csv(file_handle, header=False, sep="\t") return { "idx": idx, "path": dotpath, "hom.clusters": syn["hom.cluster"].notna().sum(), "syn.hashes.n": syn[hash_name].notna().sum(), } def merge_unambig_hashes( args, unambig=None, ambig=None, hasher=None, mailboxes=None, ): """Merge unambiguous synteny hashes into proteomes per-proteome.""" hash_name = hasher.hash_name() idx, dotpath = args outpath = dotpath_to_path(dotpath) syn = read_tsv_or_parquet(outpath / SYNTENY_FILE) syn = _join_on_col_with_na(syn, unambig, hash_name) syn = _join_on_col_with_na(syn, ambig, hash_name) syn["syn.code"] = pd.NA syn["syn.code"] = _fill_col1_val_where_col2_notna( syn["syn.code"], syn["syn.anchor.id"], UNAMBIGUOUS_CODE ) # Calculate disambiguation hashes and write them out for merge disambig_frame_list = [] for unused_frag, subframe in syn.groupby(by=["frag.id"]): disambig_frame_list.append(hasher.calculate_disambig_hashes(subframe)) disambig_fr = pd.concat( [df for df in disambig_frame_list if df is not None] ) disambig_fr = disambig_fr.dropna(how="all") syn = syn.join(disambig_fr) write_tsv_or_parquet(syn, outpath / SYNTENY_FILE, remove_tmp=False) # Write out unified upstream/downstream hash values merged_hashes = pd.concat( [ _rename_and_fill_alt(syn, "tmp.disambig.up", "tmp.disambig.down"), _rename_and_fill_alt(syn, "tmp.disambig.down", "tmp.disambig.up"), ], ignore_index=True, ) merged_hashes["self_count"] = pd.array( merged_hashes["hash"].map(merged_hashes["hash"].value_counts()), dtype=pd.UInt32Dtype(), ) merged_hashes = merged_hashes.reindex( columns=["hash", "self_count", "alt_hash"] ) unique_hashes = ( merged_hashes.drop_duplicates(subset=["hash"]) .set_index("hash") .sort_index() ) del merged_hashes with mailboxes.locked_open_for_write(idx) as file_handle: unique_hashes.to_csv(file_handle, header=False, sep="\t") return { "idx": idx, "path": dotpath, "syn.anchors.unambiguous": _count_code( syn["syn.code"], UNAMBIGUOUS_CODE ), } def merge_disambig_hashes( args, unambig=None, ambig=None, hasher=None, mailboxes=None, ): """Merge disambiguated synteny hashes into proteomes per-proteome.""" idx, dotpath = args plain_hash_name = hasher.hash_name(no_prefix=True) hash_name = "syn." + plain_hash_name outpath = dotpath_to_path(dotpath) syn = read_tsv_or_parquet(outpath / SYNTENY_FILE) syn = _join_on_col_with_na(syn, unambig, "tmp.disambig.up") syn = _join_on_col_with_na(syn, unambig, "tmp.disambig.down") for dup_col in [ "tmp.disambig.anchor.count", "tmp.disambig.anchor.id", ]: xcol = dup_col + "_x" ycol = dup_col + "_y" syn[dup_col] = syn[xcol].fillna(syn[ycol]) del syn[xcol], syn[ycol] syn["syn.anchor.id"] = syn["syn.anchor.id"].fillna( syn["tmp.disambig.anchor.id"] ) syn["syn.anchor.count"] = syn["syn.anchor.count"].fillna( syn["tmp.disambig.anchor.count"] ) syn["syn.code"] = _fill_col1_val_where_col2_notna( syn["syn.code"], syn["tmp.disambig.anchor.id"], DISAMBIGUATED_CODE ) # Delete some non-needed tmp columns non_needed_cols = [ "tmp.disambig.anchor.count", "tmp.disambig.anchor.id", "tmp.disambig.up", "tmp.disambig.down", ] syn = syn.drop(columns=non_needed_cols) # null hashes are already assigned syn[hash_name][syn["syn.anchor.id"].notna()] = pd.NA write_tsv_or_parquet(syn, outpath / SYNTENY_FILE, remove_tmp=False) # Write out non-ambiguous hashes syn["tmp.self_count"] = pd.array( syn[hash_name].map(syn[hash_name].value_counts()), dtype=pd.UInt32Dtype(), ) unique_hashes = ( syn[[hash_name, "tmp.self_count"]] .drop_duplicates(subset=[hash_name]) .dropna(how="any") ) unique_hashes = unique_hashes.set_index(hash_name).sort_index() with mailboxes.locked_open_for_write(idx) as file_handle: unique_hashes.to_csv(file_handle, header=False, sep="\t") # logger.debug(f"{dotpath} has {syn['syn.anchor.id'].notna().sum()} assignments") return { "idx": idx, "path": dotpath, "syn.anchors.disambiguated": _count_code( syn["syn.code"], DISAMBIGUATED_CODE ), } def merge_nonambig_hashes( args, join_mb=None, unambig=None, ambig=None, hasher=None, n_proteomes=None, cluster_mb=None, anchor_mb=None, write_ambiguous=True, ): """Merge disambiguated synteny hashes into proteomes per-proteome.""" idx, dotpath = args plain_hash_name = hasher.hash_name(no_prefix=True) hash_name = "syn." + plain_hash_name outpath = dotpath_to_path(dotpath) syn = read_tsv_or_parquet(outpath / SYNTENY_FILE) syn = _join_on_col_with_na(syn, unambig, hash_name) # # Do the indirects (formerly ambig made nonambig) # syn["syn.anchor.id"] = syn["syn.anchor.id"].fillna( syn["tmp.nonambig.anchor.id"] ) syn["syn.anchor.count"] = syn["syn.anchor.count"].fillna( syn["tmp.nonambig.anchor.count"] ) syn["syn.code"] = _fill_col1_val_where_col2_notna( syn["syn.code"], syn["tmp.nonambig.anchor.id"], INDIRECT_CODE ) # # Do the nonambig (w.r.t. this proteome) and ambig, if requested # syn = _join_on_col_with_na(syn, ambig, hash_name) n_proteins = len(syn) syn["tmp.i"] = range(n_proteins) ambig_code = syn["syn.code"].copy() ambig_ids = syn["tmp.ambig.anchor.id"].copy() ambig_counts = syn["tmp.ambig.anchor.count"].copy() for unused_ambig_id, subframe in syn.groupby(by=["tmp.ambig.anchor.id"]): ambig_n = len(subframe) for unused_i, row in subframe.iterrows(): row_no = row["tmp.i"] if ambig_n == 1: ambig_code.iloc[row_no] = LOCALLY_UNAMBIGUOUS_CODE elif ambig_n > 1: if write_ambiguous: ambig_code.iloc[row_no] = AMBIGUOUS_CODE else: ambig_ids.iloc[row_no] = pd.NA ambig_counts.iloc[row_no] = pd.NA syn["syn.anchor.id"] = syn["syn.anchor.id"].fillna(ambig_ids) syn["syn.anchor.count"] = syn["syn.anchor.count"].fillna(ambig_counts) syn["syn.code"] = syn["syn.code"].fillna(ambig_code) del ambig_code, ambig_ids, ambig_counts # # Hsh footprint and direction are anchor properties, where set # syn = syn.rename( columns={ "syn.hash.footprint": "syn.anchor.footprint", "syn.hash.direction": "syn.anchor.direction", } ) n_anchors = syn["syn.anchor.id"].notna().sum() # before shingling # # Do shingling # # shingle_id = np.array([np.nan] * n_proteins) # shingle_count = np.array([np.nan] * n_proteins) # shingle_code = syn["syn.code"].to_numpy() # shingle_direction = syn["syn.anchor.direction"].to_numpy() # shingle_sub = np.array([np.nan] * n_proteins) with join_mb.locked_open_for_write(idx) as file_handle: for anchor_count, subframe in syn.groupby(by=["syn.anchor.count"]): for unused_i, row in subframe.iterrows(): anchor_id = row["syn.anchor.id"] if pd.isnull(anchor_id): continue first_row = row["tmp.i"] last_row = first_row + row["syn.anchor.footprint"] # shingle_id[first_row:last_row] = anchor_id # shingle_count[first_row:last_row] = anchor_count # shingle_code[first_row:last_row] = row["syn.code"] # shingle_direction[first_row:last_row] = row[ # "syn.anchor.direction" # ] # shingle_sub[first_row:last_row] = hasher.shingle( # syn["hom.cluster"][first_row:last_row], # row["syn.anchor.direction"], # row[hash_name], # ) shingle_fr = pd.DataFrame( { "member_ids": syn.iloc[first_row:last_row].index, "syn.anchor.sub_id": hasher.shingle( syn["hom.cluster"][first_row:last_row], row["syn.anchor.direction"], row[hash_name], ), } ) shingle_fr["syn.anchor.id"] = anchor_id shingle_fr["syn.anchor.count"] = anchor_count shingle_fr["syn.code"] = row["syn.code"] shingle_fr["frag.idx"] = row["frag.idx"] shingle_fr.to_csv(file_handle, header=False, sep="\t") # syn["syn.anchor.id"] = shingle_id # syn["syn.anchor.count"] = shingle_count # syn["syn.code"] = shingle_code # syn["syn.anchor.direction"] = shingle_direction # syn["syn.anchor.sub_id"] = shingle_sub # del shingle_id, shingle_count, shingle_code, shingle_sub # Delete non-needed (but non-tmp) columns # non_needed_cols = [hash_name] # syn = syn.drop(columns=non_needed_cols) # Write proteome file # write_tsv_or_parquet( # syn, # outpath / SYNTENY_FILE, # ) # Write anchor info to mailbox # for anchor_id, subframe in syn.groupby(by=["syn.anchor.id"]): # anchor_frame = subframe.copy() # anchor_frame["path"] = dotpath # with anchor_mb.locked_open_for_write(anchor_id) as file_handle: # anchor_frame[ANCHOR_COLS].to_csv( # file_handle, header=False, sep="\t" # ) # for cluster_id, subframe in syn.groupby(by=["hom.cluster"]): # with cluster_mb.locked_open_for_write(cluster_id) as file_handle: # subframe[CLUSTER_COLS].to_csv(file_handle, header=False, sep="\t") in_synteny = syn["syn.anchor.id"].notna().sum() n_assigned = syn["hom.cluster"].notna().sum() avg_ortho = syn["syn.anchor.count"].mean() synteny_pct = in_synteny * 100.0 / n_assigned n_ambig = _count_code(syn["syn.code"], AMBIGUOUS_CODE) n_nonambig = in_synteny - n_ambig nonambig_pct = n_nonambig * 100.0 / n_assigned synteny_stats = { "idx": idx, "path": dotpath, "syn.anchors.indirect_unambiguous": _count_code( syn["syn.code"], INDIRECT_CODE ), "syn.anchors.locally_unambiguous": _count_code( syn["syn.code"], LOCALLY_UNAMBIGUOUS_CODE ), "syn.anchors.ambiguous": n_ambig, "syn.anchors.nonambiguous": n_nonambig, "syn.anchors.nonambig_pct": nonambig_pct, "syn.anchors.base": n_anchors, "syn.anchors.total": in_synteny, "syn.anchors.total_pct": synteny_pct, "syn.orthogenomic_pct": avg_ortho * 100.0 / n_proteomes, } return synteny_stats def join_synteny_to_clusters(args, cluster_parent=None, mailbox_reader=None): """Read homology info from mailbox and join it to proteome file.""" idx = args[0] cluster_path = cluster_parent / f"{idx}.parq" cluster = pd.read_parquet(cluster_path) n_cluster = len(cluster) with mailbox_reader(idx) as file_handle: synteny_frame = pd.read_csv( file_handle, sep="\t", index_col=0 ).convert_dtypes() in_synteny = len(synteny_frame) # cluster files are unusual in that I don't bother to version them, # so overlapping info has to be deleted each time clust_syn = _concat_without_overlap(cluster, synteny_frame) write_tsv_or_parquet(clust_syn, cluster_path) anchor_count = clust_syn["syn.anchor.id"].value_counts() anchor_frag_counts = [0] for unused_id_tuple, subframe in clust_syn.groupby( by=["syn.anchor.id", "path"] ): if len(subframe) == 1: anchor_frag_counts.append(1) else: anchor_frag_counts.append(len(subframe["frag.idx"].value_counts())) return { "clust_id": idx, "in_synteny": in_synteny, "n_anchors": len(anchor_count), "max_frags_per_anch": max(anchor_frag_counts), "synteny_pct": in_synteny * 100.0 / n_cluster, } def write_anchor(args, synteny_parent=None, mailbox_reader=None): """Read synteny anchor info from mailbox and join it to synteny file.""" idx = args[0] with mailbox_reader(idx) as file_handle: anchor_frame = pd.read_csv( file_handle, sep="\t", index_col=0 ).convert_dtypes() in_anchor = len(anchor_frame) if in_anchor == 0: return None # drop any duplicated ID's--normally shouldn't happen anchor_frame.drop( anchor_frame[anchor_frame.index.duplicated()].index, inplace=True ) anchor_frame.sort_values( by=["syn.anchor.sub_id", "frag.idx", "frag.pos"], inplace=True ) # Make a dictionary of common anchor properties, order will be kept anchor_props = { "anchor.id": idx, "sub": None, "code": None, "count": None, "n": None, "n_ambig": None, "n_adj": None, "adj_groups": None, "frag.direction": None, "syn.anchor.direction": None, "anchor.subframe.ok": True, "hash": None, } code_set = set(anchor_frame["syn.code"]) for test_code in CODE_DICT.keys(): if test_code in code_set: anchor_props["code"] = test_code break bad_subframe = False prop_list = [] for sub_no, subframe in anchor_frame.groupby(by=["syn.anchor.sub_id"]): (subanchor_props, anchor_subframe, bad_subframe) = _subframe_props( anchor_props, subframe, sub_no ) if bad_subframe: break write_tsv_or_parquet( anchor_subframe, synteny_parent / f"{idx}.{sub_no}.{SYNTENY_FILETYPE}", sort_cols=False, ) prop_list.append(subanchor_props) if bad_subframe: # Probably means a hash collision logger.error(f"bad anchor set {idx}") prop_list = [] sub_no = 0 anchor_props["anchor.subframe.ok"] = False for cluster_id, subframe in anchor_frame.groupby(by=["hom.cluster"]): ( subanchor_props, anchor_subframe, unused_bad_subframe, ) = _subframe_props(anchor_props, subframe, sub_no) write_tsv_or_parquet( anchor_subframe, synteny_parent / f"{idx}.{sub_no}.{SYNTENY_FILETYPE}", sort_cols=False, ) sub_no += 1 prop_list.append(subanchor_props) return prop_list def _subframe_props(anchor_props, subframe, sub_no): """Calculate subframe properties and write subframe""" anchor_subframe = subframe.copy() subanchor_props = anchor_props.copy() subanchor_props["sub"] = sub_no anchor_dir_set = set(anchor_subframe["syn.anchor.direction"]) if len(anchor_dir_set) == 1: subanchor_props["syn.anchor.direction"] = list(anchor_dir_set)[0] frag_dir_set = set(anchor_subframe["frag.direction"]) if len(frag_dir_set) == 1: subanchor_props["frag.direction"] = list(frag_dir_set)[0] subanchor_props["count"] = anchor_subframe["syn.anchor.count"].iloc[0] subanchor_props["n_ambig"] = _count_code( anchor_subframe["syn.code"], AMBIGUOUS_CODE ) hom_clust_set = set(anchor_subframe["hom.cluster"]) if len(hom_clust_set) == 1: subanchor_props[f"anchor.{sub_no}.cluster"] = list(hom_clust_set)[0] else: bad_subframe = True del ( anchor_subframe["syn.anchor.count"], anchor_subframe["syn.anchor.sub_id"], ) subanchor_props["n"] = len(anchor_subframe) subanchor_props["hash"] = hash_array( np.sort(anchor_subframe.index.to_numpy()) ) ( subanchor_props["n_adj"], subanchor_props["adj_groups"], unused_adj_group, ) = calculate_adjacency_group( anchor_subframe["frag.pos"], anchor_subframe["frag.idx"] ) return subanchor_props, anchor_subframe, bad_subframe def _concat_without_overlap(df1, df2): """Concatenate df2 on top of df1.""" overlapping = set(df1.columns).intersection(df2.columns) if len(overlapping) > 0: df1 = df1.drop(columns=overlapping) return pd.concat([df1, df2], axis=1) def _rename_and_fill_alt(df1, key, alt_key): """Rename columns and zero-fill alternate.""" df2 = df1[[key]].rename(columns={key: "hash"}) df2["alt_hash"] = df1[alt_key].fillna(0) return df2.dropna(how="any") def _join_on_col_with_na(left, right, col_name): """Join on a temporary column of type 'O'.""" tmp_col_name = "tmp." + col_name left[tmp_col_name] = left[col_name].astype("O") merged = pd.merge( left, right, left_on=tmp_col_name, right_index=True, how="left" ) del merged[tmp_col_name] return merged def _fill_col1_val_where_col2_notna(col1, col2, val): """Set col1 to val where col2 is not NA if col1 is not set.""" fill_ser = col1.copy() fill_ser[col2.notna()] = val return col1.fillna(fill_ser) def _count_code(code_ser, code): """Counts number of occurrances of code in code_ser.""" return (code_ser == code).sum() def anchors_to_adjacency(set_path, n_proteomes, mailbox_reader): """Merge adjacencies and produce and adjacency graph.""" frame_list = [] for idx in range(n_proteomes): with mailbox_reader(idx) as file_handle: frame_list.append( pd.read_csv( file_handle, sep="\t", index_col=0 ).convert_dtypes() ) nodes = pd.concat( frame_list, ignore_index=True, ) del frame_list graph = nx.Graph() for unused_tuple, subframe in nodes.groupby( by=["syn.anchor.id", "syn.anchor.sub_id"] ): ids = subframe["member_ids"] n_ids = len(ids) graph.add_nodes_from(ids) if n_ids > 1: edges = combinations(ids, 2) graph.add_edges_from(edges, weight=n_ids) outpath = set_path / ANCHORS_FILE summarypath = outpath.parent / ( outpath.name[: -len(outpath.suffix)] + "_summary.tsv" ) histpath = outpath.parent / ( outpath.name[: -len(outpath.suffix)] + "_hist.tsv" ) components = [ c for c in sorted(nx.connected_components(graph), key=len, reverse=True) if len(c) > 1 ] fh = outpath.open("w") fh.write("idx\tcluster_id\tsize\tmembers\n") n_items = 0 count_list = [] hash_list = [] id_list = [] for i, comp in enumerate(components): component = np.sort(pd.Index(list(comp)).to_numpy()) id_list.append(i) size = len(comp) count_list.append(size) hash_list.append(hash_array(component)) for node in component: fh.write(f"{n_items}\t{i}\t{size}\t{node}\n") n_items += 1 fh.close() n_clusts = len(count_list) del graph, components cluster_counts = pd.DataFrame({"size": count_list}) largest_cluster = cluster_counts["size"].max() cluster_hist = ( pd.DataFrame(cluster_counts.value_counts()).sort_index().reset_index() ) cluster_hist = cluster_hist.set_index("size") cluster_hist = cluster_hist.rename(columns={0: "n"}) cluster_hist["item_pct"] = ( cluster_hist["n"] * cluster_hist.index * 100.0 / n_items ) cluster_hist.to_csv(histpath, sep="\t", float_format="%5.2f") cluster_hist["cluster_pct"] = cluster_hist["n"] * 100.0 / n_clusts cluster_hist.to_csv(histpath, sep="\t", float_format="%5.2f") clusters = pd.DataFrame( {"anchor.id": id_list, "count": count_list, "hash": hash_list} ) clusters.to_csv(summarypath, sep="\t") stats_dict = { "in_anchor": n_items, "syn.anchors.n": n_clusts, "syn.anchors.largest": largest_cluster, } return stats_dict def intersect_anchors(set1_file, set2_file): set1_path = Path(set1_file) set2_path = Path(set2_file) set1_fr = pd.read_csv(set1_path, sep="\t", index_col=0) set2_fr = pd.read_csv(set2_path, sep="\t", index_col=0) set1_dict = {} for cluster_id, subframe in set1_fr.groupby(by=["cluster_id"]): set1_dict[cluster_id] = set(subframe["members"].to_numpy()) set2_dict = {} for cluster_id, subframe in set2_fr.groupby(by=["cluster_id"]): set2_dict[cluster_id] = set(subframe["members"].to_numpy()) identity_sets = [] s1_subset = [] s2_subset = [] incongruent = [] match_keys = list(set2_dict.keys()) for key1 in set1_dict: s1 = set1_dict[key1] for i, key2 in enumerate(match_keys): s2 = set2_dict[key2] if len(s1.intersection(s2)) == 0: continue elif s1 == s2: identity_sets.append( ( key1, key2, ) ) match_keys.pop(i) break elif s1.issubset(s2): s1_subset.append( ( key1, key2, ) ) match_keys.pop(i) break elif s2.issubset(s1): s2_subset.append( ( key1, key2, ) ) match_keys.pop(i) break else: incongruent.append( ( key1, key2, ) ) logger.info(f"set 1 ({set1_file}): {len(set1_dict)}") logger.info(f"set 2 ({set2_file}): {len(set2_dict)}") min_sets = min(len(set1_dict), len(set2_dict)) id_len = len(identity_sets) id_pct = id_len * 100.0 / min_sets logger.info(f"identity: {id_len} ({id_pct:.1f}%)") s1_len = len(s1_subset) s1_pct = s1_len * 100.0 / min_sets logger.info(f"set 1 is subset: {s1_len} ({s1_pct:.1f}%)") s2_len = len(s2_subset) s2_pct = s2_len * 100.0 / min_sets logger.info(f"set 2 is subset: {s2_len} ({s2_pct:.1f}%)") incon_len = len(incongruent) incon_pct = incon_len * 100.0 / min_sets logger.info(f"incongruent: {incon_len}({incon_pct}%)")
import unittest from jina.executors.encoders.nlp.transformer import TransformerTFEncoder, TransformerTorchEncoder from tests.unit.executors.encoders.nlp import NlpTestCase class PytorchTestCase(NlpTestCase): def _get_encoder(self, metas): return TransformerTorchEncoder( pretrained_model_name_or_path='bert-base-uncased', metas=metas) class TfTestCase(NlpTestCase): def _get_encoder(self, metas): return TransformerTFEncoder( pretrained_model_name_or_path='bert-base-uncased', metas=metas) class XLNetPytorchTestCase(NlpTestCase): def _get_encoder(self, metas): return TransformerTorchEncoder( pretrained_model_name_or_path='xlnet-base-cased', metas=metas) class XLNetTFTestCase(NlpTestCase): def _get_encoder(self, metas): return TransformerTFEncoder( pretrained_model_name_or_path='xlnet-base-cased', metas=metas) if __name__ == '__main__': unittest.main()
from os.path import join from celery import Celery from flask import Flask from flask_assets import Environment as FlaskAssets, Bundle from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('config.Config') app.secret_key = app.config['SECRET_KEY'] celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) assets = FlaskAssets(app) assets.register('js_base', Bundle( join('js', 'jquery-1.12.4.js'), join('js', 'bootstrap-3.3.7.js'), filters='jsmin', output=join('gen', 'js.%(version)s.min.js')) ) assets.register('js_activity', Bundle( join('js', 'activity.js'), filters='jsmin', output=join('gen', 'activity.%(version)s.min.js')) ) assets.register('css_base', Bundle( join('css', 'bootstrap.css'), join('css', 'font-awesome.css'), join('css', 'app.css'), filters='cssmin', output=join('gen', 'css.%(version)s.min.css')) ) db = SQLAlchemy(app) migrate = Migrate(app, db) from DataQualityTester import commands, routes, models, views, lib # noqa
""" Code to make an exploratory plot of the output of a box extraction. """ from lo_tools import Lfun, zfun from lo_tools import plotting_functions as pfun import xarray as xr import matplotlib.pyplot as plt import numpy as np import sys from cmocean import cm import pandas as pd Ldir = Lfun.Lstart() # choose the file in_dir0 = Ldir['LOo'] / 'extract' gtagex = Lfun.choose_item(in_dir0, tag='', exclude_tag='', itext='** Choose gtagex from list **') in_dir = in_dir0 / gtagex / 'box' box_name = Lfun.choose_item(in_dir, tag='.nc', exclude_tag='', itext='** Choose box extraction from list **') box_fn = in_dir / box_name # gather fields ds = xr.open_dataset(box_fn) # get time ot = ds.ocean_time.values ot_dt = pd.to_datetime(ot) NT = len(ot_dt) # choose a time to get print('Time range = ') print('0 = %s UTC' % (ot_dt[0].strftime('%Y.%m.%d %H:%M:%S'))) print('%d = %s UTC' % (NT-1, ot_dt[-1].strftime('%Y.%m.%d %H:%M:%S'))) my_choice = input('-- Input time index to plot -- (return=0) ') if len(my_choice)==0: my_choice = 0 if int(my_choice) not in range(NT): print('Error: time index out of range.') sys.exit() else: nt = int(my_choice) lon = ds.lon_rho.values lat = ds.lat_rho.values plon, plat = pfun.get_plon_plat(lon, lat) plot_uv = False if 'u' in ds.data_vars: # assume that if we have u we have v plot_uv = True if 'xi_u' in ds.u.dims: uv_grid = 'uv' elif 'xi_rho' in ds.u.dims: uv_grid = 'rho' ndims = len(ds.salt.dims) if ndims == 3: # like for a squeezed surface extraction s0 = ds.salt[nt,:,:].values if plot_uv: u0 = ds.u[nt,:,:].values v0 = ds.v[nt,:,:].values elif ndims == 4: s0 = ds.salt[nt,-1,:,:].values if plot_uv: u0 = ds.u[nt,-1,:,:].values v0 = ds.v[nt,-1,:,:].values # PLOTTING plt.close('all') pfun.start_plot(figsize=(10,10)) fig = plt.figure() ax = fig.add_subplot(111) ax.pcolormesh(plon, plat, s0, cmap='Spectral_r') pfun.add_coast(ax) pfun.dar(ax) pad = .02 ax.axis([plon[0,0]-pad, plon[-1,-1]+pad, plat[0,0]-pad, plat[-1,-1]+pad]) if plot_uv: pfun.start_plot(figsize=(20,10)) fig = plt.figure() ax = fig.add_subplot(121) if uv_grid == 'rho': ax.pcolormesh(plon, plat, u0, cmap='jet') ax.set_title('u rho-grid') elif uv_grid == 'uv': lon = ds.lon_u.values lat = ds.lat_u.values plon, plat = pfun.get_plon_plat(lon, lat) ax.pcolormesh(plon, plat, u0, cmap='jet') ax.set_title('u u-grid') pfun.add_coast(ax) pfun.dar(ax) pad = .02 ax.axis([plon[0,0]-pad, plon[-1,-1]+pad, plat[0,0]-pad, plat[-1,-1]+pad]) ax = fig.add_subplot(122) if uv_grid == 'rho': ax.pcolormesh(plon, plat, v0, cmap='jet') ax.set_title('v rho-grid') elif uv_grid == 'uv': lon = ds.lon_v.values lat = ds.lat_v.values plon, plat = pfun.get_plon_plat(lon, lat) ax.pcolormesh(plon, plat, v0, cmap='jet') ax.set_title('v v-grid') pfun.add_coast(ax) pfun.dar(ax) pad = .02 ax.axis([plon[0,0]-pad, plon[-1,-1]+pad, plat[0,0]-pad, plat[-1,-1]+pad]) plt.show() pfun.end_plot() ds.close()
import numpy as np # most basic functions def sigmoid(x): """sigmoid function""" return 1/(1+np.exp(-x)) def sigmoid_gradient(x): """gradient of sigmoid function""" return x * (1-x) def tanh(x): """tanh function""" return np.tanh(x) def tanh_gradient(x): """gradient of tanh function""" return 1-np.power(x,2) def get_Batch(M, trainX, trainy): """randomly sample a mini batch of size M from the training data""" N = trainX.shape[0] sample = np.random.choice(N,M) return trainX[sample], trainy[sample]
#!/usr/bin/env python import sys if sys.version_info.major == 3: import exodus3 as exo else: import exodus2 as exo import os.path import numpy as np f = sys.argv[-1] if not os.path.isfile(f) or not (len(sys.argv) == 2): print "usage: {0} <filename>".format(sys.argv[0]) exit e = exo.exodus(f,"r") dim = e.num_dimensions() nVertices = e.num_nodes() nCells = e.num_elems() nCSets = e.num_blks() nVSets = e.num_node_sets() print "number of dimensions: {0}".format(dim) print "number of vertices: {0}".format(nVertices) print "number of cells: {0}".format(nCells) print "number of cell sets: {0}".format(nCSets) print "number of vertex sets: {0}".format(nVSets) #listedVertices = np.empty([nVertices,],dtype=bool) listedVertices = [False,]*nVertices maxV = 0 minV = 2*nVertices for set in range(nCSets): setID = e.get_elem_blk_ids()[set] print "Cell set {0}".format(setID) connect = e.get_elem_connectivity(setID) print "\tNumber of cells: {0}".format(connect[1]) for v in connect[0]: if v > nVertices: print "PROBLEM: vertex {0} is out of range {1}".format(v,nVertices) exit else: listedVertices[v-1] = True minV = min(minV,v) maxV = max(maxV,v) print "vertex range: ({0}/{1})".format(minV,maxV) for v in range(nVertices): if not listedVertices[v]: print "PROBLEM: vertex {0} is not part of any cell".format(v+1) for set in range(nVSets): setID = e.get_elem_blk_ids()[nVSets] print "Vertex set {0}".format(setID)
# The MIT License (MIT) # # Copyright (c) 2020 Huimao Chen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import lldb import HMLLDBHelpers as HM import HMLLDBClassInfo import HMDebugBaseViewController import HMDebugMainViewController import HMProgressHUD import HMExpressionPrefix def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand(f'command script add -f HMDebugHUD.showDebugHUD showhud -h "Show debug HUD on key window.({gClassName})"') debugger.HandleCommand(f'command script add -f HMDebugHUD.removeDebugHUD removehud -h "Remove debug HUD from key window.({gClassName})"') gClassName = "HMDebugHUD" def showDebugHUD(debugger, command, exe_ctx, result, internal_dict): """ Syntax: showhud Examples: (lldb) showhud Summary: Show debug HUD. 1.Memory footprint. 2.CPU utilization. 3.FPS in main thread. The UI style is based on https://github.com/meitu/MTHawkeye This command is implemented in HMDebugHUD.py """ global gClassName if isDisplayingHUD(): HM.DPrint(f"{gClassName} is already on display") HM.processContinue() return elif HM.existClass(gClassName): showHUDFunc() HM.processContinue() return # Register class HMProgressHUD.show(f"Register {gClassName}...") HM.DPrint(f"Register {gClassName}...") classValue = HM.allocateClass(gClassName, "UIView") HM.addIvar(classValue.GetValue(), "_link", "CADisplayLink *") HM.addIvar(classValue.GetValue(), "_count", "int") # count in 1 second HM.addIvar(classValue.GetValue(), "_lastTime", "double") HM.addIvar(classValue.GetValue(), "_memoryLab", "UILabel *") HM.addIvar(classValue.GetValue(), "_cpuUtilizationLab", "UILabel *") HM.addIvar(classValue.GetValue(), "_fpsLab", "UILabel *") HM.registerClass(classValue.GetValue()) # Add methods HM.DPrint(f"Add methods to {gClassName}...") addToKeyWindowIMPValue = makeAddToKeyWindowIMP() if not HM.judgeSBValueHasValue(addToKeyWindowIMPValue): HMProgressHUD.hide() return HM.addClassMethod(gClassName, "addToKeyWindow", addToKeyWindowIMPValue.GetValue(), "@@:") tapSelfIMPValue = makeTapSelfIMP() if not HM.judgeSBValueHasValue(tapSelfIMPValue): HMProgressHUD.hide() return HM.addInstanceMethod(gClassName, "tapSelf", tapSelfIMPValue.GetValue(), "v@:") # Add methods(update) if not addUpdateMethods(): HMProgressHUD.hide() return # Add methods(move) HM.DPrint(f"Add methods to {gClassName}......") if not addMoveMethods(): HMProgressHUD.hide() return # Add breakpoint in tapSelf HM.DPrint("Add breakpoint to hook method...") HM.addOneShotBreakPointInIMP(tapSelfIMPValue, "HMDebugHUD.tapSelfBreakPointHandler", "HMDebugHUD_TapSelf_Breakpoint") HM.DPrint(f"Register {gClassName} done!") # Show HUD command showHUDFunc() HMProgressHUD.hide() HM.processContinue() def removeDebugHUD(debugger, command, exe_ctx, result, internal_dict) -> None: """ Syntax: removehud Examples: (lldb) removehud This command is implemented in HMDebugHUD.py """ global gClassName if not HM.existClass(gClassName): HM.DPrint(f"{gClassName} does not exist.") return command_script = f''' UIView *keyWindow = [UIApplication sharedApplication].keyWindow; Class HUDClass = (Class)objc_lookUpClass("{gClassName}"); UIView *objView = nil; for (UIView *subView in keyWindow.subviews) {{ if ([subView isKindOfClass:HUDClass]) {{ objView = subView; break; }} }} [objView removeFromSuperview]; objView; ''' val = HM.evaluateExpressionValue(command_script) if HM.judgeSBValueHasValue(val): HM.DPrint("remove done!") else: HM.DPrint(f"{gClassName} does not exist.") def isDisplayingHUD() -> bool: if not HM.existClass(gClassName): return False command_script = f''' BOOL isDisplaying = NO; UIView *keyWindow = [UIApplication sharedApplication].keyWindow; UIView *HUD = nil; Class HUDClass = (Class)objc_lookUpClass("{gClassName}"); for (UIView *subView in keyWindow.subviews) {{ if ([subView isKindOfClass:HUDClass]) {{ isDisplaying = YES; HUD = subView; break; }} }} if (HUD) {{ [keyWindow bringSubviewToFront:HUD]; }} isDisplaying; ''' val = HM.evaluateExpressionValue(command_script) return HM.boolOfSBValue(val) def showHUDFunc() -> None: addToKeyWindowCommand = f''' Class HUD = NSClassFromString(@"{gClassName}"); (UIView *)[HUD performSelector:@selector(addToKeyWindow)]; ''' HM.evaluateExpressionValue(addToKeyWindowCommand) def currentTask() -> lldb.SBValue: taskValue = HM.evaluateExpressionValue("(unsigned int)(long)mach_task_self_") return taskValue def addUpdateMethods() -> bool: global gClassName debugHUDtickIMPValue = makeDebugHUDtickIMP() if not HM.judgeSBValueHasValue(debugHUDtickIMPValue): return False HM.addInstanceMethod(gClassName, "debugHUDtick:", debugHUDtickIMPValue.GetValue(), "v@:@") updateMemoryFootprintIMPValue = makeUpdateMemoryFootprintIMP() if not HM.judgeSBValueHasValue(updateMemoryFootprintIMPValue): return False HM.addInstanceMethod(gClassName, "updateMemoryFootprint", updateMemoryFootprintIMPValue.GetValue(), "v@:") updateCPUUtilizationIMPValue = makeUpdateCPUUtilizationIMP() if not HM.judgeSBValueHasValue(updateCPUUtilizationIMPValue): return False HM.addInstanceMethod(gClassName, "updateCPUUtilization", updateCPUUtilizationIMPValue.GetValue(), "v@:") updateFPSIMPValue = makeUpdateFPSIMP() if not HM.judgeSBValueHasValue(updateFPSIMPValue): return False HM.addInstanceMethod(gClassName, "updateFPS:", updateFPSIMPValue.GetValue(), "v@:i") return True def makeAddToKeyWindowIMP() -> lldb.SBValue: command_script = f''' UIView * (^addToKeyWindowBlock)(id) = ^UIView *(id classSelf) {{ UIView *HUD = (UIView *)[[NSClassFromString(@"{gClassName}") alloc] init]; (void)[HUD setFrame:(CGRect){{60, [UIApplication sharedApplication].statusBarFrame.size.height, 42, 42}}]; (void)[HUD setBackgroundColor:[UIColor colorWithWhite:0.6 alpha:0.8]]; CGFloat rowHeight = 14; CGFloat rowWidth = 40; UILabel *memoryLab = [[UILabel alloc] initWithFrame:(CGRect){{0, 0 * rowHeight, rowWidth, rowHeight}}]; memoryLab.textAlignment = (NSTextAlignment)2; [HUD addSubview:memoryLab]; [HUD setValue:memoryLab forKey:@"_memoryLab"]; UILabel *cpuUtilizationLab = [[UILabel alloc] initWithFrame:(CGRect){{0, 1 * rowHeight, rowWidth, rowHeight}}]; cpuUtilizationLab.textAlignment = (NSTextAlignment)2; [HUD addSubview:cpuUtilizationLab]; [HUD setValue:cpuUtilizationLab forKey:@"_cpuUtilizationLab"]; UILabel *fpsLab = [[UILabel alloc] initWithFrame:(CGRect){{0, 2 * rowHeight, rowWidth, rowHeight}}]; fpsLab.textAlignment = (NSTextAlignment)2; [HUD addSubview:fpsLab]; [HUD setValue:fpsLab forKey:@"_fpsLab"]; CADisplayLink *link = [CADisplayLink displayLinkWithTarget:HUD selector:NSSelectorFromString(@"debugHUDtick:")]; [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; [HUD setValue:link forKey:@"_link"]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:HUD action:@selector(tapSelf)]; [HUD addGestureRecognizer:tap]; [[UIApplication sharedApplication].keyWindow addSubview:HUD]; return HUD; }}; imp_implementationWithBlock(addToKeyWindowBlock); ''' return HM.evaluateExpressionValue(expression=command_script, prefix=HMExpressionPrefix.gPrefix) def makeTapSelfIMP() -> lldb.SBValue: command_script = f''' void (^tapSelfBlock)(UIView *) = ^(UIView *HUD) {{ Class cls = (Class)objc_lookUpClass("{HMDebugMainViewController.gClassName}"); (id)[cls performSelector:@selector(present)]; }}; imp_implementationWithBlock(tapSelfBlock); ''' return HM.evaluateExpressionValue(command_script) def makeDebugHUDtickIMP() -> lldb.SBValue: command_script = ''' void (^debugHUDtickBlock)(UIView *, CADisplayLink *) = ^(UIView *HUD, CADisplayLink *link) { NSNumber *countNum = [HUD valueForKey:@"_count"]; int count = [countNum intValue] + 1; [HUD setValue:@(count) forKey:@"_count"]; NSNumber *lastTimeNum = [HUD valueForKey:@"_lastTime"]; double delta = link.timestamp - [lastTimeNum doubleValue]; if (delta < 1) { return; } [HUD setValue:@(link.timestamp) forKey:@"_lastTime"]; [HUD setValue:@(0) forKey:@"_count"]; int fps = (int)((count / delta) + 0.5); (void)[HUD updateMemoryFootprint]; (void)[HUD updateCPUUtilization]; (void)[HUD updateFPS:fps]; }; imp_implementationWithBlock(debugHUDtickBlock); ''' return HM.evaluateExpressionValue(command_script) def makeUpdateMemoryFootprintIMP() -> lldb.SBValue: command_script = f''' void (^updateMemoryFootprintBlock)(UIView *) = ^(UIView *HUD) {{ task_vm_info_data_t vmInfo; vmInfo.phys_footprint = 0; mach_msg_type_number_t count = ((mach_msg_type_number_t) (sizeof(task_vm_info_data_t) / sizeof(natural_t))); unsigned int task_vm_info = 22; unsigned int task = {currentTask().GetValue()}; kern_return_t result = (kern_return_t)task_info((unsigned int)task, (unsigned int)task_vm_info, (task_info_t)&vmInfo, &count); int kern_success = 0; if (result != kern_success) {{ return; }} int megabyte = (int)(vmInfo.phys_footprint / 1024.0 / 1024.0 + 0.5); UIColor *valueColor = [UIColor whiteColor]; UIFont *valueFont = [UIFont systemFontOfSize:12]; UIColor *unitColor = [UIColor whiteColor]; UIFont *unitFont = [UIFont systemFontOfSize:8]; NSMutableAttributedString *valueText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d", megabyte] attributes:@{{(id)NSFontAttributeName: valueFont, (id)NSForegroundColorAttributeName: valueColor}}]; NSAttributedString *unitText = [[NSAttributedString alloc] initWithString:@" MB" attributes:@{{(id)NSFontAttributeName: unitFont, (id)NSForegroundColorAttributeName: unitColor}}]; [valueText appendAttributedString:unitText]; UILabel *memoryLab = [HUD valueForKey:@"_memoryLab"]; memoryLab.attributedText = valueText; }}; imp_implementationWithBlock(updateMemoryFootprintBlock); ''' return HM.evaluateExpressionValue(command_script) def makeUpdateCPUUtilizationIMP() -> lldb.SBValue: command_script = f''' void (^updateCPUUtilizationBlock)(UIView *) = ^(UIView *HUD) {{ double totalUsageRatio = 0; double maxRatio = 0; thread_info_data_t thinfo; thread_act_array_t threads; thread_basic_info_t basic_info_t; mach_msg_type_number_t count = 0; mach_msg_type_number_t thread_info_count = 32; int kern_success = 0; int thread_basic_info = 3; int th_flags_idle = 2; double th_usage_scale = 1000.0; if ((kern_return_t)(task_threads({currentTask().GetValue()}, &threads, &count)) == kern_success) {{ for (int idx = 0; idx < count; idx++) {{ if ((kern_return_t)(thread_info(threads[idx], thread_basic_info, (thread_info_t)thinfo, &thread_info_count)) == kern_success) {{ basic_info_t = (thread_basic_info_t)thinfo; if (!(basic_info_t->flags & th_flags_idle)) {{ double cpuUsage = basic_info_t->cpu_usage / th_usage_scale; if (cpuUsage > maxRatio) {{ maxRatio = cpuUsage; }} totalUsageRatio += cpuUsage; }} }} }} if ((kern_return_t)(vm_deallocate({currentTask().GetValue()}, (vm_address_t)threads, count * sizeof(thread_t))) != kern_success) {{ printf("[HMLLDB] vm_deallocate failed\\n"); }} }} int cpuUtilization = (int)(totalUsageRatio * 100.0); UIColor *valueColor = [UIColor whiteColor]; if (cpuUtilization >= 95) {{ valueColor = [[UIColor alloc] initWithRed:0.88 green:0.36 blue:0.36 alpha:1]; }} else if (cpuUtilization > 80) {{ valueColor = [[UIColor alloc] initWithRed:0.91 green:0.73 blue:0.45 alpha:1]; }} UIFont *valueFont = [UIFont systemFontOfSize:12]; UIColor *unitColor = [UIColor whiteColor]; UIFont *unitFont = [UIFont systemFontOfSize:8]; NSMutableAttributedString *valueText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d", cpuUtilization] attributes:@{{(id)NSFontAttributeName: valueFont, (id)NSForegroundColorAttributeName: valueColor}}]; NSAttributedString *unitText = [[NSAttributedString alloc] initWithString:@" %" attributes:@{{(id)NSFontAttributeName: unitFont, (id)NSForegroundColorAttributeName: unitColor}}]; [valueText appendAttributedString:unitText]; UILabel *cpuUtilizationLab = [HUD valueForKey:@"_cpuUtilizationLab"]; cpuUtilizationLab.attributedText = valueText; }}; imp_implementationWithBlock(updateCPUUtilizationBlock); ''' return HM.evaluateExpressionValue(command_script) def makeUpdateFPSIMP() -> lldb.SBValue: command_script = ''' void (^updateFPSBlock)(UIView *, int) = ^(UIView *HUD, int fps) { UIColor *valueColor = [UIColor whiteColor]; if (fps < 45) { valueColor = [[UIColor alloc] initWithRed:0.88 green:0.36 blue:0.36 alpha:1]; } else if (fps < 52) { valueColor = [[UIColor alloc] initWithRed:0.91 green:0.73 blue:0.45 alpha:1]; } UIFont *valueFont = [UIFont systemFontOfSize:12]; UIColor *unitColor = [UIColor whiteColor]; UIFont *unitFont = [UIFont systemFontOfSize:8]; NSMutableAttributedString *valueText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d", fps] attributes:@{(id)NSFontAttributeName: valueFont, (id)NSForegroundColorAttributeName: valueColor}]; NSAttributedString *unitText = [[NSAttributedString alloc] initWithString:@" FPS" attributes:@{(id)NSFontAttributeName: unitFont, (id)NSForegroundColorAttributeName: unitColor}]; [valueText appendAttributedString:unitText]; UILabel *fpsLab = [HUD valueForKey:@"_fpsLab"]; fpsLab.attributedText = valueText; }; imp_implementationWithBlock(updateFPSBlock); ''' return HM.evaluateExpressionValue(command_script) def addMoveMethods() -> bool: global gClassName touchesMovedWithEventIMPValue = makeTouchesMovedWithEventIMP() if not HM.judgeSBValueHasValue(touchesMovedWithEventIMPValue): return False HM.addInstanceMethod(gClassName, "touchesMoved:withEvent:", touchesMovedWithEventIMPValue.GetValue(), "v@:@@") touchesEndedWithEventIMPValue = makeTouchesEndedWithEventIMP() if not HM.judgeSBValueHasValue(touchesEndedWithEventIMPValue): return False HM.addInstanceMethod(gClassName, "touchesEnded:withEvent:", touchesEndedWithEventIMPValue.GetValue(), "v@:@@") touchesCancelledWithEventIMPValue = makeTouchesCancelledWithEventIMP() if not HM.judgeSBValueHasValue(touchesCancelledWithEventIMPValue): return False HM.addInstanceMethod(gClassName, "touchesCancelled:withEvent:", touchesCancelledWithEventIMPValue.GetValue(), "v@:@@") attachToEdgeIMPValue = makeAttachToEdgeIMP() if not HM.judgeSBValueHasValue(attachToEdgeIMPValue): return False HM.addInstanceMethod(gClassName, "attachToEdge", attachToEdgeIMPValue.GetValue(), "v@:") return True def makeTouchesMovedWithEventIMP() -> lldb.SBValue: command_script = f''' void (^touchesMovedWithEventBlock)(UIView *, NSSet *, UIEvent *) = ^(UIView *HUD, NSSet * touches, UIEvent *event) {{ Class cls = objc_lookUpClass("{gClassName}"); struct objc_super superInfo = {{ .receiver = HUD, .super_class = (Class)class_getSuperclass((Class)cls) }}; ((void (*)(struct objc_super *, SEL, id, id))objc_msgSendSuper)(&superInfo, @selector(touchesMoved:withEvent:), touches, event); UIView *superView = HUD.superview; if (!superView) {{ return; }} UITouch *touch = [touches anyObject]; CGPoint previousPoint = [touch previousLocationInView:HUD]; CGPoint currentPoint = [touch locationInView:HUD]; CGPoint targetCenter = HUD.center; CGFloat offsetX = currentPoint.x - previousPoint.x; CGFloat offsetY = currentPoint.y - previousPoint.y; if ((offsetX * offsetX < 1) && (offsetY * offsetY < 1)) {{ return; }} targetCenter.x = ceil(HUD.center.x + offsetX); targetCenter.y = ceil(HUD.center.y + offsetY); HUD.center = targetCenter; }}; imp_implementationWithBlock(touchesMovedWithEventBlock); ''' return HM.evaluateExpressionValue(expression=command_script, prefix=HMExpressionPrefix.gPrefix) def makeTouchesEndedWithEventIMP() -> lldb.SBValue: command_script = f''' void (^touchesEndedWithEventBlock)(UIView *, NSSet *, UIEvent *) = ^(UIView *HUD, NSSet * touches, UIEvent *event) {{ Class cls = objc_lookUpClass("{gClassName}"); struct objc_super superInfo = {{ .receiver = HUD, .super_class = (Class)class_getSuperclass((Class)cls) }}; ((void (*)(struct objc_super *, SEL, id, id))objc_msgSendSuper)(&superInfo, @selector(touchesEnded:withEvent:), touches, event); (void)[HUD attachToEdge]; }}; imp_implementationWithBlock(touchesEndedWithEventBlock); ''' return HM.evaluateExpressionValue(command_script) def makeTouchesCancelledWithEventIMP() -> lldb.SBValue: command_script = f''' void (^touchesCancelledWithEventBlock)(UIView *, NSSet *, UIEvent *) = ^(UIView *HUD, NSSet * touches, UIEvent *event) {{ Class cls = objc_lookUpClass("{gClassName}"); struct objc_super superInfo = {{ .receiver = HUD, .super_class = (Class)class_getSuperclass((Class)cls) }}; ((void (*)(struct objc_super *, SEL, id, id))objc_msgSendSuper)(&superInfo, @selector(touchesCancelled:withEvent:), touches, event); (void)[HUD attachToEdge]; }}; imp_implementationWithBlock(touchesCancelledWithEventBlock); ''' return HM.evaluateExpressionValue(command_script) def makeAttachToEdgeIMP() -> lldb.SBValue: command_script = ''' void (^attachToEdgeBlock)(UIView *, NSSet *, UIEvent *) = ^(UIView *HUD, NSSet * touches, UIEvent *event) { if (!HUD.window) { return; } UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero; if ([HUD.window respondsToSelector:@selector(safeAreaInsets)]) { safeAreaInsets = [HUD.window safeAreaInsets]; } CGFloat minX = safeAreaInsets.left; CGFloat maxX = HUD.window.bounds.size.width - safeAreaInsets.right; CGFloat minY = safeAreaInsets.top; CGFloat maxY = HUD.window.bounds.size.height - safeAreaInsets.bottom; CGFloat x = HUD.frame.origin.x; if (x < minX) { x = minX; } if (x > maxX - HUD.frame.size.width) { x = maxX - HUD.frame.size.width; } CGFloat y = HUD.frame.origin.y; if (y < minY) { y = minY; } if (y > maxY - HUD.frame.size.height) { y = maxY - HUD.frame.size.height; } CGRect targetFrame = (CGRect)[HUD frame]; targetFrame.origin = (CGPoint){x, y}; [UIView animateWithDuration:0.2 animations:^{ HUD.frame = targetFrame; }]; }; imp_implementationWithBlock(attachToEdgeBlock); ''' return HM.evaluateExpressionValue(expression=command_script, prefix=HMExpressionPrefix.gPrefix) def tapSelfBreakPointHandler(frame, bp_loc, internal_dict) -> bool: HMDebugMainViewController.register() HM.processContinue() return True
import torch import torch.nn as nn import torch.nn.functional as F class Generator(nn.Module): def __init__(self): super(Generator, self).__init__() self.linear_z = nn.Linear(100, 200) self.linear_y = nn.Linear(10, 1000) self.linear = nn.Linear(1200, 784) # "In our generator net, a noise prior z with dimensionality 100 was drawn from a uniform distribution within # the unit hypercube. Both z and y (one-hot label <- added by Noel) are mapped to hidden layers with Rectified # Linear Unit (ReLU) activation, with layer sizes 200 and 1000 respectively, before both being mapped to second, # combined hidden ReLu layer of dimensionality 1200. We then have a final sigmoid unit layer as our output for # generating the 784-dimensional MNIST samples." - Conditional Generative Adversarial Networks. def forward(self, z, y): x = torch.cat((self.linear_z(z), self.linear_y(y)), dim=1) x = F.dropout(x, p=0.5) return nn.Sigmoid()(self.linear(x)) class Discriminator(nn.Module): def __init__(self): super(Discriminator, self).__init__() self.linear_x = Maxout(28 * 28, 240, k=5, dropout=False) self.linear_y = Maxout(10, 50, k=5, dropout=False) self.linear_1 = Maxout(290, 240, k=4) self.linear_2 = nn.Linear(240, 1) # "The discriminator maps x to a maxout layer with 240 units and 5 pieces, and y to a maxout layer with 50 units # and 5 pieces. Both of the hidden layers mapped to a joint maxout layer with 240 units and 4 pieces before # being fed to the sigmoid layer." def forward(self, x, y): x = torch.cat((self.linear_x(x), self.linear_y(y)), dim=1) x = F.dropout(self.linear_1(x), p=0.5) return nn.Sigmoid()(self.linear_2(x)) class Maxout(nn.Module): def __init__(self, in_features, out_features, k=2, dropout=True, p=0.5): super(Maxout, self).__init__() model = [nn.Dropout(p)] if dropout else [] model += [nn.Linear(in_features, out_features * k)] self.model = nn.Sequential(*model) self.k = k # Note that dropout is used before weight multiplication following 'Maxout Networks' paper. # "When training with dropout, we perform the element-wise multiplication with the dropout mask immediately # prior to the multiplication by the weights in all cases-we do not drop inputs to the max operator." - Maxout # Networks def forward(self, x): x = self.model(x) x, _ = x.view(x.shape[0], x.shape[1] // self.k, self.k).max(-1) return x
import os,sys,time from Tkinter import * from PIL import Image, ImageTk import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(8, GPIO.IN, pull_up_down=GPIO.PUD_UP) def RunPlaylist(): hdmi.destroy() path = '/home/pi/Desktop/majestic-pi/current.txt' file = open(path,'r') files = file.readlines() file.close() global cinema for file in files: filename = file.strip() if '.mp4' in filename: os.system('/usr/bin/omxplayer ' + filename) if __name__ == '__main__': global hdmi hdmi = Tk() hdmi.title("DCM - Home Cinema") cable = Image.open("hdmi.png") cables = ImageTk.PhotoImage(cable) cableimage = Label(hdmi, image=cables) cableimage.grid() mainloop() while True: input_state = GPIO.input(8) if input_state == False: RunPlaylist()
from csvhandler import * import logging class DataFeed(object): def __init__(self, instrument): self.feed = None self.subscribe_to_price_feed_for_instrument(instrument) def n_day_moving_avg(self, instrument, date, price, n): ''' trading, not calendar, day average ''' j = -1 for i in range(len(self.feed)): if (self.feed[i]['date'] == date): j = i break tally = Decimal(0) counted = Decimal(0) for i in range(n): if (j - i >= 0): tally = tally + self.feed[j - i][price] counted = counted + 1 if (counted == 0): return None avg = tally / counted return avg def get_price(self, instrument, date, price): for i in self.feed: if (i['date'] == date): return i[price] return None def get_price_info(self, instrument, date): for i in self.feed: if (i['date'] == date): return i return None def subscribe_to_price_feed_for_instrument(self, instrument): root = '/home/david/pycode/mp/data/csv/' file_name = root + instrument + '.csv' logging.info('creating data feed for') logging.info(file_name) raw_rows = load_csv_data_rows(file_name) dicts = rows_to_dicts(raw_rows) sorted_dicts = sorted(dicts, key=lambda k: k['date']) self.feed = sorted_dicts def date_is_trading_day(self, d): for day in self.feed: if (day['date'] == d): return True return False
from Crypto import Random from Crypto.Cipher import AES from Crypto.Hash import SHA256 def get_key( password: str ) -> bytes: """Generates an encryption key based on the password provided.""" key = SHA256.new(password.encode()).digest() return key def encrypt( key: bytes, source: bytes ) -> bytes: """Encrypts source data using the provided encryption key""" IV = Random.new().read(AES.block_size) # generate IV encryptor = AES.new(key, AES.MODE_CBC, IV) padding = AES.block_size - len(source) % AES.block_size # calculate needed padding source += bytes([padding]) * padding # Python 2.x: source += chr(padding) * padding data = IV + encryptor.encrypt(source) # store the IV at the beginning and encrypt return data def decrypt( key: bytes, source: bytes ) -> bytes: IV = source[: AES.block_size] # extract the IV from the beginning decryptor = AES.new(key, AES.MODE_CBC, IV) data = decryptor.decrypt(source[AES.block_size :]) # decrypt padding = data[-1] # pick the padding value from the end; Python 2.x: ord(data[-1]) if ( data[-padding:] != bytes([padding]) * padding ): # Python 2.x: chr(padding) * padding raise ValueError("Invalid padding...") return data[:-padding] # remove the padding
from .dataset import split, deploy, deploy_and_split from .generic import * class DatasetCreator: ''' Create a dataset from a string. dataset_cmd (str): Command to execute. ex: "ImageList('path/to/list.txt')" Returns: instanciated dataset. ''' def __init__(self, globs): for k, v in globs.items(): globals()[k] = v def __call__(self, dataset_cmd ): if '(' not in dataset_cmd: dataset_cmd += "()" try: return eval(dataset_cmd) except NameError: import sys, inspect dbs = [name for name,obj in globals().items() if name[0]!='_' and name not in ('DatasetCreator','defaultdict') and inspect.isclass(obj)] print("Error: unknown dataset %s\nAvailable datasets: %s" % (dataset_cmd.replace('()',''), ', '.join(sorted(dbs))), file=sys.stderr) sys.exit(1)
class Logger: enable_logging = True def __init__(self, owning_class): self.owning_class_name = type(owning_class).__name__ def warning(self, message): self.log("Warning: " + message) def log(self, message): if (Logger.enable_logging): print(self.owning_class_name + " - " + message)
def bezout(a, b): """returns u, v such as au+bv = pgcd(a,b)""" if b == 0: return (1, 0) else: (u, v) = bezout(b, a % b) return (v, u - (a // b) * v) def chinese_theorem_inv(modulo_list): """ Returns (x, n1*...*nk) such as x mod mk = ak for all k, with modulo_list = [(a1, n1), ..., (ak, nk)] n1, ..., nk most be coprime 2 by 2. """ a, n = modulo_list[0] for a2, n2 in modulo_list[1:]: u, v = bezout(n, n2) a, n = a*v*n2+a2*u*n, n*n2 for (a1, n1) in modulo_list: assert a % n1 == a1 return ((n+a % n) % n, n) T, N, M = [int(x) for x in input().split()] for t in range(1, T+1): eq = [] for n in [5, 7, 11, 13, 17, 18]: print(" ".join(str(n) for _ in range(18)), flush=True) a = sum(int(x) for x in input().split()) % n eq.append((a, n)) res, _ = chinese_theorem_inv(eq) print(res % (M+1), flush=True) if int(input()) == -1: exit()
import unittest from mock import patch from bbpyp.ll_combinator.defer import Defer @patch('test.TestContext', create=True) class TestDefer(unittest.TestCase): def test_defer_initialized_as_expected(self, test_context): expected_parser_factory = test_context.parser_factory parser = Defer(test_context.parser_factory, test_context.concat_factory, test_context.lhs_or_rhs_factory, test_context.expression_factory, test_context.apply_factory, test_context.greedy_factory, test_context.defer_factory, source_format_service=test_context.source_format_service, context_service=test_context.context_service) self.assertIs(expected_parser_factory, parser._parser_factory) def test_defer_string_representation_is_as_expected(self, test_context): expected_representation = f"{Defer.__name__}({test_context.parser_factory})" parser = Defer(test_context.parser_factory, test_context.concat_factory, test_context.lhs_or_rhs_factory, test_context.expression_factory, test_context.apply_factory, test_context.greedy_factory, test_context.defer_factory, source_format_service=test_context.source_format_service, context_service=test_context.context_service) self.assertEqual(expected_representation, f"{parser}") def test_defer_call_first_time_sets_private_parser_to_parser_factory_result(self, test_context): tokens = [("Int", "x"), ("SYNTAX", "+"), ("SYNTAX", "+")] position = 0 parser = Defer(test_context.parser_factory, test_context.concat_factory, test_context.lhs_or_rhs_factory, test_context.expression_factory, test_context.apply_factory, test_context.greedy_factory, test_context.defer_factory, source_format_service=test_context.source_format_service, context_service=test_context.context_service) test_context.parser_factory.assert_not_called() parser(tokens, position) test_context.parser_factory.assert_called_once() def test_defer_call_subsequent_times_gets_existing_private_parser_and_does_not_call_parser_factory(self, test_context): tokens = [("Int", "x"), ("SYNTAX", "+"), ("SYNTAX", "+")] position = 0 parser = Defer(test_context.parser_factory, test_context.concat_factory, test_context.lhs_or_rhs_factory, test_context.expression_factory, test_context.apply_factory, test_context.greedy_factory, test_context.defer_factory, source_format_service=test_context.source_format_service, context_service=test_context.context_service) parser(tokens, position) parser(tokens, position) result = parser(tokens, position) self.assertEqual(test_context.parser_factory.call_count, 1) self.assertIs(parser.parser, test_context.parser_factory.return_value) def test_defer_call_results_in_private_parser_being_called_with_expected_parameters(self, test_context): mock_parser = test_context.mock_parser_call test_context.parser_factory.return_value = mock_parser expected_private_parser = mock_parser expected_result = mock_parser.return_value tokens = [("Int", "x"), ("SYNTAX", "+"), ("SYNTAX", "+")] position = 0 parser = Defer(test_context.parser_factory, test_context.concat_factory, test_context.lhs_or_rhs_factory, test_context.expression_factory, test_context.apply_factory, test_context.greedy_factory, test_context.defer_factory, source_format_service=test_context.source_format_service, context_service=test_context.context_service) result = parser(tokens, position) self.assertIs(parser.parser, mock_parser) mock_parser.assert_called_once_with(tokens, position) self.assertIs(result, expected_result)
from dataclasses import dataclass, field from typing import Optional from bindings.csw.angle_type import AngleType from bindings.csw.vector import Vector __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class DirectionVectorType: """ Direction expressed as a vector, either using components, or using angles. """ vector: Optional[Vector] = field( default=None, metadata={ "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) horizontal_angle: Optional[AngleType] = field( default=None, metadata={ "name": "horizontalAngle", "type": "Element", "namespace": "http://www.opengis.net/gml", }, ) vertical_angle: Optional[AngleType] = field( default=None, metadata={ "name": "verticalAngle", "type": "Element", "namespace": "http://www.opengis.net/gml", }, )
class TestPolicy: def test_view_policy(self, lenses_conn): result = lenses_conn.ViewPolicy() assert type(result) is list def test_set_policy(self, lenses_conn): result = lenses_conn.SetPolicy("test_policy","All","HIGH","test_category",["test_field"]) policies = lenses_conn.ViewPolicy() for e in policies: if e['name'] == 'test_policy': policy_id = e['id'] break else: policy_id = None assert result == policy_id def test_del_policy(self, lenses_conn): assert lenses_conn.DelPolicy("test_policy") == 'OK'
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Abstract class for utilities that upload to and download from object stores.""" import abc import pathlib from typing import Callable, Optional, Union __all__ = ['ObjectStore', 'ObjectStoreTransientError'] class ObjectStoreTransientError(RuntimeError): """Custom exception class to signify transient errors. Implementations of the :class:`.ObjectStore` should re-raise any transient exceptions (e.g. too many requests, temporarily unavailable) with this class, so callers can easily detect whether they should attempt to retry any operation. For example, the :class:`.S3ObjectStore` does the following: .. testcode:: from composer.utils import ObjectStore, ObjectStoreTransientError import botocore.exceptions class S3ObjectStore(ObjectStore): def upload_object(self, file_path: str, object_name: str): try: ... except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == 'LimitExceededException': raise ObjectStoreTransientError(e.response['Error']['Code']) from e raise e Then, callers can automatically handle exceptions: .. testcode:: import time from composer.utils import ObjectStore, ObjectStoreTransientError def upload_file(object_store: ObjectStore, max_num_attempts: int = 3): for i in range(max_num_attempts): try: object_store.upload_object(...) except ObjectStoreTransientError: if i + 1 == max_num_attempts: raise else: # Try again after exponential back-off time.sleep(2**i) else: # upload successful return """ pass class ObjectStore(abc.ABC): """Abstract class for implementing object stores, such as LibcloudObjectStore and S3ObjectStore.""" def get_uri(self, object_name: str) -> str: """Returns the URI for ``object_name``. .. note:: This function does not check that ``object_name`` is in the object store. It computes the URI statically. Args: object_name (str): The object name. Returns: str: The URI for ``object_name`` in the object store. """ raise NotImplementedError(f'{type(self).__name__}.get_uri is not implemented') def upload_object( self, object_name: str, filename: Union[str, pathlib.Path], callback: Optional[Callable[[int, int], None]] = None, ) -> None: """Upload an object currently located on a disk. Args: object_name (str): Object name (where object will be stored in the container) filename (str | pathlib.Path): Path the the object on disk callback ((int, int) -> None, optional): If specified, the callback is periodically called with the number of bytes uploaded and the total size of the object being uploaded. Raises: ObjectStoreTransientError: If there was a transient connection issue with uploading the object. """ del object_name, filename, callback # unused raise NotImplementedError(f'{type(self).__name__}.upload_object is not implemented') def get_object_size(self, object_name: str) -> int: """Get the size of an object, in bytes. Args: object_name (str): The name of the object. Returns: int: The object size, in bytes. Raises: FileNotFoundError: If the file was not found in the object store. ObjectStoreTransientError: If there was a transient connection issue with getting the object size. """ raise NotImplementedError(f'{type(self).__name__}.get_object_size is not implemented') def download_object( self, object_name: str, filename: Union[str, pathlib.Path], overwrite: bool = False, callback: Optional[Callable[[int, int], None]] = None, ) -> None: """Download an object to the specified destination path. Args: object_name (str): The name of the object to download. filename (str | pathlib.Path): Full path to a file or a directory where the incoming file will be saved. overwrite (bool, optional): Whether to overwrite an existing file at ``filename``, if it exists. (default: ``False``) callback ((int) -> None, optional): If specified, the callback is periodically called with the number of bytes already downloaded and the total size of the object. Raises: FileNotFoundError: If the file was not found in the object store. ObjectStoreTransientError: If there was a transient connection issue with downloading the object. """ del object_name, filename, overwrite, callback # unused raise NotImplementedError(f'{type(self).__name__}.download_object is not implemented')
import os import os.path as osp import click from prettytable import PrettyTable import pandas as pd from he import colors from he.config import * from he.experiment import Experiment from he.util import ExclusivePersistentObject class Workspace: """HE Workspace""" def __init__(self): experiments_file = osp.join(WORKSPACE_DIR, "workspace.json") self.experiments_on_disk = ExclusivePersistentObject(experiments_file) def check(self): experiments_file = osp.join(WORKSPACE_DIR, "workspace.json") if not osp.exists(experiments_file): click.echo(colors.warning("Cannot find HE workspace!")) exit(0) def init(self): """ Init the Workspace: 1. make a root directory 2. check whether IGNORE_FILE exists 3. create a disk file to store experiments """ try: click.echo(colors.prompt('Creating directory ') + colors.path(WORKSPACE_DIR)) os.mkdir(WORKSPACE_DIR) if not os.path.exists(IGNORE_FILE): click.echo(colors.warning('Please provide .heignore!')) self.experiments_on_disk.create({}) except FileExistsError: click.echo(colors.warning('HE workspace already exists!')) def start_experiment(self, experiment_name): """ Create Experiment of name `experiment_name` only when it doesn't exist. """ self.check() experiments = self.experiments_on_disk.load() if experiment_name in experiments: # old experiment click.echo(colors.prompt('Using old experiment: ') + colors.path(experiment_name) + os.linesep) else: click.echo(colors.prompt('Create new experiment: ') + colors.path(experiment_name) + os.linesep) root = osp.join(WORKSPACE_DIR, experiment_name) experiments[experiment_name] = Experiment(root=root, name=experiment_name) self.experiments_on_disk.dump(experiments) def delete_experiment(self, experiment_name): self.check() experiments = self.experiments_on_disk.load() if experiment_name in experiments: # old experiment if click.prompt(colors.prompt("Delete experiment {}? (yes/no)".format(experiment_name))) == 'yes': experiment = experiments[experiment_name] import shutil shutil.rmtree(experiment.root) experiments.pop(experiment_name) else: click.echo(colors.warning("Cannot find experiment {}".format(experiment_name))) self.experiments_on_disk.dump(experiments) def run_trial(self, experiment_name, script, silence): """ :param experiment_name: (str) :param script: (list(str)) :param silence: (bool) whether print results on the screen """ self.check() # store the script information into the experiment # get the Trial of this script experiments = self.experiments_on_disk.load() assert experiment_name in experiments experiment = experiments[experiment_name] new_trial = experiment.add_trial(script) self.experiments_on_disk.dump(experiments) # running the new Trial new_trial.run(experiment.code, silence) def display(self, display_exp_names, arg_names, metric_names, has_exp_name, time, log, script, csv_file=None): """ :param display_exp_names: (list(str)) the names of all the experiments to be displayed :param arg_names: (list(str)) the names of all the hyper-parameters to be displayed :param metric_names: (list(str)) the names of all the metric to be displayed :param has_exp_name: (bool) whether show exp_name :param time: (bool) whether show time :param log: (bool) whether show log file_name :param script: (bool) whether show script string :param csv_file: (str) output csv filename. Defualt: None """ self.check() experiments = self.experiments_on_disk.load() if len(display_exp_names) == 0: display_exp_names = experiments.keys() else: # check whether the display experiments exists for exp_name in display_exp_names: if exp_name not in experiments: click.echo(colors.warning("Experiment {} doesn't exist".format(exp_name))) return # get the table head table_head = [] if len(display_exp_names) > 1: has_exp_name = True if has_exp_name: table_head.append("exp_name") table_head.extend(list(arg_names) + list(metric_names)) if time: table_head.append('time') if log: table_head.append('log') if script: table_head.append('script') table = PrettyTable(table_head) # get all the table rows table_rows = [] for exp_name in display_exp_names: table_rows.extend(experiments[exp_name].get_table_rows( has_exp_name, arg_names, metric_names, time, log, script)) for table_row in table_rows: table.add_row(table_row) self.experiments_on_disk.dump(experiments) print(table) if csv_file is not None: csv = pd.DataFrame(columns=table_head, data=table_rows) csv.to_csv(csv_file)
""" Initialization module. """
import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib import rc from matplotlib import rcParams from matplotlib import style # https://stackoverflow.com/questions/15814635/prettier-default-plot-colors-in-matplotlib # http://seaborn.pydata.org/tutorial/color_palettes.html #import seaborn as sns # http://tonysyu.github.io/mpltools/auto_examples/style/plot_ggplot.html #style.use('ggplot') ########################################################################### ########################### MATPLOTLIB CONFIGS ############################ ########################################################################### # http://sbillaudelle.de/2015/02/20/matplotlib-with-style.html # http://sbillaudelle.de/2015/02/23/seamlessly-embedding-matplotlib-output-into-latex.html # Activate latex text rendering plt.rc('text', usetex=True) # Controlling font size from matplotlib: https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot SMALL_SIZE = 8 MEDIUM_SIZE = 11 BIGGER_SIZE = 12 plt.rc('font', size=SMALL_SIZE) # controls default text sizes plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=BIGGER_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize plt.rc('legend', loc="best") plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title # Disable automatic layout resize. This way the plot rectangle will always be the same size. plt.rcParams['figure.autolayout'] = False plt.rcParams['legend.loc'] = "best" plt.rcParams['lines.markersize'] = 7 plt.rcParams['lines.linestyle'] = "--" plt.rcParams['lines.linewidth'] = 0.65 plt.rcParams['lines.marker'] = "^" plt.rcParams['lines.color'] = "black" plt.rcParams['figure.figsize'] = (8,5) PLOT_ALPHA = 0.45 # List of matplotlib markers: https://matplotlib.org/api/markers_api.html #colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k') # Convert the cycler of rcParams to a list of colors strings. # https://matplotlib.org/examples/color/color_cycle_demo.html # https://matplotlib.org/gallery/color/color_cycler.html colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] # Set plot styles for group plots. styles = ["o","+","*","x","D", "<"] # Set linestyles. linestyles = ['_', '-', '--', ':'] markers = [] # List of matplotlib markers: https://matplotlib.org/api/markers_api.html for m in Line2D.markers: try: if len(m) == 1 and m != ' ': markers.append(m) except TypeError: pass
from nacl.utils import random from nacl.secret import SecretBox from nacl.pwhash.argon2i import kdf class TestRule4c: def __init__(self): self.g_salt1 = b"1234567812345678" self.g_salt2 = bytes("1234567812345678", "utf8") self.nonce = b"123456781234567812345678" # 24 byte def p_example1_hard_coded1(self, password, data): key = kdf(32, password, b"1234567812345678") secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example2_hard_coded2(self, password, data): key = kdf(32, password, bytes("1234567812345678", "utf8")) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example3_local_variable1(self, password, data): salt = b"1234567812345678" key = kdf(32, password, salt) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example4_local_variable2(self, password, data): salt = bytes("1234567812345678", "utf8") key = kdf(32, password, salt) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example5_nested_local_variable1(self, password, data): salt1 = b"1234567812345678" salt2 = salt1 salt3 = salt2 key = kdf(32, password, salt3) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example6_nested_local_variable2(self, password, data): salt1 = bytes("1234567812345678", "utf8") salt2 = salt1 salt3 = salt2 key = kdf(32, password, salt3) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example_method_call(self, password, salt, data): key = kdf(32, password, salt) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example_nested_method_call(self, password, salt, data): return self.p_example_method_call(password, salt, data) def p_example7_direct_method_call1(self, password, data): salt = b"1234567812345678" return self.p_example_method_call(password, salt, data) def p_example8_direct_method_call2(self, password, data): salt = bytes("1234567812345678", "utf8") return self.p_example_method_call(password, salt, data) def p_example9_nested_method_call1(self, password, data): salt = b"1234567812345678" return self.p_example_nested_method_call(password, salt, data) def p_example10_nested_method_call2(self, password, data): salt = bytes("1234567812345678", "utf8") return self.p_example_nested_method_call(password, salt, data) def p_example11_direct_g_variable_access1(self, password, data): key = kdf(32, password, self.g_salt1) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example12_direct_g_variable_access2(self, password, data): key = kdf(32, password, self.g_salt2) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example13_indirect_g_variable_access1(self, password, data): salt = self.g_salt1 key = kdf(32, password, salt) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example14_indirect_g_variable_access2(self, password, data): salt = self.g_salt2 key = kdf(32, password, salt) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def p_example15_warning_parameter_not_resolvable(self, password, salt, data): key = kdf(32, password, salt) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text def n_example1_random_salt(self, password, data): salt = random(16) key = kdf(32, password, salt) secret_box = SecretBox(key) cipher_text = secret_box.encrypt(data, self.nonce) return cipher_text
### This is a script to get fragments using Murcko method ### import os import pandas as pd import rdkit from rdkit import Chem from rdkit.Chem.Scaffolds import MurckoScaffold as Murcko from rdkit.Chem import AllChem import numpy as np import ast def get_fragments(insmiles): """Get core and sidechains using Murcko fragmentation method Args: insmiles (str): SMILES for molecule Returns: core: scaffold SMILES side: side chain SMILES """ mol_prev = Chem.MolFromSmiles(insmiles) ### get core using Murcko fragmentation ### core = Murcko.MurckoScaffoldSmilesFromSmiles(insmiles) if core != "": mol_core = Chem.MolFromSmiles(core) ### get sidechains ### mol_side = Chem.rdmolops.DeleteSubstructs(mol_prev, mol_core) side = Chem.MolToSmiles(mol_side).split(".") else: side = [insmiles] return core, side def get_number(infile, core_column, side_column): """Get occurence number after fragmentation, input should be ... + "_addfrags.csv" Args: infile (str): input file name core_column (str): column name for core side_column(str): column name for side Returns: absolute number (dict): the absolute occurence of the fragments molecule number (dict): the number of molecules that have certain fragments (max=1 for each molecule) """ inf = pd.read_csv(infile) c_id = inf.columns.get_loc(core_column) s_id = inf.columns.get_loc(side_column) absolute_number = {frag:0 for frag in []} molecule_number = {frag:0 for frag in []} for idx, i in enumerate(inf.index): if str(inf.iloc[i,c_id]) != "nan" and inf.iloc[i,s_id] != "['']": fragments = [inf.iloc[i,c_id]] + ast.literal_eval(inf.iloc[i,s_id]) elif str(inf.iloc[i,c_id]) == "nan": fragments = ast.literal_eval(inf.iloc[i,s_id]) elif inf.iloc[i,s_id] == "['']": fragments = [inf.iloc[i,c_id]] for f in fragments: if f not in absolute_number: absolute_number[f] = 1 else: absolute_number[f] += 1 fragments = set(fragments) for f in fragments: if f not in molecule_number: molecule_number[f] = 1 else: molecule_number[f] += 1 if idx % 10000 == 0: print("Finish", idx) return absolute_number, molecule_number def fragMol(dir, infile, column_name, id=None, outfile=None, cal_occurrence=True): """Get fragments of molecules Args: dir: datadir for the input and output file infile (str): input file name, contains the SMILES inform column_name (str): column_name for SMILES id (str): defaults to None, can be given as the conlumn name of id if infile has id infor outfile (str): defaults to None, outfile will be named as "fragments.csv", can be changed using custome name cal_occurrence: whether to calculate occurrence number for fragments, if true, will creat a "fragments_occurance.npz" with frags are the name of fragments and occurance are the occurance numbers Returns: No return, but will generated two files: 1. File for fragments 2. File for original data plus the fragments information for each molecule. Filename is the infile + "_addfrags.csv" """ dir = os.path.realpath(dir) df = pd.read_csv(os.path.join(dir,infile)) smiles_list = list(df[column_name]) if id: id_list = list(df[id]) else: id_list = list(df.index) fragments = [] if outfile: out = open(os.path.join(dir, outfile), "w") else: out = open(os.path.join(dir, "fragments.csv"), "w") out.write("mol_id,frags_id,frags_SMILES\n") core_list = [] side_list = [] if cal_occurrence: occurrence = {} f_id = 0 for idx, smiles in enumerate(smiles_list): try: core, side = get_fragments(smiles) except: print(id_list[idx], ": Fragmentation failed") core_list.append("Problem") side_list.append("Problem") else: core_list.append(core) side_list.append(side) frags = set([core] + side) for f in frags: if f not in fragments and f != "": fragments.append(f) out.write(str(id_list[idx]) + "," + str(f_id) + "," + f + "\n") f_id += 1 if cal_occurrence: occurrence.update({f:1}) elif cal_occurrence and f != "": occurrence[f] += 1 if idx % 10000 == 0: print("Finish", idx) out.close() if cal_occurrence: np.savez(os.path.join(dir, "fragments_occurance.npz"), frags=list(occurrence), occurance=list(occurrence.values())) df["core_list"] = core_list df["side_list"] = side_list df.to_csv(os.path.join(dir, infile.split("/")[-1].split(".")[0] + "_addfrags.csv"), index = None) if __name__ == "__main__": dir = "../test/fragmentation/" infile = "test_fragments.csv" column_name = "SMILES" id = "idx" fragMol(dir, infile, column_name, id) infile_frag = "../test/fragmentation/test_fragments_addfrags.csv" absolute_number, molecule_number = get_number(infile_frag, "core_list", "side_list") print(absolute_number) print(molecule_number)
"""This module contains utilities for docstrings parsers.""" from __future__ import annotations from ast import PyCF_ONLY_AST from contextlib import suppress from typing import TYPE_CHECKING, Callable from griffe.agents.nodes import get_annotation from griffe.expressions import Expression, Name from griffe.logger import get_logger if TYPE_CHECKING: from griffe.dataclasses import Docstring def warning(name: str) -> Callable[[Docstring, int, str], None]: """Create and return a warn function. Parameters: name: The logger name. Returns: A function used to log parsing warnings. This function logs a warning message by prefixing it with the filepath and line number. Other parameters: Parameters of the returned function: docstring (Docstring): The docstring object. offset (int): The offset in the docstring lines. message (str): The message to log. """ logger = get_logger(name) def warn(docstring: Docstring, offset: int, message: str) -> None: # noqa: WPS430 try: prefix = docstring.parent.relative_filepath # type: ignore[union-attr] except AttributeError: prefix = "<module>" logger.warning(f"{prefix}:{(docstring.lineno or 0)+offset}: {message}") return warn def parse_annotation(annotation: str, docstring: Docstring) -> str | Name | Expression: """Parse a string into a true name or expression that can be resolved later. Parameters: annotation: The annotation to parse. docstring: The docstring in which the annotation appears. The docstring's parent is accessed to bind a resolver to the resulting name/expression. Returns: The string unchanged, or a new name or expression. """ with suppress(AttributeError, SyntaxError): code = compile(annotation, mode="eval", filename="", flags=PyCF_ONLY_AST, optimize=2) if code.body: return get_annotation(code.body, parent=docstring.parent) or annotation # type: ignore[arg-type] return annotation
from decimal import Decimal import numpy as np import matplotlib.pyplot as plt from scipy import io from scipy.optimize import minimize def cofi_costfunc(params, Y, R, num_users, num_movies, num_features, lambda_): # 还原参数 X = params[:num_movies * num_features].reshape(num_movies, num_features, order='F') Theta = params[num_movies * num_features:].reshape(num_users, num_features, order='F') # [num_movies,num_users] h = X@Theta.T # 协同滤波算法代价函数 J = ((R * (h - Y)**2).sum() + lambda_ * (Theta**2).sum() + lambda_ * (X**2).sum()) / 2 X_grad = (R * (h - Y))@Theta + lambda_ * X Theta_grad = (R * (h - Y)).T@X + lambda_ * Theta grad = np.vstack(( X_grad.reshape(-1, 1, order='F'), Theta_grad.reshape(-1, 1, order='F') )) return J, grad def check_cost_function(lambda_=0): # 创建小的测试数据 X_t = np.random.rand(4, 3) Theta_t = np.random.rand(5, 3) # 将不符合的数据去除掉 Y = X_t@Theta_t.T Y[np.random.rand(Y.shape[0], Y.shape[1]) > 0.5] = 1 R = np.zeros(Y.shape) R[Y != 0] = 1 # 进行梯度检验 X = np.random.randn(X_t.shape[0], X_t.shape[1]) Theta = np.random.randn(Theta_t.shape[0], Theta_t.shape[1]) num_users = Y.shape[1] num_movies = Y.shape[0] num_features = Theta_t.shape[1] params = np.vstack(( X.reshape(-1, 1, order='F'), Theta.reshape(-1, 1, order='F'))) def cost_func(p): return cofi_costfunc(p, Y, R, num_users, num_movies, num_features, lambda_) numgrad = compute_numberical_gradient(cost_func, params) _, grad = cofi_costfunc(params, Y, R, num_users, num_movies, num_features, lambda_) for pair in zip(numgrad, grad): print(pair) # 科学记数法显示误差 diff = Decimal(np.linalg.norm(numgrad - grad)) / \ Decimal(np.linalg.norm(numgrad + grad)) # 应该小于1e-9 print(diff) def compute_numberical_gradient(J, theta): e = 1e-4 numgrad = np.zeros(theta.shape) perturb = np.zeros(theta.shape) for i in range(theta.size): perturb[i] = e loss1, _ = J(theta - perturb) loss2, _ = J(theta + perturb) numgrad[i] = (loss2 - loss1) / (2 * e) perturb[i] = 0 return numgrad def load_movie_list(): movie_list = dict() with open('./movie_ids.txt', 'r', encoding='utf8') as fp: i = 1 for line in fp.readlines(): line = line.strip() index = line.index(' ') idx, movie_name = line[:index], line[index + 1:] movie_list[int(idx) - 1] = movie_name return movie_list def normalize_rating(Y, R): m, n = Y.shape Y_mean = np.zeros((m, 1)) Y_norm = np.zeros(Y.shape) for i in range(m): idx = np.where(R[i, :] == 1) Y_mean[i] = np.mean(Y[i, idx]) Y_norm[i, idx] = Y[i, idx] - Y_mean[i] return Y_norm, Y_mean if __name__ == '__main__': # part1 加载电影数据集 data = io.loadmat('./ex8_movies.mat') Y = data['Y'] R = data['R'] print('预期值为3.8783') print(np.mean(Y[0, R[0, :] == 1])) plt.imshow(Y) plt.ylabel('Movies') plt.xlabel('Users') plt.show() input('next step') plt.close() # part2 协同滤波算法损失函数 data = io.loadmat('./ex8_movieParams.mat') X = data['X'] Theta = data['Theta'] num_users = 4 num_movies = 5 num_features = 3 X = X[:num_movies, :num_features] Theta = Theta[:num_users, :num_features] Y = Y[:num_movies, :num_users] R = R[:num_movies, :num_users] params = np.vstack(( X.reshape(-1, 1, order='F'), Theta.reshape(-1, 1, order='F') )) J, grad = cofi_costfunc(params, Y, R, num_users, num_movies, num_features, 0) print('预期值为22.22') print(J) input('next step') # part3 协同滤波梯度 check_cost_function() input('next step') # part4 协同滤波算法正则化 J, _ = cofi_costfunc(params, Y, R, num_users, num_movies, num_features, 1.5) print('预期值为31.34') print(J) input('next step') # part5 协同滤波算法梯度正则化 check_cost_function(1.5) input('next step') # part6 对于新用户添加新的数据评级 movie_list = load_movie_list() my_ratings = np.zeros((1682, 1)) my_ratings[0] = 4 my_ratings[97] = 2 my_ratings[6] = 3 my_ratings[11] = 5 my_ratings[53] = 4 my_ratings[63] = 5 my_ratings[66] = 3 my_ratings[68] = 5 my_ratings[182] = 4 my_ratings[225] = 5 my_ratings[354] = 5 for i in range(len(my_ratings)): if my_ratings[i] > 0: print('Rated {} for {}'.format( int(my_ratings[i]), movie_list[i])) input('next step') # part7 学习电影评级 data = io.loadmat('./ex8_movies.mat') Y = data['Y'] R = data['R'] Y = np.hstack((my_ratings, Y)) R = np.hstack((np.array(my_ratings != 0), R)) Y_norm, Y_mean = normalize_rating(Y, R) num_users = Y.shape[1] num_movies = Y.shape[0] num_features = 10 X = np.random.randn(num_movies, num_features) Theta = np.random.randn(num_users, num_features) initial_parameters = np.vstack(( X.reshape(-1, 1, order='F'), Theta.reshape(-1, 1, order='F') )) lambda_ = 10 def cost_func(p): return cofi_costfunc(p, Y_norm, R, num_users, num_movies, num_features, lambda_) myoptions = {'maxiter': 100, 'disp': True} result = minimize(cost_func, initial_parameters, method='L-BFGS-B', options=myoptions, jac=True) theta = result['x'] X = theta[:num_movies * num_features].reshape( num_movies, num_features, order='F') Theta = theta[num_movies * num_features:].reshape( num_users, num_features, order='F') # part8 为你推荐电影 p = X@Theta.T my_prediction = p[:, 0] + Y_mean.flatten() movie_list = load_movie_list() ix = my_prediction.argsort()[::-1] print('\nTop recommendations for you:\n') for i in range(10): j = ix[i] print(j) print('Predicting rating {} for movie {}'.format( my_prediction[j], movie_list[j])) print('\n\nOriginal ratings provided:\n') for i in range(len(my_ratings)): if my_ratings[i] > 0: print('Rated {} for {}'.format( int(my_ratings[i]), movie_list[i]))
import glob import subprocess import sys from multiprocessing import Pool FILES_DIR = '/tmp/credo/parts' CORES = 4 def run_file(fn): print('Start compressing: %s' % fn) sp = subprocess.Popen(["xz", "-9e", fn]) sp.wait() print('... finish compressing: %s' % fn) def main(): # list all files in INPUT_DIR files = glob.glob('%s/*.json' % FILES_DIR) with Pool(CORES) as pool: # each file parsed separately pool.map(run_file, files) if __name__ == '__main__': main() sys.exit(0) # not always close
# MenuTitle: Copy Paths To All Layers for layer in Glyphs.font.selectedLayers: g = layer.parent paths = [p.copy() for p in layer.paths] for l in g.layers: if layer == l: continue l.shapes = [] for p in paths: l.paths.append(p.copy()) l.width = layer.width
from toolz.functoolz import curry from sympy.core.function import Function NAN = Function('NAN') Missing = Function('Missing') NaNProtect = Function('NaNProtect') Expit = Function('Expit') # def call_method_or_dispatch(method_name, dispatcher): # def _call_method_or_dispatch(estimator, *args, **kwargs): # try: # return getattr(estimator, method_name)(*args, **kwargs) # except AttributeError: # for klass in type(estimator).mro(): # if klass in dispatcher: # exporter = dispatcher[klass] # return exporter(estimator, *args, **kwargs) # raise # except: # raise # _call_method_or_dispatch.__name__ = method_name # return _call_method_or_dispatch def fallback(*args): def _fallback(*inner_args, **kwargs): steps = list(args) while steps: try: return steps.pop(0)(*inner_args, **kwargs) except: if not steps: raise _fallback.__name__ = args[0].__name__ return _fallback # def create_registerer(dispatcher, name): # @curry # def _register(cls, function): # dispatcher[cls] = function # return function # _register.__name__ = name # return _register
from datetime import datetime from abc import ABCMeta, abstractmethod from typing import List from domain.entry import Entry class EntryRepository(metaclass=ABCMeta): @abstractmethod def get_all_entries(self, url: str) -> List[Entry]: raise NotImplementedError @abstractmethod def get_until_last_published_entries(self, url: str, time: datetime) -> List[Entry]: raise NotImplementedError @abstractmethod def get_latest_published_entry(self, url: str) -> Entry: raise NotImplementedError
from scrabbler.scrabbler import Game # from dqn.dqn_scrabble_helpers import DQNScrabbleHelpers import random import copy class Simulation: # LETTERS = ("AAAAAAAAAB" # "BCCDDDDEEE" # "EEEEEEEEEF" # "FGGGHHIIII" # "IIIIIJKLLL" # "LMMNNNNNNO" # "OOOOOOOPPQ" # "RRRRRRSSSS" # "TTTTTTUUUU" # "VVWWXYYZ??") LETTERS = ("AAAAAB" "BCDEEE" "EEE" "FGGHIIII" "IIJKL" "LMNNO" "OOOPQ" "RRSS" "TTUU" "VWXYZ") # LETTERS = "QQQQXXXXVVVVGGGGDDDDAAAA" # LETTERS = "AAAAAQQQQQ" # LETTERS = DQNScrabbleHelpers.create_uniform_letters() RACK_SIZE = 5 @staticmethod def simulate_game(player1, player2, start_player = None): return Simulation(player1, player2, start_player).simulate() def __init__(self, player1, player2, start_player = None): # Initialize game and board self.game = Game() self.board = self.game.board # List of letters we can still pick from. self.bag = list(Simulation.LETTERS) self.players = (player1, player2) if start_player != None: self.player = start_player else: # randomly choose which player goes first so that it varies during each simulation self.player = random.randint(0,1) self.endgame = False # fills the players racks to start the game self.generate_rack_and_bag(0) self.generate_rack_and_bag(1) self.most_recent_move = None # needed for dqn def simulate(self): # Keep playing until we're out of tiles or solutions. while self.simulate_step(): self.game.show() self.print_end_game_message() p1_score = self.players[1].score_tiles_in_rack() p0_score = self.players[0].score_tiles_in_rack() return p0_score, p1_score def simulate_step(self): done = self.exectute_turn() # switch whose turn it is self.player = 1 - self.player return done def exectute_turn(self): # End of the game once either player has no letters left if self.players[0].is_rack_empty() or self.players[1].is_rack_empty(): return False print("########################## Player %d turn ############################"%(self.player + 1)) print("Bag: %s" % "".join(self.bag)) # print("Player %d rack pre-draw: %s" % (self.player + 1, self.players[self.player].get_rack())) if self.player == 0: other_player = 1 else: other_player = 0 best_move = self.players[self.player].choose_move(self.endgame, self.game, self.players[other_player].get_score(), self.players[other_player].get_rack(), self.game.dictionary) self.most_recent_move = best_move # needed for dqn # If a valid move exists, then make best move, otherwise end game if best_move: self.make_move(best_move) self.generate_new_rack() return True else: return False def generate_new_rack(self): """ Generates new rack after drawing tiles from the bag and prints out the new rack before and after the draw.""" self.generate_rack_and_bag(self.player) # print("Player %d rack post-draw: %s" % (self.player + 1, self.players[self.player].get_rack())) def generate_rack_and_bag(self, player): """Randomly chooses tiles from bag and places in rack""" new_letters = [] for i in range(Simulation.RACK_SIZE - len(self.players[player].get_rack())): # If bag has ended then end game begins if not self.bag: if not self.endgame: print('|||||||||||||||||||| END GAME STARTS NOW ||||||||||||||||||||') self.endgame = True self.players[0].set_endgame_score() self.players[1].set_endgame_score() break new_tile = random.choice(self.bag) new_letters.append(new_tile) self.bag.remove(new_tile) self.players[player].update_rack(new_letters) def make_move(self, move): """ Places given move on the board and removes tiles from the rack""" start_row = move.start_square[0] start_column = move.start_square[1] # Remove tiles that are about to be played from rack. Look at the squares on board that # will contain word after tiles are placed. If square has no tile (no letter there so # this move must place a letter there) then we must remove the letter from the rack that # corresponds to the letter that will be placed (based on index in word). If the square has # no letter AND the letter that will be placed is not in the rack then that means that it # must be a ? tile so remove the ? from the rack. if move.direction == "across": for i in range(start_column, start_column + len(move.word)): if self.board.square(start_row, i).tile is None: self.players[self.player].remove_tile_from_rack(move, i - start_column) else: for i in range(start_row, start_row + len(move.word)): if self.board.square(i, start_column).tile is None: self.players[self.player].remove_tile_from_rack(move, i - start_row) # Actually play the move here self.game.play(move.start_square, move.word, move.direction) print("Player %d plays: %s" % (self.player + 1, move.word)) self.players[self.player].update_score(move.score) def print_end_game_message(self): print("\nGAME OVER!") print("PLAYER 1 SCORE: %d ...... PLAYER 2 SCORE: %d" % (self.players[0].get_score(), self.players[1].get_score()))
print([123, 'das'] * 2 )
# -*- coding: utf-8 -*- import unittest import psycopg2 import mock from pgclient.exceptions import ErrorsRegistry as registry, PgClientError class ErrorsRegistryTest(unittest.TestCase): def test_registry(self): from psycopg2 import errorcodes codes = {k: v for k, v in errorcodes.__dict__.items() if k.startswith('CLASS_')} self.assertTrue(registry.ERRORS) # print(set(codes.values()) - set(registry.ERRORS.keys())) self.assertEqual(len(codes), len(registry.ERRORS)) for code, cls in registry.ERRORS.items(): self.assertTrue(issubclass(cls, PgClientError)) def test_get_error_class(self): pg_code = '42P01' cls = registry.get_error_class(pg_code) self.assertTrue(issubclass(cls, PgClientError)) self.assertEqual(cls.CLASS_CODE, '42') def test_get_error_class_with_none_code(self): pg_code = None cls = registry.get_error_class(pg_code) self.assertEqual(cls, PgClientError) def test_get_error(self): error = mock.MagicMock(spec=psycopg2.Error) pg_code = '08006' pg_error = 'error' diag = 'connection_failure' message = 'Connection failure' setattr(error, 'pgcode', pg_code) setattr(error, 'pgerror', pg_error) setattr(error, 'diag', diag) setattr(error, 'message', message) instance = registry.get_error(error) self.assertIsInstance(instance, PgClientError) self.assertEqual(instance.message, message) self.assertEqual(instance.pgcode, pg_code) self.assertTrue(instance.diag, diag) self.assertIn(instance.pgerror, pg_error)
import torchdiffeq import torch import torch.utils.data import torch.nn as nn import numpy as np import transformer.Constants as Constants from transformer.Layers import EncoderLayer, DecoderLayer from transformer.Modules import ScaledDotProductAttention from transformer.Models import ( Decoder, get_attn_key_pad_mask, get_non_pad_mask, get_sinusoid_encoding_table, get_subsequent_mask ) from transformer.SubLayers import PositionwiseFeedForward from odeint_ext import odeint_adjoint_ext as odeint class NodeMultiHeadAttentionFunc(nn.Module): def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1): super().__init__() self.n_head = n_head self.d_k = d_k self.d_v = d_v self.w_qs = nn.Linear(d_model, n_head * d_k) self.w_ks = nn.Linear(d_model, n_head * d_k) self.w_vs = nn.Linear(d_model, n_head * d_v) nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k))) nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k))) nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_v))) self.attention = ScaledDotProductAttention(temperature=np.power(d_k, 0.5)) self.fc = nn.Linear(n_head * d_v, d_model) nn.init.xavier_normal_(self.fc.weight) self.dropout = nn.Dropout(dropout) def forward(self, t, qkv, mask): q, k, v = qkv d_k, d_v, n_head = self.d_k, self.d_v, self.n_head sz_b, len_q, _ = q.size() sz_b, len_k, _ = k.size() sz_b, len_v, _ = v.size() q = self.w_qs(q).view(sz_b, len_q, n_head, d_k) k = self.w_ks(k).view(sz_b, len_k, n_head, d_k) v = self.w_vs(v).view(sz_b, len_v, n_head, d_v) q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, d_k) # (n*b) x lq x dk k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, d_k) # (n*b) x lk x dk v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, d_v) # (n*b) x lv x dv mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x .. output, attn = self.attention(q, k, v, mask=mask) output = output.view(n_head, sz_b, len_q, d_v) output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_q, -1) # b x lq x (n*dv) output = self.dropout(self.fc(output)) #return output, attn return output class NodeMultiHeadAttention(nn.Module): ''' Multi-Head Attention module ''' def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1, method='dopri5', rtol=1e-3, atol=1e-3): super().__init__() self.method = method self.node_func = NodeMultiHeadAttentionFunc(n_head, d_model, d_k, d_v) self.layer_norm = nn.LayerNorm(d_model) self.rtol = rtol self.atol = atol def forward(self, q, k, v, ts, mask): #q = q.unsqueeze(0) #k = k.unsqueeze(0) #v = v.unsqueeze(0) qkv = torch.stack((q, k, v), dim=0) #output, attn = odeint(self.node_func, qkv, ts, method=self.method, options={"mask":mask}, # rtol=1e-3, atol=1e-3) output = odeint(self.node_func, qkv, ts, method=self.method, options={"mask":mask}, rtol=self.rtol, atol=self.atol) # output contains approximation of q, k, v so we keep only v which is the value we want to keep #output = output[2] # keep only last element (last timestamp) #output = output[-1, :, :] output = output[-1, 0, :] output = self.layer_norm(output) #return output, attn return output class NodeEncoderLayer(nn.Module): ''' Compose with two layers ''' def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1, method='dopri5', rtol=1e-3, atol=1e-3): super(NodeEncoderLayer, self).__init__() self.slf_attn = NodeMultiHeadAttention( n_head, d_model, d_k, d_v, dropout=dropout, method=method, rtol=rtol, atol=atol) self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout) def forward(self, enc_input, ts, non_pad_mask=None, slf_attn_mask=None): #enc_output, enc_slf_attn = self.slf_attn( # enc_input, enc_input, enc_input, ts, mask=slf_attn_mask) enc_output = self.slf_attn( enc_input, enc_input, enc_input, ts, mask=slf_attn_mask) enc_output *= non_pad_mask enc_output = self.pos_ffn(enc_output) enc_output *= non_pad_mask #return enc_output, enc_slf_attn return enc_output return output class NodeEncoder(nn.Module): ''' A encoder model with self attention mechanism. ''' def __init__( self, n_src_vocab, len_max_seq, d_word_vec, n_layers, n_head, d_k, d_v, d_model, d_inner, dropout=0.1, method='dopri5', rtol=1e-3, atol=1e-3): super().__init__() n_position = len_max_seq + 1 self.src_word_emb = nn.Embedding( n_src_vocab, d_word_vec, padding_idx=Constants.PAD) self.position_enc = nn.Embedding.from_pretrained( get_sinusoid_encoding_table(n_position, d_word_vec, padding_idx=0), freeze=True) self.layer_stack = nn.ModuleList([ NodeEncoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout, method=method, rtol=rtol, atol=atol) for _ in range(n_layers)]) def forward(self, src_seq, src_pos, ts, return_attns=False): enc_slf_attn_list = [] # -- Prepare masks slf_attn_mask = get_attn_key_pad_mask(seq_k=src_seq, seq_q=src_seq) non_pad_mask = get_non_pad_mask(src_seq) # -- Forward enc_output = self.src_word_emb(src_seq) + self.position_enc(src_pos) for enc_layer in self.layer_stack: #enc_output, enc_slf_attn = enc_layer( # enc_output, ts, # non_pad_mask=non_pad_mask, # slf_attn_mask=slf_attn_mask) enc_output = enc_layer( enc_output, ts, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask) if return_attns: enc_slf_attn_list += [enc_slf_attn] if return_attns: return enc_output, enc_slf_attn_list return enc_output class NodeEncoderLayerFunc(nn.Module): def __init__(self, n_head, d_model, d_inner, d_k, d_v, dropout=0.1): super().__init__() self.mha_func = NodeMultiHeadAttentionFunc(n_head, d_model, d_k, d_v) self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout) self.layer_norm = nn.LayerNorm(d_model) def forward(self, t, enc_input, non_pad_mask, slf_attn_mask): qkv = torch.stack((enc_input, enc_input, enc_input), dim=0) output = self.mha_func(t, qkv, mask=slf_attn_mask) output *= non_pad_mask output = self.layer_norm(output) output = self.pos_ffn(output) output *= non_pad_mask output = self.layer_norm(output) return output class NodeEncoderLayer2(nn.Module): def __init__(self, n_head, d_model, d_inner, d_k, d_v, dropout=0.1, method='dopri5', rtol=1e-3, atol=1e-3): super().__init__() self.method = method self.node_func = NodeEncoderLayerFunc(n_head, d_model, d_inner, d_k, d_v, dropout) self.layer_norm = nn.LayerNorm(d_model) self.rtol = rtol self.atol = atol def forward(self, enc_input, ts, non_pad_mask=None, slf_attn_mask=None): output = odeint(self.node_func, enc_input, ts, method=self.method, options={"non_pad_mask":non_pad_mask, "slf_attn_mask":slf_attn_mask}, rtol=self.rtol, atol=self.atol) # keep only last time step output = output[-1, :, :] output = self.layer_norm(output) return output class NodeEncoder2(nn.Module): ''' A encoder model with self attention mechanism. ''' def __init__( self, n_src_vocab, len_max_seq, d_word_vec, n_layers, n_head, d_k, d_v, d_model, d_inner, dropout=0.1, method='dopri5', rtol=1e-3, atol=1e-3): super().__init__() n_position = len_max_seq + 1 self.src_word_emb = nn.Embedding( n_src_vocab, d_word_vec, padding_idx=Constants.PAD) self.position_enc = nn.Embedding.from_pretrained( get_sinusoid_encoding_table(n_position, d_word_vec, padding_idx=0), freeze=True) self.encoder = NodeEncoderLayer2( n_head, d_model, d_inner, d_k, d_v, dropout=dropout, method=method, rtol=rtol, atol=atol) def forward(self, src_seq, src_pos, ts, return_attns=False): # enc_slf_attn_list = [] # -- Prepare masks slf_attn_mask = get_attn_key_pad_mask(seq_k=src_seq, seq_q=src_seq) non_pad_mask = get_non_pad_mask(src_seq) # -- Forward enc_output = self.src_word_emb(src_seq) + self.position_enc(src_pos) enc_output = self.encoder( enc_output, ts, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask) # if return_attns: # return enc_output, enc_slf_attn_list return enc_output class NodeDecoderLayer(nn.Module): ''' Compose with three layers ''' def __init__(self, d_model, d_inner, n_head, d_k, d_v, dropout=0.1, method='dopri5', rtol=1e-3, atol=1e-3): super(NodeDecoderLayer, self).__init__() self.slf_attn = NodeMultiHeadAttention( n_head, d_model, d_k, d_v, dropout=dropout, method=method, rtol=rtol, atol=atol) self.enc_attn = NodeMultiHeadAttention( n_head, d_model, d_k, d_v, dropout=dropout, method=method, rtol=rtol, atol=atol) self.pos_ffn = PositionwiseFeedForward(d_model, d_inner, dropout=dropout) def forward(self, dec_input, enc_output, ts, non_pad_mask=None, slf_attn_mask=None, dec_enc_attn_mask=None): #dec_output, dec_slf_attn = self.slf_attn( # dec_input, dec_input, dec_input, mask=slf_attn_mask) dec_output = self.slf_attn( dec_input, dec_input, dec_input, ts, mask=slf_attn_mask) dec_output *= non_pad_mask #dec_output, dec_enc_attn = self.enc_attn( # dec_output, enc_output, enc_output, mask=dec_enc_attn_mask) dec_output = self.enc_attn( dec_output, enc_output, enc_output, ts, mask=dec_enc_attn_mask) dec_output *= non_pad_mask dec_output = self.pos_ffn(dec_output) dec_output *= non_pad_mask #return dec_output, dec_slf_attn, dec_enc_attn return dec_output class NodeDecoder(nn.Module): ''' A decoder model with self attention mechanism. ''' def __init__( self, n_tgt_vocab, len_max_seq, d_word_vec, n_layers, n_head, d_k, d_v, d_model, d_inner, dropout=0.1, method='dopri5', rtol=1e-3, atol=1e-3): super().__init__() n_position = len_max_seq + 1 self.tgt_word_emb = nn.Embedding( n_tgt_vocab, d_word_vec, padding_idx=Constants.PAD) self.position_enc = nn.Embedding.from_pretrained( get_sinusoid_encoding_table(n_position, d_word_vec, padding_idx=0), freeze=True) self.layer_stack = nn.ModuleList([ NodeDecoderLayer(d_model, d_inner, n_head, d_k, d_v, dropout=dropout, method=method, rtol=rtol, atol=atol) for _ in range(n_layers)]) def forward(self, tgt_seq, tgt_pos, src_seq, enc_output, ts, return_attns=False): dec_slf_attn_list, dec_enc_attn_list = [], [] # -- Prepare masks non_pad_mask = get_non_pad_mask(tgt_seq) slf_attn_mask_subseq = get_subsequent_mask(tgt_seq) slf_attn_mask_keypad = get_attn_key_pad_mask(seq_k=tgt_seq, seq_q=tgt_seq) slf_attn_mask = (slf_attn_mask_keypad + slf_attn_mask_subseq).gt(0) dec_enc_attn_mask = get_attn_key_pad_mask(seq_k=src_seq, seq_q=tgt_seq) # -- Forward dec_output = self.tgt_word_emb(tgt_seq) + self.position_enc(tgt_pos) for dec_layer in self.layer_stack: #dec_output, dec_slf_attn, dec_enc_attn = dec_layer( dec_output = dec_layer( dec_output, enc_output, ts, non_pad_mask=non_pad_mask, slf_attn_mask=slf_attn_mask, dec_enc_attn_mask=dec_enc_attn_mask) if return_attns: dec_slf_attn_list += [dec_slf_attn] dec_enc_attn_list += [dec_enc_attn] if return_attns: return dec_output, dec_slf_attn_list, dec_enc_attn_list #return dec_output, return dec_output class NodeTransformer(nn.Module): ''' A sequence to sequence model with attention mechanism. ''' def __init__( self, n_src_vocab, n_tgt_vocab, len_max_seq, d_word_vec=512, d_model=512, d_inner=2048, n_layers=6, n_head=8, d_k=64, d_v=64, dropout=0.1, tgt_emb_prj_weight_sharing=True, emb_src_tgt_weight_sharing=True, method='dopri5', rtol=1e-3, atol=1e-3): super().__init__() self.encoder = NodeEncoder( n_src_vocab=n_src_vocab, len_max_seq=len_max_seq, d_word_vec=d_word_vec, d_model=d_model, d_inner=d_inner, n_layers=n_layers, n_head=n_head, d_k=d_k, d_v=d_v, dropout=dropout, method=method, rtol=rtol, atol=atol) self.decoder = Decoder( n_tgt_vocab=n_tgt_vocab, len_max_seq=len_max_seq, d_word_vec=d_word_vec, d_model=d_model, d_inner=d_inner, n_layers=n_layers, n_head=n_head, d_k=d_k, d_v=d_v, dropout=dropout) #self.decoder = NodeDecoder( # n_tgt_vocab=n_tgt_vocab, len_max_seq=len_max_seq, # d_word_vec=d_word_vec, d_model=d_model, d_inner=d_inner, # n_layers=n_layers, n_head=n_head, d_k=d_k, d_v=d_v, # dropout=dropout, method=method, rtol=rtol, atol=atol) self.tgt_word_prj = nn.Linear(d_model, n_tgt_vocab, bias=False) nn.init.xavier_normal_(self.tgt_word_prj.weight) assert d_model == d_word_vec, \ 'To facilitate the residual connections, \ the dimensions of all module outputs shall be the same.' if tgt_emb_prj_weight_sharing: # Share the weight matrix between target word embedding & the final logit dense layer self.tgt_word_prj.weight = self.decoder.tgt_word_emb.weight self.x_logit_scale = (d_model ** -0.5) else: self.x_logit_scale = 1. if emb_src_tgt_weight_sharing: # Share the weight matrix between source & target word embeddings assert n_src_vocab == n_tgt_vocab, \ "To share word embedding table, the vocabulary size of src/tgt shall be the same." self.encoder.src_word_emb.weight = self.decoder.tgt_word_emb.weight def forward(self, src_seq, src_pos, tgt_seq, tgt_pos, ts): tgt_seq, tgt_pos = tgt_seq[:, :-1], tgt_pos[:, :-1] #enc_output, *_ = self.encoder(src_seq, src_pos, ts) enc_output = self.encoder(src_seq, src_pos, ts) #print("enc_ouput", enc_output.size()) dec_output, *_ = self.decoder(tgt_seq, tgt_pos, src_seq, enc_output) #dec_output = self.decoder(tgt_seq, tgt_pos, src_seq, enc_output, ts) seq_logit = self.tgt_word_prj(dec_output) * self.x_logit_scale return seq_logit.view(-1, seq_logit.size(2))
import data_preparation def main(file): data_preparation.save_data(file) file = '../data/viirs-snpp_2016_Australia.csv' main(file)
import requests class ImportApi: """ import french products from api openfoodfact""" def __init__(self): self._page = None self._page_size = None self._actual_request = None self._status_code = None self._imported_file = None @property def page(self): return self._page @page.setter def page(self, new_value): self._page = new_value @property def page_size(self): return self._page_size @page_size.setter def page_size(self, new_value): self._page_size = new_value @property def actual_request(self): return self._actual_request @actual_request.setter def actual_request(self, new_value): self._actual_request = new_value @property def status_code(self): return self._status_code @status_code.setter def status_code(self, new_value): self._status_code = new_value @property def imported_file(self): return self._imported_file @imported_file.setter def imported_file(self, new_value): self._imported_file = new_value def api_parameters(self, nbr_page=1, size_page=1000): """ define number of page and products to import""" self.page = nbr_page self.page_size = size_page def get_status_code(self): """ get the status code from de request api""" return self.status_code def api_connexion(self): """ create the connexion with the api""" try: payload = { "action": "process", "sort_by": "unique_scans_n", "page_size": self.page_size, "page": self.page, "json": 1, } self.actual_request = requests.get( "https://fr.openfoodfacts.org/cgi/search.pl?", params=payload ) self.status_code = self.actual_request.status_code except requests.exceptions.ConnectionError: print( "connexion : Ooops there some troubles with the app, " "check internet connexion please" ) def import_products(self): """ import products from the api if connexion is OK""" if self.status_code == 200: results = self.actual_request.json() products = results["products"] self.imported_file = products return self.imported_file else: print("get file : there no file to get, status code : ", self.status_code)
import cv2 import random import itertools import numpy as np from skimage.measure import compare_mse def random_drop(img, ws, ratio): h, w = img.shape[:2] drop_map = np.zeros((h, w)) img_drop = img.copy() for i, j in itertools.product(range(h // ws), range(w // ws)): drop_index = random.sample(range(ws ** 2), np.int(np.round(ws ** 2 * ratio))) for d in drop_index: x, y = i * ws + d % ws, j * ws + d // ws img_drop[x, y], drop_map[x, y] = 0, 1 return img_drop, drop_map def image_recovery(img_drop, drop_map, ws, delta, mu): h, w = img_drop.shape[:2] img_rec = img_drop.copy() for i, j in itertools.product(range(h // ws), range(w // ws)): img1 = img_drop[i * ws:(i + 1) * ws, j * ws:(j + 1) * ws].copy() img2 = img_drop[i * ws:(i + 1) * ws, j * ws:(j + 1) * ws].copy() for k, l in itertools.product(range(ws), range(ws)): if drop_map[i * ws + k, j * ws + l] == 1: img1[k, l] += delta img2[k, l] -= delta dct1 = cv2.dct(img1) dct2 = cv2.dct(img2) Y1 = np.sum(np.abs(dct1)) Y2 = np.sum(np.abs(dct2)) grad = (Y1 - Y2) / (2 * delta) img_rec[i * ws + k, j * ws + l] -= mu * grad return img_rec def recovery_iter(img_drop, drop_map, ws, delta, mu, eps=1e-05, max_iters=100): max_mse = 0 gamma = 0.01 img_rec_0 = img_drop.copy() img_rec = np.zeros(img_drop.shape) for i in range(max_iters): for c in range(3): img_rec[:, :, c] = image_recovery(img_rec_0[:, :, c], drop_map, ws, delta, mu) img_rec = np.clip(img_rec, 0, 1) mse = compare_mse(img_rec_0, img_rec) if mse > max_mse: max_mse = mse elif mse < gamma * max_mse: delta /= 10 mu /= 10 if mse < eps: break max_mse = mse img_rec_0 = img_rec.copy() return img_rec def accuracy(pred, real): return np.sum(np.argmax(pred, 1) == np.argmax(real, 1)) / pred.shape[0] def linf_distortion(img1, img2): if len(img1.shape) == 4: n = img1.shape[0] l = np.mean(np.max(np.abs(img1.reshape((n, -1)) - img2.reshape((n, -1))), axis=1), axis=0) else: l = np.max(np.abs(img1 - img2)) return l def l2_distortion(img1, img2): if len(img1.shape) == 4: n = img1.shape[0] l = np.mean(np.sqrt(np.sum((img1.reshape((n, -1)) - img2.reshape((n, -1))) ** 2, axis=1)), axis=0) else: l = np.sqrt(np.sum(img1 - img2) ** 2) return l
import numpy as np import matplotlib.pyplot as plt import os import itertools import bayesiantests as bt import matplotlib.pyplot as plt import seaborn as snb import scipy.io as sio # Define set that stores names of results files. res_list = [] # Define path to folder containing results. RESULTS_FOLDER = '../results-single-dataset/' RESULTS_FOLDER_PLOTS = '../results-single-dataset/plots/' # Go over results files in results folder. for file_name in os.listdir(RESULTS_FOLDER): if file_name.split('.')[-1] == 'mat': res_list.append(file_name) # Set rope values rope = 0.01 # Go over pairs of algorithms and compare. for idx1 in np.arange(len(res_list)-1): for idx2 in np.arange(idx1+1, len(res_list)): # Load results. acc1 = np.ravel(sio.loadmat(RESULTS_FOLDER + res_list[idx1])['res']) # pleft acc2 = np.ravel(sio.loadmat(RESULTS_FOLDER + res_list[idx2])['res']) # pright # Specify names. names = (res_list[idx1].split(".")[0].split("_")[1], res_list[idx2].split(".")[0].split("_")[1]) # Difference of accuracies. x = acc1 - acc2 # Perform Bayesian correlated t-test. pleft, prope, pright = bt.correlated_ttest(x, rope=rope, runs=10, verbose=True, names=names) # Save results to file. with open('../results-single-dataset/results_single_dataset.res', 'a') as f: f.write('{0} - {1}: pleft={2}, prope={3}, pright={4}\n'.format(names[0], names[1], pleft, prope, pright)) ### RESULTS PLOT ### # Generate samples from posterior (it is not necesssary because the posterior is a Student). samples=bt.correlated_ttest_MC(x, rope=rope, runs=10, nsamples=50000) # Plot posterior. snb.kdeplot(np.array(samples), shade=True) # Plot rope region. plt.axvline(x=-rope,color='orange') plt.axvline(x=rope,color='orange') # Add label. plt.xlabel(names[0] + " - " + names[1]) # Save figure. plt.savefig(RESULTS_FOLDER_PLOTS + names[0] + '_' + names[1] + '.png') plt.clf() ####################
# -*- coding: utf-8 -*- import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.callbacks import ModelCheckpoint import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import RobustScaler from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt mm = MinMaxScaler() ss = StandardScaler() rs = RobustScaler() toyota_df = pd.read_csv('./toyota_new.csv') X = toyota_df.drop(['Reach12+','Reach15+', 'new_reg', 'after_1m', 'year', 'after_2m', 'after_3m', 'after_4m', 'after_5m', 'after_6m','log_0', 'log_1', 'log_2', 'log_3', 'log_4', 'log_5', 'log_6'],1) y = toyota_df['log_0'] i=0 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=13, shuffle=True) ss_f = ss.fit(X_train) X_train = ss_f.transform(X_train) X_test = ss_f.transform(X_test) model = keras.Sequential([ layers.Dense(16, activation='elu', input_shape=list(X_train.shape)), layers.Dense(8, activation='elu'), layers.Dense(1) ]) optimizer = tf.keras.optimizers.SGD(learning_rate=0.00001) early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0.01, patience=300, verbose=1, mode='min', baseline=None, restore_best_weights=False) mc = ModelCheckpoint(f'{i}_best_model.h5', monitor='val_loss', mode='min', save_best_only=True) model.compile(loss='mse', optimizer=optimizer, metrics=['mae']) history = model.fit( X_train, y_train, batch_size= 5, epochs= 10000 , verbose=1, validation_data=(X_test, y_test),callbacks=[early_stopping, mc]) my_Work = pd.DataFrame(history.history) my_Work["loss"].plot(color="r") my_Work["val_loss"].plot(color="g") plt.legend() plt.title('val_loss : ' + str(my_Work['val_loss'][-1:].values[0]), pad=30) #loss, mae, mse plt.savefig(f"./{i}.png") plt.show()