text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- """ Author: Philippe 'paHpa' Vivien <philippe.vivien@nerim.com> Copyright: Nerim, 2014 """ from __future__ import unicode_literals from django.conf import settings from runner.utils.logger import logger, logdebug logdebug() class DatabaseAppsRouter(object): """ A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'} """ def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" logger.debug('self=%s model=%s' % (self, model.__dict__)) if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label): return settings.DATABASE_APPS_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" logger.debug('self=%s model=%s' % (self, model.__dict__)) if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label): return settings.DATABASE_APPS_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" logger.debug('self=%s obj1=%s obj2=%s' % (self, obj1, obj2)) db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label) db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None def allow_syncdb(self, db, model): """Make sure that apps only appear in the related database.""" logger.debug('self=%s db=%s model=%s' % (self.__dict__, db, model)) if db in settings.DATABASE_APPS_MAPPING.values(): logger.debug('ALLOW db=%s' % db) return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) == db elif settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label): logger.debug('NOT ALLOW db=%s' % db) return False return None
# Generated by Django 2.2.4 on 2019-08-31 10:53 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('vehicle', '0014_log_reason'), ] operations = [ migrations.AddField( model_name='vehicle', name='first_entry_at', field=models.DateTimeField(default=django.utils.timezone.now, null=True), ), migrations.AddField( model_name='vehicle', name='registered_at', field=models.DateTimeField(default=django.utils.timezone.now, null=True), ), ]
from lol import More courses = [] def print_courses(): for lol in courses: print('{0}', print(), '{1}', print(), '{2}', print(), '{3}', print(), '{4}', print(), '{5}', print(), '{6}', print(), '{7}.'.format(lol.coursename, lol.qualification, lol.description, lol.whystudy, lol.requirements, lol.opportunities, lol.testimonials)) print() def main(): c1 = Art courses.append(c1) c2 = Biology courses.append(c2) c3 = Business courses.append(c3) print_courses()
''' Created on Mar 12, 2016 @author: zhongzhu ''' import nltk from nltk.stem.wordnet import WordNetLemmatizer from nltk.tree import Tree lemmatizer = WordNetLemmatizer() def insert_aux(node, mainvb, aux): for c in node: if isinstance(c, nltk.Tree): if c.label() == "INSERT": c.set_label(mainvb.label()) c.remove("insert") c.append(aux) if c == mainvb: ori = c[0] c.remove(ori) c.insert(0, lemmatizer.lemmatize(ori, 'v')) if c.height() > 2: insert_aux(c, mainvb, aux) tree = Tree.fromstring("(ROOT (S (NP (PRP We)) (VP (INSERT insert) (VBD worked) (PP (IN on) (NP (DT the) (JJ final) (NN project)))) (. .)))") insert_aux(tree, Tree.fromstring("(VBD worked)"), "did") print(tree)
import os from tests.utils import check_or_update def test_cast(parser, update): code = """ typedef int int32_T; typedef unsigned int uint32_T; int32_T i; int32_T icng; uint32_T jsr; int main(){ i = (int32_T)(icng + jsr); return 0; } """ tree = parser.parse(code) file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "test_cast.tree") check_or_update(update, tree, file_path) def test_double_cast(parser, update): code = """ typedef double real_T; typedef int int32_T; typedef unsigned int uint32_T; real_T y_0; int32_T icng; uint32_T jsr; int main(){ y_0 = (real_T)(int32_T)(icng + jsr) * 2.328306436538696E-10 + 0.5; return 0; } """ tree = parser.parse(code) file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), "test_double_cast.tree") check_or_update(update, tree, file_path)
class Tile(): def __init__(self, position, is_snake, is_ladder, destination=None): self.position = position self.snake = is_snake self.ladder = is_ladder self.destination = destination def is_snake(self): return self.snake == True def is_ladder(self): return self.ladder == True def is_safe(self): return self.ladder == False and self.snake == False def increment_position(self, number): return self.position + number def decrement_position(self, number): return self.position - number
#!/usr/bin/env python3 """ Causes appveyor to wait for testing """ from os import getenv from time import sleep, time import requests HEADERS = { 'Authorization': 'Bearer {}'.format( getenv('APPVEYOR_TOKEN'))} BASE_URI = "https://ci.appveyor.com/api" INFO_URI = "projects/{}/{}/build/{}".format( getenv("APPVEYOR_ACCOUNT_NAME"), getenv("APPVEYOR_PROJECT_SLUG"), getenv("APPVEYOR_BUILD_VERSION")) MESSAGE_URI = "build/messages" TEST_TIMEOUT = 1200 TEST_BACKOFF = 30 TEST_POLL_INTERVAL = 30 # Test runners can be up to POLL_INTERVAL # out of sync, give them some time to sync up TEST_UPLOAD_INTERVAL = 60 def fetch_test_info(): """ Queries API for test info """ return requests.get( "{}/{}".format( BASE_URI, INFO_URI), headers=HEADERS).json() def fetch_test_results(): """ Downloads and unzips build artifacts """ info = fetch_test_info() print("Waiting for tests") start = time() while info["build"]["jobs"][0]["testsCount"] == 0: if time() - start > TEST_TIMEOUT: print("Timed out waiting for tests") requests.post( "{}/{}".format( BASE_URI, MESSAGE_URI), json={ "message": "Test TimeOut", "category": "error", "details": "Timed out waiting for test-runners to upload results" }) return sleep(TEST_POLL_INTERVAL) try: info = fetch_test_info() except NewConnectionError(): sleep(TEST_BACKOFF) except TimeoutError(): sleep(TEST_BACKOFF) # Finish upload sleep(TEST_UPLOAD_INTERVAL) print("Tests collected") fetch_test_results()
from twitterAPIKey import TwitterAPIKey import sys sys.path.append('/home/ec2-user/workspace/work') class TwitterAPIManager: # ไฝœๆˆใ—ใŸAPIใ‚ญใƒผใ‚’TwitterAPIKeyใ‚ฏใƒฉใ‚นใซใ‚ปใƒƒใƒˆใ—ใ€APIKeysใƒชใ‚นใƒˆใซ่ฉฐใ‚ใฆใŠใ # key๏ผ‘ใคใง15ๅˆ†้–“ใซ300ใƒชใ‚ฏใ‚จใ‚นใƒˆใ€ใ™ใชใ‚ใกๆฏŽๅˆ†20ใƒชใ‚ฏใ‚จใ‚นใƒˆใพใงใ€‚ # ใ‚ˆใฃใฆใ‚ญใƒผใฎๆ•ฐ * 20ใ‚ขใ‚ซใ‚ฆใƒณใƒˆใŒๅ–ๅพ—ๅˆถ้™็›ฎๅฎ‰ใ€‚ key1 = TwitterAPIKey( 'hogehoge1', 'fugafuga', '00000000-hogefuga', 'fugahoge') key2 = TwitterAPIKey( 'hogehoge2', 'fugafuga', '00000000-hogefuga', 'fugahoge') key3 = TwitterAPIKey( 'hogehoge3', 'fugafuga', '00000000-hogefuga', 'fugahoge') key4 = TwitterAPIKey( 'hogehoge4', 'fugafuga', '00000000-hogefuga', 'fugahoge') key5 = TwitterAPIKey( 'hogehoge5', 'fugafuga', '00000000-hogefuga', 'fugahoge') APIKeys = [key1, key2, key3, key4, key5] currentIndex = -1 def nextKey(self): self.currentIndex += 1 if self.currentIndex >= len(self.APIKeys): self.currentIndex = 0 return self.APIKeys[self.currentIndex]
import bpy from bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class MatrixMathNode(Node, ArmLogicTreeNode): '''Matrix math node''' bl_idname = 'LNMatrixMathNode' bl_label = 'Matrix Math' bl_icon = 'CURVE_PATH' property0: EnumProperty( items = [('Multiply', 'Multiply', 'Multiply')], name='', default='Multiply') def init(self, context): self.inputs.new('NodeSocketShader', 'Matrix') self.inputs.new('NodeSocketShader', 'Matrix') self.outputs.new('NodeSocketShader', 'Matrix') def draw_buttons(self, context, layout): layout.prop(self, 'property0') add_node(MatrixMathNode, category='Value')
from importlib import reload as reload_module import json from re import match from django.contrib.auth import get_user_model from django.urls import reverse, NoReverseMatch from django.http import SimpleCookie from django.test import TestCase User = get_user_model() class APITest(TestCase): longMessage = True def setUp(self): user = User.objects.create_user( username="admin", email="admin@admin.admin", password="admin" ) user.is_staff = True user.is_superuser = True user.save() user = User.objects.create_user( username="nobody", email="nobody@nobody.niks", password="nobody" ) user.is_staff = False user.is_superuser = False user.save() user = User.objects.create_user( username="somebody", email="somebody@nobody.niks", password="somebody" ) user.is_staff = False user.is_superuser = False user.save() def login(self, username, password): result = self.client.login(username=username, password=password) self.assertTrue(result, "%s should be able to log in" % username) return True def hlogin(self, username, password, session_id): response = self.post( "api-login", session_id, username=username, password=password ) self.assertEqual( response.status_code, 200, "%s should be able to login via the api" % username, ) return True def api_call(self, url_name, method, session_id=None, authenticated=False, **data): try: url = reverse(url_name) except NoReverseMatch: url = url_name method = getattr(self.client, method.lower()) kwargs = {"content_type": "application/json"} if session_id is not None: auth_type = "AUTH" if authenticated else "ANON" kwargs["HTTP_SESSION_ID"] = "SID:%s:testserver:%s" % (auth_type, session_id) response = None if data: response = method(url, json.dumps(data), **kwargs) else: response = method(url, **kwargs) # throw away cookies when using session_id authentication if session_id is not None: self.client.cookies = SimpleCookie() return response def get(self, url_name, session_id=None, authenticated=False): return self.api_call( url_name, "GET", session_id=session_id, authenticated=authenticated ) def post(self, url_name, session_id=None, authenticated=False, **data): return self.api_call( url_name, "POST", session_id=session_id, authenticated=authenticated, **data ) def put(self, url_name, session_id=None, authenticated=False, **data): return self.api_call( url_name, "PUT", session_id=session_id, authenticated=authenticated, **data ) def patch(self, url_name, session_id=None, authenticated=False, **data): return self.api_call( url_name, "PATCH", session_id=session_id, authenticated=authenticated, **data ) def delete(self, url_name, session_id=None, authenticated=False): return self.api_call( url_name, "DELETE", session_id=session_id, authenticated=authenticated ) def tearDown(self): User.objects.get(username="admin").delete() User.objects.get(username="nobody").delete() @property def response(self): return self._response @response.setter def response(self, response): self._response = ParsedResponse(response, self) @staticmethod def reload_modules(modules=()): for module in modules: reload_module(module) class ParsedResponse(object): def __init__(self, response, unittestcase): self.response = response self.t = unittestcase @property def response(self): return self._response @response.setter def response(self, response): self._response = response self.status_code = response.status_code try: self.body = response.data # pylint: disable=bare-except except: self.body = None def __getattr__(self, name): return getattr(self._response, name) def __getitem__(self, name): return self.body[name] def __len__(self): return len(self.body) def assertStatusEqual(self, code, message=None): self.t.assertEqual(self.status_code, code, message) def assertValueEqual(self, value_name, value, message=None): self.t.assertEqual(self[value_name], value, message) def assertObjectIdEqual(self, value_name, value, message=None): pattern = r".*?%s.*?/(?P<object_id>\d+)/?" % reverse("api-root") m = match(pattern, self[value_name]) if m: object_id = int(m.groupdict()["object_id"]) else: object_id = None self.t.assertEqual(object_id, value, message) def __str__(self): return str(self._response)
#Find the length of the list #find the node of K+1 #K and K+1 devided, move to in the front of the list def rotateList(head,k): if not head or head.next:return head Length = 0 cur = head while cur: Length += 1 cur = cur.next k %= Length if k == 0: return head #how to find the K+1, use fast and slow point: fast, slow = head, head for i in range(0,k): fast = fast.next while fast: fast = fast.next slow = slow.next #newHead is the Nth Node from end newHead = slow.next #devide the Node K+1 from the end and node K from the end slow.next = None fast.next = head return newHead #Time complixity : O(N) #Space complixity : O(1)
# -*- coding: utf-8 -*- """ Created on Mon 11 Jan 2016 Last update: - @author: Michiel Stock michielfmstock@gmail.com Pairwise performance measures """ import numpy as np from sklearn.metrics import roc_auc_score as auc import numba # PERFORMANCE MEASURES # -------------------- rmse = lambda Y, P : np.mean((Y - P)**2)**0.5 # mean squared error mse = lambda Y, P : np.mean( (Y - P)**2 ) # micro AUC micro_auc = lambda Y, P : auc(np.ravel(Y) > 0, np.ravel(P)) # instance AUC def instance_auc(Y, P): n, m = Y.shape return np.mean([auc(Y[i] > 0, P[i]) for i in range(n) if Y[i].var()]) # macro AUC def macro_auc(Y, P): n, m = Y.shape return np.mean([auc(Y[:,i] > 0, P[:,i]) for i in range(m) if Y[:,i].var()]) # C-index @numba.jit def c_index(y, p): """ C-index for vectors """ compared = 0.0 ordered = 0.0 n = len(y) for i in range(n): for j in range(n): if y[i] > y[j]: compared += 1 if p[i] > p[j]: ordered += 1 elif p[i] == p[j]: ordered += 0.5 return ordered / compared # C-index for matrices def matrix_c_index(Y, P, axis=0): nrows, ncols = Y.shape if axis==0: return np.mean([c_index(Y[:,i], P[:,i]) for i in range(ncols) if np.var(Y[:,i]) > 1e-8]) elif axis==1: return np.mean([c_index(Y[[i]], P[[i]]) for i in range(nrows) if np.var(Y[[i]]) > 1e-8]) else: raise KeyError
"""Test the Julython API library.""" from julythontweets import config from julythontweets.julython import Connection, Project #User, Commit import json import time from tornado.testing import AsyncHTTPTestCase from tornado.web import Application, RequestHandler, HTTPError # Building out the fake API. Contract driven! :) FAKE_DB = { "projects": {}, "users": {} } def clear_db(): FAKE_DB["projects"] = {} FAKE_DB["users"] = {} class FakeProjectHandler(RequestHandler): def get(self, project_id): if project_id not in FAKE_DB["projects"]: raise HTTPError(404) self.write(FAKE_DB["projects"][project_id]) def post(self, project_id): body = json.loads(self.request.body) if project_id in FAKE_DB["projects"]: raise HTTPError(400) body["commits"] = [] body["users"] = [] FAKE_DB["projects"][project_id] = body self.set_status(201) self.write(body) class FakeUserHandler(RequestHandler): def get(self, user_id): if user_id not in FAKE_DB["users"]: raise HTTPError(404) self.write(FAKE_DB["users"][user_id]) def post(self, user_id): body = json.loads(self.request.body) if user_id in FAKE_DB["users"]: raise HTTPError(400) FAKE_DB["users"][user_id] = body self.set_status(201) self.write(body) class FakeCommitsHandler(RequestHandler): def post(self, project_id): body = json.loads(self.request.body) user_id = body["user_id"] project = FAKE_DB["projects"][project_id] if user_id not in project["users"]: project["users"].append(user_id) project["commits"].append(body) self.set_status(201) self.write(body) class TestJulython(AsyncHTTPTestCase): def tearDown(self): super(TestJulython, self).tearDown() clear_db() def get_app(self): return Application([ ("/api/v1/projects/([^/]+)", FakeProjectHandler), ("/api/v1/projects/([^/]+)/commits", FakeCommitsHandler), ("/api/v1/users/([^/]+)", FakeUserHandler) ]) def test_julython_project(self): base_url = "http://localhost:%d/api/v1" % self.get_http_port() connection = Connection(self.io_loop, base_url) project = Project( connection, "github:julython/julythontweets", { "name": "julythontweets", "url": "https://github.com/julython/julythontweets", }) def callback(project): self.stop() project_id = "github:julython/julythontweets" escaped_project_id = "github%3Ajulython%2Fjulythontweets" self.assertEqual("projects/%s" % escaped_project_id, project.to_url()) project.save(callback) # blocks till stop or timeout self.wait() self.assertTrue(project_id in FAKE_DB["projects"]) self.assertEqual( "julythontweets", FAKE_DB["projects"][project_id]["name"])
# -*- coding: utf-8 -*- #Steven Ramirez from __future__ import unicode_literals from django.shortcuts import render, HttpResponse, redirect from .models import Users from .models import Friendship from django.contrib import messages from django.contrib.messages import error import time import bcrypt def main(request): is_signed_in = request.session.get('is_signed_in', False) if (is_signed_in == True): return redirect('/friends') return render(request, 'main.html') def login(request): if (request.method == "POST"): try: user = Users.objects.get(email = request.POST['email']) if (bcrypt.checkpw(request.POST['password'].encode('utf8'), user.password.encode('utf8'))): request.session['first_name'] = user.first_name request.session['last_name'] = user.last_name request.session['alias'] = user.alias request.session['email'] = request.POST['email'] request.session['id'] = user.id request.session['is_signed_in'] = True return redirect('/friends') else: messages.error(request, 'Incorrect password.') return redirect('/main') except: messages.error(request, 'E-mail address not found, please enter a valid e-mail.') return redirect('/main') else: return redirect('/main') def register(request): if (request.method == "POST"): errors = Users.objects.basic_validator(request.POST) if len(errors): for tag, error in errors.iteritems(): messages.error(request, error, extra_tags=tag) return redirect('/main') elif (request.POST['password'] == request.POST['confirmpw']): errors = Users.objects.basic_validator(request.POST) salt = bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt()) user = Users.objects.create(first_name = request.POST['first_name'], last_name = request.POST['last_name'], email = request.POST['email'], password = salt, alias = request.POST['alias']) user.save() return redirect('register/'+str(user.id)) else: return redirect('/main') else: return redirect('/main') def success_reg(request, idnum): user = Users.objects.get(id = idnum) return render(request, 'register.html', {'user': user}) def friends(request): if request.session['is_signed_in'] == False: return redirect('/main') user = Users.objects.get(id = request.session['id']) try: myfriends = Friendship.objects.filter(friend1_id = user.id ) if not myfriends.exists(): myfriends = None except: myfriends = None flist = Friendship.objects.filter(friend1_id = user.id ).values("friend2_id").distinct() other_users = Users.objects.exclude(id = request.session['id'] ) for i in flist: other_users = other_users.exclude(id = int(i['friend2_id'])) try: a = 1 if not other_users.exists(): other_users = None except: other_users = None #print("myfriends", myfriends) #print("others", other_users) #print(Friendship.objects.filter(friend1_id = user.id)) return render(request, 'friends.html', {'myfriends' : myfriends, 'other_users' : other_users} ) def signout(request): if request.session['is_signed_in'] == False: return redirect('/main') request.session['first_name'] = None request.session['last_name'] = None request.session['email'] = None request.session['id'] = None request.session['is_signed_in'] = False return redirect('/main') def add(request, idnum): if request.session['is_signed_in'] == False: return redirect('/main') errors = Friendship.objects.basic_validator(request.session["id"], idnum) if len(errors): for tag, error in errors.iteritems(): messages.error(request, error, extra_tags=tag) return redirect('/main') try: Users.objects.get(id = idnum) Friendship.objects.create(friend1_id = request.session['id'], friend2_id = idnum) Friendship.objects.create(friend2_id = request.session['id'], friend1_id = idnum) except: messages.error(request, "Unable to add friend :(") return redirect('/friends') return redirect('/friends') def destroy(request, idnum): if request.session['is_signed_in'] == False: return redirect('/main') try: Friendship.objects.filter(friend1_id = request.session['id'], friend2_id = idnum).delete() Friendship.objects.filter(friend2_id = request.session['id'], friend1_id = idnum).delete() except: messages.error(request, 'Friend not found.') return redirect('/friends') def users(request, idnum): if request.session['is_signed_in'] == False: return redirect('/main') try: friends = Friendship.objects.filter(friend1_id = idnum ) if not friends.exists(): friends = None except: friends = None try: user = Users.objects.get(id = idnum) except: users = None return render(request, 'users/users.html', {'friends' : friends, 'user':user}) # Create your views here.
''' Dividing two integers without using mod or dividing ''' def divide(self,dividend,divisor): is_negative = (dividend<0) != (divisor<0) divisor,dividend = abs(divisor),abs(dividend) quotient = 0 the_sum = divisor while the_sum <= dividend: current_quotient = 1 while(the_sum+the_sum)<=dividend: the_sum += the_sum current_quotient += current_quotient dividend -= the_sum the_sum = divisor quotient += current_quotient return min(2147483647,min(-quotient if is_negative else quotient , -2147483648))
# import the necessary packages import numpy as np import argparse import cv2 from PIL import Image import math isShowImage = True def showCV2Image(title, img): cv2.namedWindow(title, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # ่ฐƒๆ•ด็ช—ๅฃๅคงๅฐๅนถไฟๆŒๆฏ”ไพ‹ cv2.imshow(title, img) cv2.waitKey(0) # construct the argument parse and parse the arguments # ap = argparse.ArgumentParser() # ap.add_argument("-i", "--image", required=True,help="path to input image file") # args = vars(ap.parse_args()) # load the image from disk # image = cv2.imread(args["image"]) image = cv2.imread('r0.jpg') # convert the image to grayscale and flip the foreground and background to ensure foreground is now "white" and the background is "black" gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.bitwise_not(gray) rows, cols = gray.shape dia_length = int(math.sqrt(rows*rows+cols*cols)) img_ex = cv2.copyMakeBorder(image, int((dia_length-rows)), int((dia_length-rows)), int((dia_length-cols)), int((dia_length-cols)), cv2.BORDER_CONSTANT, value=(255, 255, 255)) cv2.imwrite('r0_1.jpg', img_ex) if isShowImage: showCV2Image('img_ex', img_ex) #ๅŠ ไบ†่พนๆก†็š„ๅ›พ rows1, cols1 = img_ex.shape[:2] center = (int(cols1/2), int(rows1/2)) # img = Image.open('r0_1.jpg') # threshold the image, setting all foreground pixels to 255 and all background pixels to 0 thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] # grab the (x, y) coordinates of all pixel values that are greater than zero, then use these coordinates to # compute a rotated bounding box that contains all coordinates coords = np.column_stack(np.where(thresh > 0)) rect = cv2.minAreaRect(coords) angle = rect[2] width = int(rect[1][0]) height = int(rect[1][1]) if width < height: img3 = cv2.rotate(img_ex, -90) # if isShowImage: # showCV2Image('img3', img3) # img = img.rotate(-90) # img.show() x1 = int(cols1/2)-int(cols/2) y1 = int(rows1/2)-int(rows/2) x2 = int(cols1/2)+int(cols/2) y2 = int(rows1/2)+int(rows/2) # img1 = img.crop((y1, x1, y2, x2)) # img1.save('r0_90.jpg') img2 = cv2.rectangle(img3, (x1, y1), (x2, y2), (0, 255, 0), 1) if isShowImage: showCV2Image('img2', img2) # the `cv2.minAreaRect` function returns values in the range [-90, 0); as the rectangle rotates clockwise the # returned angle trends to 0 -- in this special case we need to add 90 degrees to the angle if angle < -45: angle = -(90 + angle) # otherwise, just take the inverse of the angle to make it positive else: angle = -angle # rotate the image to deskew it (h, w) = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) rotated = cv2.warpAffine(image, M, (w, h),flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) # draw the correction angle on the image so we can validate it cv2.putText(rotated, "Angle: {:.2f} degrees".format(angle),(10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # show the output image print("[INFO] angle: {:.3f}".format(angle)) if isShowImage: showCV2Image('input', image) showCV2Image('rotated', rotated) cv2.imwrite('deskewed_r0.jpg', rotated)
import sys sys.stdin = open('lunchtime.txt') T = int(input()) def group(n,k): if n == k : seq = [] for i in range(n): if groups[i] == 1: gotostair(P[i],S[0],seq,0) else: gotostair(P[i],S[1],seq,1) seq.sort(key=lambda x: x[2]) # print(seq) timeflow(seq) else: groups[k] = 0 group(n, k+1) groups[k] = 1 group(n, k+1) def timeflow(seq): global Time q0 = [] q1 = [] t = 0 while seq or q0 or q1 : if t >= Time : return if q0 : if len(q0) > 3 : for i in range(3): q0[i] -= 1 while q0[0] == 0: q0.pop(0) elif len(q0) > 0: for i in range(len(q0)): q0[i] -= 1 while q0 and q0[0] == 0: q0.pop(0) if q1 : if len(q1) > 3 : for i in range(3): q1[i] -= 1 while q1[0] == 0: q1.pop(0) elif len(q1) > 0: for i in range(len(q1)): q1[i] -= 1 while q1 and q1[0] == 0: q1.pop(0) if seq: while seq and seq[0][2] == t: a = seq.pop(0) if a[3] == 0: q0.append(S[0][2]) else : q1.append(S[1][2]) t += 1 Time = t return Time def gotostair(p,g,seq,m): t = abs(p[0]-g[0])+ abs(p[1]-g[1]) seq.append(p+[t,m]) for tc in range(1, T+1): N = int(input()) G = [list(map(int, input().split())) for _ in range(N)] Time = 10000 # print(G) P = [] S = [] for i in range(N): for j in range(N): if G[i][j] == 1: P.append([j,i]) elif G[i][j] > 1 : S.append([j,i,G[i][j]]) # print(P) pnum = len(P) groups = [0]*pnum group(pnum,0) print('#{} {}' .format(tc, Time))
""" Run this script after modifying the data.json file. Regenerate the *m.png files according to new data.json. """ import json from utilities import picture import os if __name__ == "__main__": os.chdir(os.getcwd() + "/..") data_path = "views/" f = open(data_path + "data.json", 'r') data = f.read() f.close() data = json.loads(data) for view in data: ids = data[view]['elements'].keys() element_nodes = data[view]['elements'].values() picture.mark_nodes(data_path + view + '.png', element_nodes, ids)
from __future__ import absolute_import # flake8: noqa # import apis into api package from swagger_client.api.accounts_api import AccountsApi from swagger_client.api.addresses_api import AddressesApi from swagger_client.api.agreements_api import AgreementsApi from swagger_client.api.auth_api import AuthApi from swagger_client.api.captcha_api import CaptchaApi from swagger_client.api.clients_api import ClientsApi from swagger_client.api.contact_infos_api import ContactInfosApi from swagger_client.api.contacts_api import ContactsApi from swagger_client.api.files_api import FilesApi from swagger_client.api.images_api import ImagesApi from swagger_client.api.marketplace_api import MarketplaceApi from swagger_client.api.mobile_api import MobileApi from swagger_client.api.nfc_api import NFCApi from swagger_client.api.notifications_api import NotificationsApi from swagger_client.api.operations_api import OperationsApi from swagger_client.api.operators_api import OperatorsApi from swagger_client.api.pos_api import POSApi from swagger_client.api.passwords_api import PasswordsApi from swagger_client.api.payment_requests_api import PaymentRequestsApi from swagger_client.api.payments_api import PaymentsApi from swagger_client.api.pending_payments_api import PendingPaymentsApi from swagger_client.api.phones_api import PhonesApi from swagger_client.api.push_api import PushApi from swagger_client.api.records_api import RecordsApi from swagger_client.api.recurring_payments_api import RecurringPaymentsApi from swagger_client.api.scheduled_payments_api import ScheduledPaymentsApi from swagger_client.api.sessions_api import SessionsApi from swagger_client.api.tickets_api import TicketsApi from swagger_client.api.transactions_api import TransactionsApi from swagger_client.api.transfers_api import TransfersApi from swagger_client.api.ui_api import UIApi from swagger_client.api.users_api import UsersApi from swagger_client.api.validation_api import ValidationApi from swagger_client.api.vouchers_api import VouchersApi
import torch import torch.nn as nn import torch.nn.functional as F ################################## ######### ConvBn block ########### ################################## class ConvBn(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): super().__init__() self.conv_bn=nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.BatchNorm2d(out_channels)) def forward(self, x): return self.conv_bn(x) ################################## ####### ConvLeakyReLU block ###### ################################## class ConvLReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1, alpha=0.2): super().__init__() self.conv_lrelu=nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.LeakyReLU(alpha, inplace=True)) def forward(self, x): return self.conv_lrelu(x) ################################## ######### ConvPReLU block ######## ################################## class ConvPReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): super().__init__() self.conv_prelu=nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.PReLU()) def forward(self, x): return self.conv_prelu(x) ################################## ######### ConvTanh block ######### ################################## class ConvTanh(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): super().__init__() self.conv_th=nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.Tanh()) def forward(self, x): return self.conv_th(x) ################################## ####### ConvBnPReLU block ######## ################################## class ConvBnPReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): super().__init__() self.conv_bn_prelu=nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.BatchNorm2d(out_channels), nn.PReLU()) def forward(self, x): return self.conv_bn_prelu(x) ################################## ##### ConvBnLeakyReLU block ###### ################################## class ConvBnLReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=4, stride=2, padding=1, alpha=0.2): super().__init__() self.conv_bn_lrelu=nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.BatchNorm2d(out_channels), nn.LeakyReLU(alpha, inplace=True)) def forward(self, x): return self.conv_bn_lrelu(x) ################################## ####### ConvPixPReLU block ####### ################################## class ConvPixPReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1): super().__init__() self.conv_pix_prelu=nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding), nn.PixelShuffle(2), nn.PReLU()) def forward(self, x): return self.conv_pix_prelu(x) ################################## ######### Residual Block ######### ################################## class ResidualBlock(nn.Module): def __init__(self, in_channels, kernel_size=3, stride=1, padding=1): super().__init__() self.block = nn.Sequential( ConvBnPReLU(in_channels, in_channels, kernel_size, stride, padding), ConvBn(in_channels, in_channels, kernel_size, stride, padding)) def forward(self, x): fx = self.block(x) return fx + x
#! /usr/bin/env python from os import path from flask.ext.openid import OpenID from openid.extensions import pape from wmt.flask import create_app import local_settings application = create_app(settings_override=local_settings, wmt_root_path=path.abspath(path.dirname(__file__))) oid = OpenID(application, safe_roots=[], extension_responses=[pape.Response]) #if __name__ == "__main__": # from os import path # # create_app(wmt_root_path=path.abspath(path.dirname(__file__))).run()
#!/usr/bin/env python # coding: utf-8 # # **0. ์ปดํ“จํ„ฐ์™€์˜ ์†Œํ†ต์„ ์œ„ํ•œ ๋„๊ตฌ ์†Œ๊ฐœ** # # > **Python** # > - ๊ฐ„๊ฒฐํ•˜๊ณ  ์‰ฌ์šด ์ปดํ“จํ„ฐ์™€์˜ ์†Œํ†ต์–ธ์–ด # > - ๋ฐ์ดํ„ฐ๋ถ„์„๊ณผ ๋จธ์‹ ๋Ÿฌ๋‹์„ ์œ„ํ•œ ์ˆ˜๋งŽ์€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ํฌํ•จ # > - ๋‹ค์–‘ํ•œ ํ™•์žฅ์ด ์šฉ์ด(ex. R, SPSS, etc.) # # > **Anaconda** # > - Python๊ธฐ๋ฐ˜์˜ Open Data Science Platform # > - Python์„ ํฌํ•จํ•˜์—ฌ Python Library ๋“ฑ์„ ํ•˜๋‚˜๋กœ ์ •๋ฆฌํ•ด ๋‘” ๋ฐฐํฌํŒ # > - Pandas, Numpy, Matplotlib ๋“ฑ ๋ฐ์ดํ„ฐ๋ถ„์„์— ์œ ์šฉํ•œ Library๋ฅผ ํฌํ•จ # > - ์ถ”๊ฐ€์ ์ธ Library๋ฅผ ์—ฐ๊ฒฐ ๋ฐ ํ™•์žฅํ•˜์—ฌ ๊ฐœ๋ฐœ/์›น/์˜คํ”ผ์Šค/๋น„์ฆˆ๋‹ˆ์Šค๋กœ ํ™œ์šฉ๊ฐ€๋Šฅ # >> - ์–ด๋–ค ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์จ์•ผํ• ์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์„๋•Œ: https://github.com/vinta/awesome-python # >> - ์ฃผ๋ชฉ๋ฐ›๋Š” ํŒŒ์ด์ฌ ํ”„๋กœ์ ํŠธ๋“ค์„ ๋‘˜๋Ÿฌ๋ณด๊ณ  ์‹ถ์„๋•Œ: https://github.com/trending/python # # > **Jupyter Notebook / Jupyter Lab** # > - Interactive ํ™˜๊ฒฝ์„ ์ธ๊ฐ„์—๊ฒŒ ์ œ๊ณตํ•˜์—ฌ ์ปดํ“จํ„ฐ(Programming Platform)์™€ ์†Œํ†ต์„ ์‰ฝ๊ฒŒํ•จ # > - Anaconda ํ”„๋กœ๊ทธ๋ž˜๋ฐ ํ™˜๊ฒฝ์„ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ # > - ์ฝ”๋”ฉํ•˜๋ฉด์„œ ๋ฐ”๋กœ ๊ฒฐ๊ณผ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Œ # > - ๋ฌธ์„œํ™”(Markdown)์™€ ํด๋ผ์šฐ๋“œ(Git, Google Drive ๋“ฑ) ์—ฐ๊ฒฐ/์ €์žฅ ๋“ฑ์ด ๊ฐ€๋Šฅ # > - ๊ฐ์ข… ๋‹จ์ถ•ํ‚ค์™€ ํŠœํ„ฐ๋ฆฌ์–ผ ๋“ฑ์˜ ์ž๋ฃŒ๊ฐ€ ๋งŽ์Œ # # **1. ๋ถ„์„ํ™˜๊ฒฝ ์„ธํŒ…ํ•˜๊ธฐ(์œˆ๋„์šฐ10๊ธฐ์ค€)** # ## **1-1) ๊ธฐ๋ณธ์„ธํŒ…: Anaconda & Jupyter** # # **1) PC ๋‚ด ์ œ์–ดํŒ: ์ด์ „์— ์„ค์น˜๋œ ๊ธฐ๋ก์ด ์žˆ๋‹ค๋ฉด ์‚ญ์ œ** # -> ์‹œ์ž‘ -> "์ œ์–ดํŒ" ํƒ€์ดํ•‘ -> "์ œ์–ดํŒ" ์„ ํƒ # -> ํ”„๋กœ๊ทธ๋žจ๋ฐ๊ธฐ๋Šฅ ์„ ํƒ # -> Anaconda3 ๋˜๋Š” Python์œผ๋กœ ์‹œ์ž‘๋˜๋Š” ์ด๋ฆ„ ์„ ํƒ # -> ์šฐํด๋ฆญ์œผ๋กœ ์ œ๊ฑฐ # **2) ์ธํ„ฐ๋„ท: ํ”„๋กœ๊ทธ๋žจ ๋‹ค์šด๋กœ๋“œ** # -> https://www.anaconda.com/download/ ์ ‘์† # -> Windows/macOX/Linux์ค‘ Windows ํด๋ฆญ # -> Python "Download" ํด๋ฆญ # **3) PC: ๋‹ค์šด๋กœ๋“œํ•œ ํ”„๋กœ๊ทธ๋žจ ์‹คํ–‰ ๋ฐ ์„ค์น˜** # -> ๋‹ค์šด๋กœ๋“œํ•œ ์„ค์น˜ํŒŒ์ผ ์šฐํด๋ฆญ์œผ๋กœ "๊ด€๋ฆฌ์ž ๊ถŒํ•œ์œผ๋กœ ์‹คํ–‰" # ->"Next"๋ฅผ ๋ˆ„๋ฅด๋ฉฐ ์ง„ํ–‰ํ•˜๋ฉด ๋˜๋Š”๋ฐ ์„ค์น˜ ์ค‘ "Advanced Options" ํŽ˜์ด์ง€์—์„œ # "Add Anaconda to the system PATH environment variable"์„ ์„ ํƒ์„ ์ฒดํฌํ•˜๊ณ  ์ง„ํ–‰ # (๋ณธ ๋งํฌ https://hobbang143.blog.me/221461726444 "์„ค์น˜ 02" ๋ถ€ํ„ฐ ๋™์ผํ•˜๊ฒŒ ์ฐธ์กฐ) # ## **1-2) ๊ณ ๊ธ‰์„ธํŒ…: PIP & Jupyter Notebook & Jupyter Lab ์—…๋ฐ์ดํŠธ ๋ฐ ํ™•์žฅ** # # **1) PC: Anaconda Prompt ์ ‘์†** # -> ์‹œ์ž‘ -> "Anaconda" ํƒ€์ดํ•‘ # -> "Anaconda Prompt" ์šฐํด๋ฆญ์œผ๋กœ "๊ด€๋ฆฌ์ž ๊ถŒํ•œ์œผ๋กœ ์‹คํ–‰" # **2) Anaconda Prompt: PIP & Jupyter Notebook & Jupyter Lab ์—…๋ฐ์ดํŠธ ๋ฐ ํ™•์žฅ ํ•œ๋ฒˆ์— ์„ค์น˜** # **(ํ•˜๊ธฐ ๋‚ด์šฉ ๋ณต์‚ฌ ํ›„ Anaconda Prompt์— ์šฐํด๋ฆญ(๋ถ™์—ฌ๋„ฃ๊ธฐ))** # :: Update of PIP # pip install --upgrade pip # python -m pip install --user --upgrade pip # :: Jupyter Nbextensions # pip install jupyter_contrib_nbextensions # jupyter contrib nbextension install --user # :: Jupyter Lab # pip install jupyterlab # pip install --upgrade jupyterlab # :: Jupyter Lab Extensions Package # pip install nodejs # conda install --yes nodejs # conda install -c conda-forge --yes nodejs # :: Table of Contents # jupyter labextension install @jupyterlab/toc # :: Shortcut UI # jupyter labextension install @jupyterlab/shortcutui # :: Variable Inspector # jupyter labextension install @lckr/jupyterlab_variableinspector # :: Go to Definition of Module # jupyter labextension install @krassowski/jupyterlab_go_to_definition # :: Interactive Visualization # jupyter labextension install @jupyter-widgets/jupyterlab-manager # jupyter labextension install lineup_widget # :: Connection to Github # jupyter labextension install @jupyterlab/github # :: CPU+RAM Monitor # pip install nbresuse # jupyter labextension install jupyterlab-topbar-extension jupyterlab-system-monitor # :: File Tree Viewer # jupyter labextension install jupyterlab_filetree # :: Download Folder as Zip File # conda install --yes jupyter-archive # jupyter lab build # jupyter labextension update --all # :: End # # ## **1-3) ์„ ํƒ์„ธํŒ…: Jupyter Lab์— R์—ฐ๊ฒฐ** # # **1) ์ธํ„ฐ๋„ท: Rํ”„๋กœ๊ทธ๋žจ ๋‹ค์šด๋กœ๋“œ ๋ฐ ์„ค์น˜** # -> https://cran.r-project.org/bin/windows/base/ ์ ‘์† # -> "Download" ํด๋ฆญ ๋ฐ ์‹คํ–‰ # **2) ์ธํ„ฐ๋„ท: Git ์„ค์น˜** # -> https://git-scm.com ์ ‘์† # -> "Download" ํด๋ฆญ ๋ฐ ์‹คํ–‰ # **3) PC: Anaconda Prompt ์ ‘์†** # -> ์‹œ์ž‘ -> "Anaconda" ํƒ€์ดํ•‘ # -> "Anaconda Prompt" ์šฐํด๋ฆญ์œผ๋กœ "๊ด€๋ฆฌ์ž ๊ถŒํ•œ์œผ๋กœ ์‹คํ–‰" # **4) Anaconda Prompt: Jupyter Client & R์„ค์น˜** # -> conda install --yes -c anaconda jupyter_client # -> conda install --yes -c r r-essentials # **5) Anaconda Prompt: RํŒจํ‚ค์ง€ ์„ค์น˜** # -> cd C:\Program Files\R\R-3.6.1\bin(R์ด ์„ค์น˜๋œ ๊ฒฝ๋กœ๋กœ ์ด๋™) # -> R.exe # -> install.packages("devtools") # -> devtools::install_github("IRkernel/IRkernel") # -> IRkernel::installspec(user = FALSE) # # **2. ๋ถ„์„์ค€๋น„ ์„ค์ • ๋ฐ ๊ฐ•์˜์‹œ์ž‘(์œˆ๋„์šฐ10๊ธฐ์ค€)** # ## **2-1) Jupyter Notebook & Jupyter Lab ์—ด๊ธฐ ๋ฐ ๋‚ด๋ถ€ ์„ค์ •** # # **1) PC: Jupyter Notebook ์†์„ฑ ์ง„์ž…** # -> ์‹œ์ž‘ -> "Jupyter" ํƒ€์ดํ•‘ # -> "Jupyter Notebook" ์šฐํด๋ฆญ์œผ๋กœ "์ž‘์—… ํ‘œ์‹œ์ค„์— ๊ณ ์ •" # -> ์ž‘์—… ํ‘œ์‹œ์ค„์˜ "Jupyter Notebook" ์•„์ด์ฝ˜ ์šฐํด๋ฆญ # -> ์ƒ๋‹จ "Jupyter Notebook" ์šฐํด๋ฆญ -> ์†์„ฑ ํด๋ฆญ # **2) PC: Jupyter Notebook ์ž‘์—…๊ฒฝ๋กœ ๋ฐ˜์˜** # -> "๋Œ€์ƒ"์—์„œ "%USERPROFILE%/" ์‚ญ์ œํ›„ ๋ณธ์ธ ์ž‘์—… ํด๋” ๋ฐ˜์˜(ex. D:\) # -> (ํ•„์š”์‹œ:๊ธฐ์กด) jupyter-notebook-script.py (ํ•„์š”์‹œ:๋ณ€๊ฒฝ) jupyter-lab-script.py # -> "์‹œ์ž‘์œ„์น˜"์—์„œ %HOMEPATH% ์‚ญ์ œํ›„ ๋ณธ์ธ ์ž‘์—… ํด๋” ๋ฐ˜์˜(ex. D:\) # -> ํ•˜๋‹จ "ํ™•์ธ" ํด๋ฆญ # **3) PC: Jupyter Notebook ์‹คํ–‰** # -> ์ž‘์—… ํ‘œ์‹œ์ค„์˜ "Jupyter Notebook" ์ขŒํด๋ฆญ # -> (๋งŒ์•ฝ ์ธํ„ฐ๋„ท ์ฐฝ์ด ๋ฐ˜์‘์ด ์—†๋‹ค๋ฉด) ์ธํ„ฐ๋„ท ์ฃผ์†Œ์ฐฝ์— http://localhost:8888/tree ํƒ€์ดํ•‘ # **4) PC: Jupyter Notebook Nbextensions ๊ธฐ๋Šฅ ์ถ”๊ฐ€** # -> Files/Running/Clusters/Nbextensions ์ค‘ Nbextensions ํด๋ฆญ # -> "disable configuration for nbextensions without explicit compatibility" ์ฒดํฌ ํ•ด์ œ # -> ํ•˜๊ธฐ 7์ข… ํด๋ฆญํ•˜์—ฌ ๊ธฐ๋Šฅํ™•์ธ ํ›„ ํ•„์š”์‹œ ์ถ”๊ฐ€(Table of Contents๋Š” ์ˆ˜์—…์šฉ ํ•„์ˆ˜) # - Table of Contents # - Autopep8 # - Codefolding # - Collapsible Headings # - Hide Input All # - Execute Time # - Variable Inspector # # **5) PC: Jupyter Notebook์œผ๋กœ ๊ฐ•์˜์‹œ์ž‘(์ด๋ก ๋Œ€์‘)** # -> Files/Running/Clusters/Nbextensions ์ค‘ Files ํด๋ฆญ # -> ๋‹ค์šด๋กœ๋“œ ๋ฐ›์€ ๊ฐ•์˜์ž๋ฃŒ์˜ ํด๋”์œ„์น˜๋กœ ์ด๋™ํ•˜์—ฌ ์ž๋ฃŒ ์‹คํ–‰ # **6) PC: Jupyter Lab์œผ๋กœ ๊ฐ•์˜์‹œ์ž‘(์‹ค์Šต๋Œ€์‘): ํ™•์žฅ๊ธฐ๋Šฅ์„ค์น˜๋Š” 1-2)์— ์ด๋ฏธ ํฌํ•จ๋จ** # -> ์ธํ„ฐ๋„ท ์ฃผ์†Œ์ฐฝ์—์„œ http://localhost:8888/lab ํƒ€์ดํ•‘ # -> ์ขŒ์ธก ์ƒ๋‹จ ํด๋”์—์„œ ๋‹ค์šด๋กœ๋“œ ๋ฐ›์€ ๊ฐ•์˜์ž๋ฃŒ์˜ ํด๋”์œ„์น˜๋กœ ์ด๋™ํ•˜์—ฌ ์ž๋ฃŒ ์‹คํ–‰ # # **๋ณ„์ฒจ. ์ด์ƒ ๋ฌด!** # # - ์œ„ ๋‚ด์šฉ๋“ค์ด ์ˆœ์„œ๋Œ€๋กœ ์ง„ํ–‰๋˜์•ผ ํ•˜๋ฉฐ, ์ œ๋Œ€๋กœ ์ง„ํ–‰ํ•˜์…จ๋‹ค๋ฉด ๋ฌธ์ œ ๋ฐœ์ƒ ํ™•๋ฅ  ๋‚ฎ์Œ # - ๋งŒ์•ฝ ์ด์ƒ์ด ์žˆ๋‹ค๋ฉด ๋ชจ๋‘ ์‚ญ์ œ ํ›„ ์ฒ˜์Œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ๋‹ค์‹œ ์ง„ํ–‰ํ•˜์‹œ๊ธธ ๊ถŒ์žฅ
import sys from PyQt5.QtWidgets import QWidget, QApplication, QRadioButton, QLabel, QPushButton, QVBoxLayout class Window(QWidget): def __init__(self): super().__init__() self.init_ui() def init_ui(self): self.infoLabel = QLabel("What is your fav lang?") self.radioButton = QRadioButton("C") self.radioButton2 = QRadioButton("Java") self.radioButton3 = QRadioButton("Python") self.radioButton4 = QRadioButton("MATLAB") self.label = QLabel("") self.button = QPushButton("Click!") v_box = QVBoxLayout() v_box.addWidget(self.radioButton) v_box.addWidget(self.radioButton2) v_box.addWidget(self.radioButton3) v_box.addWidget(self.radioButton4) v_box.addWidget(self.label) v_box.addWidget(self.button) self.setLayout(v_box) self.button.clicked.connect(lambda: self.click(self.radioButton.isChecked(), self.radioButton2.isChecked(), self.radioButton3.isChecked(), self.radioButton4.isChecked(), self.label)) self.setWindowTitle("Checkbox") self.show() def click(self, c, java, python, matlab, label): if c: label.setText("C") if java: label.setText("Java") if python: label.setText("Python") if matlab: label.setText("MATLAB") if __name__ == "__main__": app = QApplication(sys.argv) window = Window() sys.exit(app.exec_())
import dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output app = dash.Dash(__name__) app.layout = html.Div(children=[ html.Div( html.H3('first dash app and you can type something : ') ), html.Div(['type here : ', dcc.Input(id="inputa", type="number"), html.Span(' type here : '), dcc.Input(id="inputb", type="number"), html.Span(' type here : '), dcc.Input(id="inputc", type="number"), html.Hr(), html.H3(id='outpout1')]) ]) @app.callback( Output('outpout1', 'children'), [Input("inputa", "value"), Input("inputb", "value"), Input("inputc", "value")], ) def rewrite (a, b, c): return a, b, c if __name__ == '__main__': app.run_server()
# Generated by Django 2.0 on 2017-12-08 17:03 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contacts', '0003_auto_20160102_1338'), ] operations = [ migrations.AlterModelOptions( name='category', options={'ordering': ['name'], 'verbose_name': 'Category', 'verbose_name_plural': 'Categories'}, ), migrations.AlterModelOptions( name='email', options={'ordering': ['email'], 'verbose_name': 'Email', 'verbose_name_plural': 'Emails'}, ), migrations.AlterModelOptions( name='phone', options={'ordering': ['number'], 'verbose_name': 'Phone', 'verbose_name_plural': 'Phones'}, ), migrations.AlterField( model_name='category', name='name', field=models.CharField(max_length=100, unique=True, verbose_name='Name'), ), migrations.AlterField( model_name='email', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contacts.Category', verbose_name='Category'), ), migrations.AlterField( model_name='email', name='comment', field=models.CharField(blank=True, max_length=255, verbose_name='Additional info'), ), migrations.AlterField( model_name='email', name='email', field=models.EmailField(max_length=254, unique=True, verbose_name='Email'), ), migrations.AlterField( model_name='phone', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contacts.Category', verbose_name='Category'), ), migrations.AlterField( model_name='phone', name='comment', field=models.CharField(blank=True, max_length=255, verbose_name='Additional info'), ), migrations.AlterField( model_name='phone', name='number', field=models.CharField(max_length=20, unique=True, verbose_name='Number'), ), ]
from django import forms from createproject.models import Entry class EntryForm(forms.ModelForm): class Meta: model = Entry
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 14:47:06 2019 @author: Henrik """ def calc(y0,x0,T,N,evaluateModel,calculateTimeStep,euler): dt=T/N y=[] x=[] y.append(y0) x.append(x0) i=1 a=[] while i<N: a=calculateTimeStep(x[i-1],y[i-1],dt,evaluateModel,euler) y.append(a[1]) x.append(a[0]) i+=1 return (x,y)
import tensorflow as tf from taskman_client.task_proxy import get_local_machine_name, assign_tpu_anonymous from trainer_v2.chair_logging import c_log import atexit def device_list_summary(device_list): if not device_list: return "No device found" n_gpu = 0 name_set = set() for dev in device_list: if dev.device_type == 'GPU': if dev.name in name_set: c_log.warn("Duplicated name {}".format(dev.name)) name_set.add(dev.name) n_gpu += 1 if n_gpu == len(device_list): return "{} GPUs found".format(n_gpu) else: return str(device_list) def get_strategy(use_tpu=False, tpu_name=None): if use_tpu: strategy = get_tpu_strategy_inner(tpu_name) else: c_log.debug("use_tpu={}".format(use_tpu)) strategy = tf.distribute.MultiWorkerMirroredStrategy() c_log.info(device_list_summary(tf.config.list_logical_devices('GPU'))) try: atexit.register(strategy._extended._cross_device_ops._pool.close) # type: ignore atexit.register(strategy._extended._host_cross_device_ops._pool.close) # type: ignore except AttributeError: c_log.warning("Skip atexit.register") return strategy def get_strategy2(use_tpu, tpu_name=None, force_use_gpu=False): if use_tpu: strategy = get_tpu_strategy_inner(tpu_name) else: c_log.debug("use_tpu={}".format(use_tpu)) strategy = tf.distribute.MultiWorkerMirroredStrategy() gpu_devices = tf.config.list_logical_devices('GPU') if force_use_gpu and not gpu_devices: raise Exception("GPU devices not found") c_log.info(device_list_summary(gpu_devices)) try: atexit.register(strategy._extended._cross_device_ops._pool.close) # type: ignore atexit.register(strategy._extended._host_cross_device_ops._pool.close) # type: ignore except AttributeError: pass return strategy def get_tpu_strategy_inner(tpu_name): from cloud_tpu_client import Client c_log.debug("get_tpu_strategy:: init TPUClusterResolver") resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=tpu_name) c_log.debug("get_tpu_strategy:: experimental_connect_to_cluster") tf.config.experimental_connect_to_cluster(resolver) c_log.debug("get_tpu_strategy:: initialize_tpu_system") tf.tpu.experimental.initialize_tpu_system(resolver) c_log.debug("get_tpu_strategy:: init TPUStrategy") strategy = tf.distribute.TPUStrategy(resolver) c_log.debug("get_tpu_strategy:: init Client") c = Client(tpu=tpu_name) # c.configure_tpu_version(tf.__version__, restart_type='ifNeeded') return strategy def get_strategy_by_machine_name(): machine_name = get_local_machine_name() if machine_name == "us-1": tpu_name = assign_tpu_anonymous() strategy = get_strategy(True, tpu_name) elif machine_name == "GOSFORD": strategy = get_strategy(False, "") elif machine_name == "ingham.cs.umass.edu": strategy = get_strategy(False, "") else: # It should be tpu v4 strategy = get_strategy(True, "local") return strategy
import mapnik m = mapnik.Map(3500,1500) m.background = mapnik.Color('red') s = mapnik.Style() r = mapnik.Rule() polygon_symbolizer = mapnik.PolygonSymbolizer() polygon_symbolizer.fill = mapnik.Color('#96ff00') r.symbols.append(polygon_symbolizer) line_symbolizer = mapnik.LineSymbolizer() line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('white'), 1) line_symbolizer.stroke_width = 10.0 r.symbols.append(line_symbolizer) s.rules.append(r) m.append_style('My Style',s) ds = mapnik.Shapefile(file="Indonesia_Kab_Kota/Indo_Kab_Kot.shp") layer = mapnik.Layer('indo') layer.datasource = ds layer.styles.append('My Style') m.layers.append(layer) m.zoom_all() mapnik.render_to_file(m, 'indo.pdf', 'pdf') print "rendered image to 'indo.pdf' " #PDF
import json import os from random import randint from locust import HttpLocust from locust import TaskSet from locust import task from locust.web import app from src import report # For reporting app.add_url_rule('/htmlreport', 'htmlreport', report.download_report) # Read json file json_file = os.path.join(os.path.dirname(__file__), 'payloads.json') class SimplePostBehavior(TaskSet): def __init__(self, parent): super(SimplePostBehavior, self).__init__(parent) with open(json_file) as file: self.payloads = json.load(file, 'utf-8') self.length = len(self.payloads) - 1 @task def post_random_payload(self): l_inputJSON = self.payloads[randint(0, self.length)] weight = l_inputJSON.get('weight',1) l_method = l_inputJSON.get('method','GET') l_url = l_inputJSON.get('url','/') l_headers = l_inputJSON.get('headers',None) l_cookies = l_inputJSON.get('cookies',None) #self.client.request("{}".format(l_inputJSON.get('method')), "{}".format(l_inputJSON.get('url')),headers=l_headers,cookies=l_cookies) self.client.request("{}".format(l_method), "{}".format(l_url),headers=l_headers,cookies=l_cookies) class MyLocust(HttpLocust): task_set = SimplePostBehavior min_wait = 0 max_wait = 0
from urllib.request import urlopen, Request from html.parser import HTMLParser import binascii import argparse import re import os # global functions def saveImg(url, name, header): if name == "-1" or url == "-1": print("Not a correct URL or name for an image!") exit() else: print("download image \"", url, "\"") req = Request(url=url, headers=header) with urlopen(req) as response, open(name, 'wb') as out: out.write(response.read()) # overwrite HTMLParser interface class htmlParser(HTMLParser): imgURL = "-1" numSites = "-1" def handle_starttag(self, tag, attrs): if tag == "img": for a in attrs: if a[0] == "src": strImg = re.findall('.*\.(?:jpg|jpeg|png)', a[1]) # there is another png on the site inside a img-tag called 'tasten' # so further check and skip it if re.search('tasten', a[1]): continue if strImg: self.imgURL = strImg[0] if tag == "a": for a in attrs: if a[0] == "href": split = a[1].split("/") # ASCII numbers are in range [48,57] if len(split[-1]) > 0 and len(split[-1]) <= 3: if int(split[-1]) > int(self.numSites): self.numSites = split[-1] # def handle_endtag(self, tag): # print("Encountered an end tag : ", tag) # def handle_data(self, data): # print("Encountered some data : ", data) ''' MAIN ''' # check input args for number of chapter to download argparser = argparse.ArgumentParser(description="download the requested chapter from the One Piece Tube website.") helpStr = "number of chapter(s) to download. At least one number required, at most two. All chapters from first to second number will be downloaded." argparser.add_argument("chapters", type=int, nargs="+", help=helpStr) args = argparser.parse_args() # global variable definitions base = "../out/" chapters = args.chapters # check for ammount of arguments beeing passed if len(chapters) == 1: chapters.append(chapters[0]) for chapter in range(chapters[0], chapters[1]+1): # print status message print("\033[0m\033[1;47;30mdownload chapter ", str(chapter), "from \"http://onepiece-tube.com\"\033[0m") # create folder for chapter chap_dir = base + str(chapter) if not os.path.exists(chap_dir): os.makedirs(chap_dir) i = 1 url = "http://onepiece-tube.com/kapitel/" + str(chapter) + "/" header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/79.0.3945.79 Chrome/79.0.3945.79 Safari/537.36'} while True: # download site from one piece tube webpage req = Request(url=url+str(i), headers=header) contents = urlopen(req).read() # parser html site parser = htmlParser() parser.feed(str(contents)) # download manga image of current site split = parser.imgURL.split("/") terminator = split[-1] imgName = base + str(chapter) + "/" + terminator saveImg(parser.imgURL, imgName, header) # get number of pages of requested chapter pages = int(parser.numSites) # check if all pages are downloaded i += 1 if i > pages: break;
# -*- coding: utf-8 -*- from __future__ import print_function import subprocess from grooveshark import Client client = Client() client.init() #for song in client.favorites("hasantayyar"): # print(song) playlist = client.playlist("32271770") print("This is a huge link of my favorite songs on grooveshark. This list is used for my own needs." ) print("But you may discover some new songs.") print("There is too many types of genres in this list, so I didnt group them by genres." ) print("\n\n") for song in playlist.songs: print("+ **" + unicode(song.artist.name)+ "** - " + unicode(song.name) + " / [" + unicode(song.album.name) + "](http://grooveshark.com/#!/album/a/" + song.album.id +")")
import appuifw, time, os, sys, e32db, key_codes, e32 from time import strftime from string import replace db = e32db.Dbms() dbv = e32db.Db_view() class View( object ): ## The constructor. def __init__(self, dbpath): self.dbpath = dbpath self.old_title = appuifw.app.title self.old_quit = appuifw.app.exit_key_handler self.old_body = appuifw.app.body self.old_menu = appuifw.app.menu appuifw.app.title = u"Config View" db.open(self.dbpath) # self.list_fuel = [] self._initialize_config() def back(self): appuifw.app.body = self.old_body appuifw.app.menu = self.old_menu appuifw.app.exit_key_handler = self.old_quit appuifw.app.title = self.old_title def _initialize_config(self): appuifw.app.menu = [(u"Select", self._select_config), (u"Modify", self.__modify_field), (u"Back", self.back)] self.__create_list() try: self.list_box_config = appuifw.Listbox(map(lambda x:x[1], self.list_config)) except: self.list_empty = [] self.list_empty.append(u"< Empty >") self.list_box_config = appuifw.Listbox(map(lambda x:x, self.list_empty)) self.list_box_config.bind(key_codes.EKeySelect, self._select_config) self.list_box_config.bind(key_codes.EKeyBackspace, self.__delete_field) appuifw.app.body = self.list_box_config appuifw.app.exit_key_handler = self.back def _select_config(self): if len(self.list_config) > 0: id = self.list_box_config.current() self.__get_info(self.list_config[id][0]) self.__show_form(self.info_selection) def __show_form(self, lista): old_title = appuifw.app.title appuifw.app.title = u"ID: %s View Config" % lista[0] self._iFields = [( u"Auto", "text", lista[1]), ( u"Rimborso", "float", lista[2])] ## Mostro il form. self._iForm = appuifw.Form(self._iFields, appuifw.FFormDoubleSpaced+appuifw.FFormViewModeOnly) self._iForm.execute() appuifw.app.title = old_title def __modify_field(self): if len(self.list_config) > 0: id = self.list_config[self.list_box_config.current()][0] #print "primo id %d" %id #self.__get_info(self.list_fuel[id][0]) self.__get_info(id) #self.__get_info_prec(self.list_fuel[id][0]) #self.__show_form_modify(self.info_selection, self.info_selection_prec,id) self.update_modify(self.info_selection) def show_form_modify(self, lista): old_title = appuifw.app.title appuifw.app.title = u"ID: %s Modify Config" % lista[0] self._iFields = [( u"Auto", "text", lista[1]), ( u"Rimborso", "float", lista[2])] ## Mostro il form. self._iIsSaved = False self._iForm = appuifw.Form(self._iFields, appuifw.FFormDoubleSpaced+appuifw.FFormEditModeOnly) self._iForm.save_hook = self._markSaved self._iForm.execute() #appuifw.app.title = old_title ## save_hook send True if the form has been saved. def _markSaved( self, aBool ): self._iIsSaved = aBool ## _iIsSaved getter. def isSaved( self ): return self._iIsSaved def update_modify(self, uno,id): old_title = appuifw.app.title appuifw.app.title = u"Modify Config" self.show_form_modify(uno) if self.isSaved(): # estraggo i dati che mi servono auto = self.getAuto() cilindrata = self.getCilindrata() rimborso = self.getRimborso() #sql_string = u"UPDATE fuel SET (date, priceLiter, euro, paid, who, km, another) VALUES (%d, %f, %f, '%s', '%s', %d, '%s') WHERE id=%d" %( date, priceLiter, euro, paid, who, km, another, int(id) ) sql_string = u"UPDATE config SET auto='%s', cilindrata=%f, rimborso=%f WHERE id=%d" %( auto, cilindrata, rimborso, int(id) ) try: db.execute(sql_string) except: db.open(self.dbpath) db.execute(sql_string) appuifw.note(u"Update", "conf") db.close() appuifw.app.title = old_title ## save_hook send True if the form has been saved. #def _markSaved( self, aBool ): #self._iIsSaved = aBool ## _iIsSaved getter. #def isSaved( self ): #return self._iIsSaved def getAuto(self): # return strftime("%d/%m/%Y", time.localtime(self._iForm[0][2])) return self._iForm[0][2] def getCilindrata(self): return self._iForm[1][2] def getRimborso(self): return self._iForm[2][2] def __get_info(self, id): import globalui sql_string = u"SELECT * FROM config WHERE id=%d" % int(id) #globalui.global_msg_query( sql_string, u"SQL Debug" ) self.info_selection = [] try: dbv.prepare(db, sql_string) except: db.open(self.dbpath) dbv.prepare(db, sql_string) dbv.get_line() for l in range(1, dbv.col_count()+1): try: self.info_selection.append(dbv.col(l)) except Exception, err: globalui.global_msg_query( unicode(err), u"error" ) db.close() del globalui def __delete_field(self): if not len(self.list_config) > 0: return id = self.list_config[self.list_box_config.current()][0] import globalui if globalui.global_query(u"Delete ID: '%s'?" % id): sql_string = u"DELETE FROM config WHERE id=%d" % int(id) try: db.execute(sql_string) except: db.open(self.dbpath) db.execute(sql_string) # db.execute(u"ALTER TABLE fuel AUTO_INCREMENT = 1") appuifw.note(u"Deleted", "conf") db.close() del globalui self._initialize_config() def __create_list(self): self.list_config = [] sql_string = u"SELECT * FROM config" try: dbv.prepare(db, sql_string) except: db.open(self.dbpath) dbv.prepare(db,sql_string) for i in range(1,dbv.count_line()+1): dbv.get_line() result = [] for l in range(1,dbv.col_count()+1): try: result.append(dbv.col(l)) except: result.append(None) # self.list_fuel.append((result[0], unicode(strftime("%d/%m/%Y", time.localtime(result[1]))))) self.list_config.append((result[0], unicode("[%s] %s" % (result[1], result[2]))))#, ("%s", result[1]))))) dbv.next_line() db.close()
from fparser import api def test_reproduce_issue(): source_str = '''\ subroutine bndfp() use m_struc_def C- C C C C C end ''' tree = api.get_reader(source_str, isfree=False, isstrict=False) tree = list(tree) s, u, c, e = tree[:3]+tree[-1:] assert s.span==(1,1),repr(s.span) assert u.span==(2,2),repr(u.span) assert c.span==(3,3),repr(c.span) assert e.span==(9,9),repr(e.span) def test_reproduce_issue_fix77(): source_str = '''\ subroutine foo() real a c c end ''' tree = api.get_reader(source_str, isfree=False, isstrict=True) tree = list(tree) foo, a, comment, end = tree[:3]+tree[-1:] assert foo.span==(1,1) assert a.span==(2,4),repr(a.span) assert comment.span==(5,5),repr(comment.span) assert end.span==(5,5),repr(end.span) def test_reproduce_issue_fix90(): source_str = '''\ subroutine foo() real a c 1 c 2 end ''' tree = api.get_reader(source_str, isfree=False, isstrict=False) tree = list(tree) foo, a, comment,end = tree[:3]+tree[-1:] assert foo.span==(1,1) assert a.span==(2,2),repr(a.span) assert end.span==(5,5),repr(end.span) source_str = '''\ subroutine foo() real a c- c end ''' tree = api.get_reader(source_str, isfree=False, isstrict=False) tree = list(tree) foo, a, comment,end = tree[:3]+tree[-1:] assert foo.span==(1,1) assert a.span==(2,2),repr(a.span) assert end.span==(5,5),repr(end.span) source_str = '''\ subroutine foo() real a c c end ''' tree = api.get_reader(source_str, isfree=False, isstrict=False) tree = list(tree) foo, a, comment, end = tree[:3]+tree[-1:] assert foo.span==(1,1) assert a.span==(2,2),repr(a.span) assert comment.span == (3,3) assert end.span==(5,5),repr(end.span) def test_comment_cont_fix90(): source_str = '''\ subroutine foo() real c 1 & a c 2 end ''' tree = api.get_reader(source_str, isfree=False, isstrict=False) tree = list(tree) foo, a, comment, end = tree[:3]+tree[-1:] assert foo.span==(1,1) assert a.span==(2,4),repr(a.span) assert comment.span==(3,3),repr(comment.span) assert end.span==(6,6) source_str = '''\ subroutine foo() real c & a c 2 end ''' tree = api.get_reader(source_str, isfree=False, isstrict=False) tree = list(tree) foo, a, comment, end = tree[:3]+tree[-1:] assert foo.span==(1,1) assert a.span==(2,4),repr(a.span) assert comment.span==(3,3),repr(comment.span) assert end.span==(6,6) source_str = '''\ subroutine foo() real c 1 & a c end ''' tree = api.get_reader(source_str, isfree=False, isstrict=False) tree = list(tree) foo, a, comment, end = tree[:3]+tree[-1:] assert foo.span==(1,1) assert a.span==(2,4),repr(a.span) assert comment.span==(3,3),repr(comment.span) assert end.span==(6,6) source_str = '''\ subroutine foo() real c 1 & a c 2 &,b end ''' tree = api.get_reader(source_str, isfree=False, isstrict=False) tree = list(tree) foo, ab, comment, end = tree[:3]+tree[-1:] assert foo.span==(1,1) assert ab.span==(2,6),repr(a.span) assert comment.span==(3,3),repr(comment.span) assert end.span==(7,7)
import logging from decimal import Decimal from typing import Iterable, Optional from django.db import models from auction.models.client import Client from auction.models.product import Product from core.errors import CodeError logger = logging.getLogger(__name__) class BidStatus(models.TextChoices): ACTIVE = "active", "ะะบั‚ะธะฒะฝะฐั ัั‚ะฐะฒะบะฐ" DELETED = "deleted", "ะฃะดะฐะปะตะฝะฝะฐั ัั‚ะฐะฒะบะฐ" class Bid(models.Model): """ ะกั‚ะฐะฒะบะธ ะฝะฐ ั‚ะพะฒะฐั€ั‹ """ client = models.ForeignKey( Client, on_delete=models.CASCADE, blank=False, null=False ) product = models.ForeignKey( Product, on_delete=models.CASCADE, blank=False, null=False ) status = models.CharField( choices=BidStatus.choices, default=BidStatus.ACTIVE, max_length=32, ) price = models.DecimalField(max_digits=19, decimal_places=2) cdate = models.DateTimeField(auto_now=False, auto_now_add=True) mdate = models.DateTimeField(auto_now=True, auto_now_add=False) class Meta: indexes = [models.Index(fields=["price"])] def __str__(self) -> str: return f"{self.product.name}: {self.price}" @classmethod def is_possible_to_place_bid(cls, product: Product, price: Decimal) -> bool: """ ะŸั€ะพะฒะตั€ะบะธ ะฒะพะทะผะพะถะฝะพัั‚ะธ ัƒัั‚ะฐะฝะพะฒะบะธ ัั‚ะฐะฒะบะธ ะฟะตั€ะตะด ัะพั…ั€ะฐะฝะตะฝะธะตะผ """ where = models.Q(product=product, price__gte=price) bid = cls.objects.filter(where).first() return bid is None def clean(self) -> None: super().clean() if not Bid.is_possible_to_place_bid( product=self.product, price=self.price ): raise CodeError.ALREADY_HAS_HIGHER_BID.exception def save( self, force_insert: bool = False, force_update: bool = False, using: Optional[str] = None, update_fields: Optional[Iterable[str]] = None, ) -> None: """ ะฟั€ะพะฒะตั€ะบะธ ะฟะตั€ะตะด ัะพั…ั€ะฐะฝะตะฝะธะตะผ ัั‚ะฐะฒะบะธ """ self.full_clean() return super().save(force_insert, force_update, using, update_fields) def post_save(self) -> None: """ ะฑัƒะดะตะผ ะฒั‹ะทั‹ะฒะฐั‚ัŒ ะธะท ั…ะตะปะฟะตั€ะฐ ะพั‚ะดะตะปัŒะฝะพ """ try: self.product.bid_posthook() except Exception as e: logger.warning(f"failed posthook: {e}")
import unittest from BowlingGame import BowlingGame class BowlingGameTest(unittest.TestCase): def setUp(self): self.game = BowlingGame() def rollMany(self, pins, times): for i in xrange(0, times): self.game.roll(pins) def rollSpare(self): self.game.roll(5) self.game.roll(5) def rollStrike(self): self.game.roll(10) def test_worstGame(self): self.rollMany(0, 20) self.assertEqual(0, self.game.get_score()) def test_onePin(self): self.rollMany(1, 20) self.assertEqual(20, self.game.get_score()) def test_spare(self): self.rollSpare() self.game.roll(2) self.rollMany(0, 17) self.assertEqual(14, self.game.get_score()) def test_strike(self): self.rollStrike() self.game.roll(3) self.game.roll(4) self.rollMany(0, 17) self.assertEqual(24, self.game.get_score()) def test_double_strike(self): self.rollStrike() self.rollStrike() self.game.roll(4) self.game.roll(2) self.rollMany(0, 16) self.assertEqual(46, self.game.get_score()) def test_perfect_game(self): self.rollMany(10, 12) self.assertEqual(300, self.game.get_score()) if __name__ == '__main__': unittest.main()
def file_reader_1(): # pythonๅœจๅฝ“ๅ‰ๆ‰ง่กŒ็š„ๆ–‡ไปถๆ‰€ๅœจ็š„็›ฎๅฝ•ไธญๆŸฅๆ‰พๆŒ‡ๅฎš็š„ๆ–‡ไปถ with open('test.txt', encoding='utf-8') as file_obj: contents = file_obj.read() print(contents.rstrip()) # rstrip()ๅˆ ้™คๅญ—็ฌฆไธฒๆœซๅฐพ็š„็ฉบ็™ฝ def file_reader_2(): filename = r'test.txt' with open(filename, encoding='utf-8') as file_obj: for line in file_obj: # ๆ–‡ไปถไธญๆฏ่กŒ็š„ๆœซๅฐพ้ƒฝๆœ‰ไธ€ไธช็œ‹ไธ่ง็š„ๆข่กŒ็ฌฆ, ่€Œprint่ฏญๅฅไนŸไผšๅŠ ไธŠไธ€ไธชๆข่กŒ็ฌฆ print(line.rstrip()) def file_readlines_1(): filename = r'test.txt' with open(filename, encoding='utf-8') as file_obj: lines = file_obj.readlines() for line in lines: print(line.rstrip()) def file_read_to_string(): """ๅฐ†ๆ–‡ไปถไฟๅญ˜ๅˆฐๅญ—็ฌฆไธฒไธญ""" filename = 'test.txt' with open(filename, encoding='utf-8') as file_obj: lines = file_obj.readlines() txt_string = '' for line in lines: txt_string += line.rstrip() print(txt_string) print(len(txt_string)) if __name__ == '__main__': # file_readlines_1() file_read_to_string()
#https://www.programiz.com/python-programming/decorator #https://realpython.com/blog/python/primer-on-python-decorators/ #http://www.bogotobogo.com/python/python_decorators.php """ Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. def myFunction(in_function): def out_function(): pass return out_function The myFunction is indeed a decorator because by definition a decorator is a function that takes a function object as its argument, and returns a function object. """ def my_decorator(some_function): def wrapper(): num = 10 if num == 10: print("Yes!") else: print("No!") some_function() print("Something is happening after some_function() is called.") return wrapper def just_some_function(): print("Wheee!") """ just_some_function = my_decorator(just_some_function) just_some_function() """ @my_decorator def just_some_function(): print("Wheee!") just_some_function()
from django.urls import path, re_path from django.conf.urls import url from . import views urlpatterns = [ path('', views.home, name='home'), re_path(r'^search/$', views.search_list, name='search_list'), re_path(r'^search/(?P<string>.+)/$', views.download, name='details'), re_path(r'^download/(?P<string>.+)/$', views.download, name='download') ]
# coding: utf-8 from typing import Optional, Union from urllib.parse import urlparse, parse_qs from django.conf import settings from django.contrib.auth.models import User from django.core.signing import Signer from django.db import models from django.utils import timezone class OneTimeAuthToken(models.Model): HEADER = 'X-KOBOCAT-OTA-TOKEN' user = models.ForeignKey( User, related_name='authenticated_requests', on_delete=models.CASCADE ) token = models.CharField(max_length=50) expiration_time = models.DateTimeField() method = models.CharField(max_length=6) class Meta: unique_together = ('user', 'token', 'method') @classmethod def grant_access( cls, request: 'rest_framework.request.Request', use_referrer: bool = False, instance: Optional['onadata.apps.logger.models.Instance'] = None, ): token = cls.is_signed_request(request, use_referrer, instance) if token is None: # No token is detected, the authentication should be # delegated to other mechanisms present in permission classes return None user = request.user try: auth_token = cls.objects.get( user=user, token=token, method=request.method ) except OneTimeAuthToken.DoesNotExist: return False granted = timezone.now() <= auth_token.expiration_time # void token auth_token.delete() # clean-up expired or already used tokens OneTimeAuthToken.objects.filter( expiration_time__lt=timezone.now(), user=user, ).delete() return granted @classmethod def is_signed_request( cls, request: 'rest_framework.request.Request', use_referrer: bool = False, instance: Optional['onadata.apps.logger.models.Instance'] = None, ) -> Union[str, None]: """ Search for a OneTimeAuthToken in the request headers. If there is a match, it is returned. Otherwise, it returns `None`. If `use_referrer` is `True`, the comparison is also made on the HTTP referrer, and `instance` must be provided. The referrer must include an `instance_id` query parameter that matches `instance.uuid`. """ try: token = request.headers[cls.HEADER] except KeyError: if not use_referrer: return None else: return token if use_referrer and not instance: raise TypeError( # I win!!! '`instance` must be provided when `use_referrer = True`' ) try: referrer = request.META['HTTP_REFERER'] except KeyError: return None else: # There is no reason that the referrer could be something else # than Enketo Express edit URL. edit_url = f'{settings.ENKETO_URL}/edit' if not referrer.startswith(edit_url): return None # When using partial permissions, deny access if the UUID in the # referrer URL does not match the UUID of the submission being # edited referrer_qs = parse_qs(urlparse(referrer).query) try: referrer_uuid = referrer_qs['instance_id'][0] except (IndexError, KeyError): return None else: if referrer_uuid != instance.uuid: return None parts = Signer().sign(referrer).split(':') return parts[-1]
# Standard library imports import json import logging # Third party imports from django.contrib import messages from django.contrib.auth.decorators import user_passes_test from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.contrib.admin.utils import NestedObjects from django.db import DEFAULT_DB_ALIAS # Local application/library imports from dojo.models import Rule,\ System_Settings, Finding, Test, Test_Type, Engagement, \ Product, Product_Type, Child_Rule from dojo.forms import RuleFormSet, DeleteRuleForm, RuleForm from dojo.utils import add_breadcrumb logger = logging.getLogger(__name__) # Fields for each model ruleset finding_fields = [f.name for f in Finding._meta.fields] test_fields = [f.name for f in Test._meta.fields] test_type_fields = [f.name for f in Test_Type._meta.fields] engagement_fields = [f.name for f in Engagement._meta.fields] product_fields = [f.name for f in Product._meta.fields] product_type_fields = [f.name for f in Product_Type._meta.fields] field_dictionary = {} field_dictionary['Finding'] = finding_fields field_dictionary['Test Type'] = test_type_fields field_dictionary['Test'] = test_fields field_dictionary['Engagement'] = engagement_fields field_dictionary['Product'] = product_fields field_dictionary['Product Type'] = product_type_fields def rules(request): initial_queryset = Rule.objects.all().order_by('name') add_breadcrumb(title="Rules", top_level=True, request=request) return render(request, 'dojo/rules.html', { 'name': 'Rules List', 'metric': False, 'user': request.user, 'rules': initial_queryset}) def new_rule(request): if request.method == 'POST': form = RuleForm(request.POST) if form.is_valid(): rule = form.save() messages.add_message(request, messages.SUCCESS, 'Rule created successfully.', extra_tags='alert-success') if "_Add Child" in request.POST: return HttpResponseRedirect(reverse('Add Child', args=(rule.id,))) return HttpResponseRedirect(reverse('rules')) form = RuleForm() add_breadcrumb(title="New Dojo Rule", top_level=False, request=request) return render(request, 'dojo/new_rule2.html', {'form': form, 'finding_fields': finding_fields, 'test_fields': test_fields, 'engagement_fields': engagement_fields, 'product_fields': product_fields, 'product_type_fields': product_type_fields, 'field_dictionary': json.dumps(field_dictionary)}) @user_passes_test(lambda u: u.is_staff) def add_child(request, pid): rule = get_object_or_404(Rule, pk=pid) if request.method == 'POST': forms = RuleFormSet(request.POST) for form in forms: if form.is_valid(): cr = form.save(commit=False) cr.parent_rule = rule cr.save() messages.add_message(request, messages.SUCCESS, 'Rule created successfully.', extra_tags='alert-success') return HttpResponseRedirect(reverse('rules')) form = RuleFormSet(queryset=Child_Rule.objects.filter(parent_rule=rule)) add_breadcrumb(title="New Dojo Rule", top_level=False, request=request) return render(request, 'dojo/new_rule.html', {'form': form, 'pid': pid, 'finding_fields': finding_fields, 'test_fields': test_fields, 'engagement_fields': engagement_fields, 'product_fields': product_fields, 'product_type_fields': product_type_fields, 'field_dictionary': json.dumps(field_dictionary)}) @user_passes_test(lambda u: u.is_staff) def edit_rule(request, pid): pt = get_object_or_404(Rule, pk=pid) children = Rule.objects.filter(parent_rule=pt) all_rules = children | Rule.objects.filter(pk=pid) form = RuleForm(instance=pt) if request.method == 'POST': form = RuleForm(request.POST, instance=pt) if form.is_valid(): pt = form.save() messages.add_message(request, messages.SUCCESS, 'Rule updated successfully.', extra_tags='alert-success') if "_Add Child" in request.POST: return HttpResponseRedirect(reverse('Add Child', args=(pt.id,))) return HttpResponseRedirect(reverse('rules')) add_breadcrumb(title="Edit Rule", top_level=False, request=request) return render(request, 'dojo/edit_rule.html', { 'name': 'Edit Rule', 'metric': False, 'user': request.user, 'form': form, 'field_dictionary': json.dumps(field_dictionary), 'pt': pt, }) @user_passes_test(lambda u: u.is_staff) def delete_rule(request, tid): rule = get_object_or_404(Rule, pk=tid) form = DeleteRuleForm(instance=rule) if request.method == 'POST': # print('id' in request.POST, file=sys.stderr) # print(str(rule.id) == request.POST['id'], file=sys.stderr) # print(str(rule.id) == request.POST['id'], file=sys.stderr) # if 'id' in request.POST and str(rule.id) == request.POST['id']: form = DeleteRuleForm(request.POST, instance=rule) # print(form.is_valid(), file=sys.stderr) # print(form.errors, file=sys.stderr) # print(form.non_field_errors(), file=sys.stderr) # print('id' in request.POST, file=sys.stderr) if form.is_valid(): rule.delete() messages.add_message(request, messages.SUCCESS, 'Rule deleted.', extra_tags='alert-success') return HttpResponseRedirect(reverse('rules')) collector = NestedObjects(using=DEFAULT_DB_ALIAS) collector.collect([rule]) rels = collector.nested() add_breadcrumb(parent=rule, title="Delete", top_level=False, request=request) system_settings = System_Settings.objects.get() return render(request, 'dojo/delete_rule.html', {'rule': rule, 'form': form, 'active_tab': 'findings', 'system_settings': system_settings, 'rels': rels, })
# -*- coding: utf-8 -*- ''' Created on Feb 6, 2013 @author: Hugo ''' import xlrd, xlwt from xlutils.copy import copy import os from decimal import Decimal #xlrd.Book.encoding = "gbk" location = './/Data/' location_ws = './/Data2/' stand_cells_conf = './conf/standcells.conf' cell_cells_conf = './conf/cell_cells.conf' ws_cells_conf = './conf/ws_cells.conf' cell_custom_conf = './conf/cell_customquery.conf' ws_custom_conf = './conf/ws_customquery.conf' years = [] years_ws = [] dep_list = os.listdir(location) #print dep_list for year in os.listdir(location + '\\' + dep_list[0]): years.append(year[0:-4]) dep_list_ws = os.listdir(location_ws) for year in os.listdir(location + '\\' + dep_list[0]): years_ws.append(year[0:-4]) # Create a font to use with the style style = xlwt.XFStyle() font0 = xlwt.Font() font0.name = u'ๅพฎ่ฝฏ้›…้ป‘' font0.colour_index = 0 font0.bold = True pattern = xlwt.Pattern() # Create the Pattern pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12 pattern.pattern_fore_colour = 2 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on... style.pattern = pattern # Add Pattern to Style style.font = font0 #Init Standard Query report if os.path.exists('./report/Stand_report.xls'): os.remove('./report/Stand_report.xls') worksheet_stand_report = xlwt.Workbook(encoding='gbk') worksheet_stand_report.add_sheet(u'็ฌฌไธ€่กจ', cell_overwrite_ok=True) report_table = worksheet_stand_report.get_sheet(0) report_table.write(1, 0, u'็ฌฌไธ€่กจ') report_table.write(3, 0, u'ๅ•ไฝ') worksheet_stand_report.save('./report/Stand_report.xls') #Init Custom Query Report if os.path.exists('./report/Cell_Custom_report.xls'): os.remove('./report/Cell_Custom_report.xls') cell_custom_report = xlwt.Workbook(encoding='gbk') cell_custom_report.add_sheet(u'้ป˜่ฎค่กจ', cell_overwrite_ok=True) cell_custom_report.save('./report/Cell_Custom_report.xls') #if os.path.exists('./report/WS_Custom_report.xls'): # os.remove('./report/WS_Custom_report.xls') #ws_custom_report = xlwt.Workbook(encoding='gbk') #ws_custom_report.add_sheet(u'้ป˜่ฎค่กจ', cell_overwrite_ok=True) #ws_custom_report.save('./report/WS_Custom_report.xls') #Init index of cells.conf def index_init(filename): index = {} f = file(filename, 'r') #t = len(f.readlines()) i = 0 #f.readline(100) first = f.readline().split('.') index[first[0].decode('gbk')] = 0 while True: record = f.readline() # print record if len(record) == 0: break else: if index.has_key(record.split('.')[0].decode('gbk')): # print i, 'same', record.decode('gbk') i += 1 else: # print i, 'diff', record.decode('gbk') index[record.split('.')[0].decode('gbk')] = i + 1 i += 1 f.close return index #Get_customquery cells def get_customrecords(xy): # a = 'ๆต‹่ฏ•:2011.็ฌฌไธ€่กจ.A1+2012.็ฌฌไบŒ่กจ.A2-2011.็ฌฌไบŒ่กจ.A3+2011.็ฌฌไบŒ่กจ.A4-2011.็ฌฌไบŒ่กจ.A5-2011.็ฌฌไบŒ่กจ.A6+2011.็ฌฌไบŒ่กจ.A7' # print xy record = xy.split(':') record_xy = [record[0]] cell = record[1].split('+') for a in cell: # print a if a.find('-') != -1: # print 'find' i = 0 for b in a.split('-'): record_xy.append(b) if i != len(a.split('-')) - 1: record_xy.append('-') else: record_xy.append('+') i += 1 else: # print 'no found' record_xy.append(a) record_xy.append('+') # for i in record_xy[0:-1]: # print 'dsa=', i return record_xy[0:-1] #Get cells physical location of Excel. def get_standcell_xy(xy): # try: result = [] record = xy.split('=') query_id = record[0].split('.')[1] query_name = record[3] #print phyical location of record for lens in range(1, len(record) - 1): table_cell = record[lens].split('->') cell = table_cell[1].split(':') if len(cell[0]) <= 1: cell_x = ord(cell[0]) - 65 else: cell_x = ord(cell[0][-1]) + 26 - 65 cell_y = cell[1] result.append(xy.split('.')[0]) result.append(int(table_cell[0]) - 1) result.append(int(cell_x)) result.append(int(cell_y) - 1) result.append(query_id) result.append(query_name) # print 'aaaa', result return result # except: # print 'Get cells xy failed' def get_allcells_xy(xy): # try: result = [] record = xy.split('=') query_name = record[0].split('.')[0] #print phyical location of record for lens in range(1, len(record)): table_cell = record[lens].split('->') cell = table_cell[1].split(':') # cell_x = ord(cell[0]) - 65 if len(cell[0]) <= 1: cell_x = ord(cell[0]) - 65 else: cell_x = ord(cell[0][-1]) + 26 - 65 # print cell_x cell_y = cell[1] # print cell, cell_x, cell_y, int(table_cell[0]) - 1 result.append(query_name) result.append(int(table_cell[0]) - 1) result.append(int(cell_x)) result.append(int(cell_y) - 1) # print result return result # except: # print 'Get cells xy failed' def get_customcells_xy(xy): # try: result = [] record = xy.split('=') query_name = record[0].split('.')[0] #print phyical location of record for lens in range(1, len(record)): table_cell = record[lens].split('->') cell = table_cell[1].split(':') # cell_x = ord(cell[0]) - 65 if len(cell[0]) <= 1: cell_x = ord(cell[0]) - 65 else: cell_x = ord(cell[0][-1]) + 26 - 65 cell_y = cell[1] # print cell, cell_x, cell_y, int(table_cell[0]) - 1 result.append(query_name) result.append(int(table_cell[0]) - 1) result.append(int(cell_x)) result.append(int(cell_y) - 1) # print result return result # except: # print 'Get cells xy failed' #Load standard query configure from standcells.conf def StandQuery(*query_content): # Create a font to use with the style font0 = xlwt.Font() font0.name = u'ๅพฎ่ฝฏ้›…้ป‘' font0.colour_index = 2 font0.bold = True style = xlwt.XFStyle() style.font = font0 for name_id in (query_content): f = file(stand_cells_conf, 'r') length = 0 while True: line = f.readline() if len(line) == 0: break if line.decode('gbk').split('=')[0].startswith(name_id) != 1: # print 'diff' pass else: # print 'same' record = get_standcell_xy(line.decode('gbk')) # print record dep_list = os.listdir(location) length += 4 # print length #Write data into report.xls # try: report_xls = xlrd.open_workbook('./report/Stand_report.xls') for k in range(0, len(report_xls.sheet_names())): # print k, len(report_xls.sheet_names()) # print record[0], report_xls.sheet_names()[k].decode('utf-8') if record[0] == report_xls.sheet_names()[k] : table = report_xls.sheet_by_name(record[0]) for i in range(0, len(dep_list)): data_source_before = location + dep_list[i] + '\\' + years[0] + '.xls' data_source_after = location + dep_list[i] + '\\' + years[1] + '.xls' worksheet_before = xlrd.open_workbook(data_source_before) worksheet_after = xlrd.open_workbook(data_source_after) table_before = worksheet_before.sheet_by_index(int(record[1])) table_after = worksheet_after.sheet_by_index(int(record[5])) a = table_before.cell(record[3], record[2]).value b = table_after.cell(record[7], record[6]).value if a == '': a = a.replace('', '0') if b == '': b = b.replace('', '0') report_table = worksheet_stand_report.get_sheet(k) #Deal with ncols >250 if length <= 16: length_y = table.ncols report_table.write(2 , 0 + length_y , record[8] + '-' + record[9]) report_table.write(3 , 0 + length_y , years[0]) report_table.write(3 , 1 + length_y , years[1]) report_table.write(3 , 2 + length_y , u'ๅˆ่ฎก', style) report_table.write(4 + i , 0, dep_list[i]) report_table.write(4 + i , 0 + length_y, int(a)) report_table.write(4 + i , 1 + length_y, int(b)) report_table.write(4 + i , 2 + length_y, int(b) - int(a)) report_table.write(4 + i , 3 + length_y, ' ') worksheet_stand_report.save('./report/Stand_report.xls') # print length, 'oooo' elif length % 16 > 0: length_x = (length / 16) * (len(dep_list) + 3) length_y = length % 16 - 3 # print length, length_x, length_y report_table.write(2 + length_x, 0 + length_y, record[8] + '-' + record[9]) report_table.write(3 + length_x, 0 + length_y, years[0]) report_table.write(3 + length_x, 1 + length_y, years[1]) report_table.write(3 + length_x, 2 + length_y, u'ๅˆ่ฎก', style) report_table.write(4 + i + length_x , 0, dep_list[i]) report_table.write(4 + i + length_x, 0 + length_y, int(a)) report_table.write(4 + i + length_x, 1 + length_y, int(b)) report_table.write(4 + i + length_x, 2 + length_y, int(b) - int(a)) report_table.write(4 + i + length_x, 3 + length_y, ' ') worksheet_stand_report.save('./report/Stand_report.xls') else: # print 'end of line' length_x = (length / 16 - 1) * (len(dep_list) + 3) length_y = 16 - 3 # print length, length_x, length_y report_table.write(2 + length_x, 0 + length_y, record[8] + '-' + record[9]) report_table.write(3 + length_x, 0 + length_y, years[0]) report_table.write(3 + length_x, 1 + length_y, years[1]) report_table.write(3 + length_x, 2 + length_y, u'ๅˆ่ฎก', style) report_table.write(4 + i + length_x , 0, dep_list[i]) report_table.write(4 + i + length_x, 0 + length_y, int(a)) report_table.write(4 + i + length_x, 1 + length_y, int(b)) report_table.write(4 + i + length_x, 2 + length_y, int(b) - int(a)) report_table.write(4 + i + length_x, 3 + length_y, ' ') worksheet_stand_report.save('./report/Stand_report.xls') break elif k == int(len(report_xls.sheet_names()) - 1): worksheet_stand_report.add_sheet(record[0], cell_overwrite_ok=True) report_table = worksheet_stand_report.get_sheet(k + 1) report_table.write(2 , 1 , record[8] + '-' + record[9]) report_table.write(1, 0, record[0]) report_table.write(3, 0, u'ๅ•ไฝ') report_table.write(3, 1, years[0]) report_table.write(3, 2, years[1]) report_table.write(3, 3, u'ๅˆ่ฎก', style) for i in range(0, len(dep_list)): data_source_before = location + dep_list[i] + '\\' + years[0] + '.xls' data_source_after = location + dep_list[i] + '\\' + years[1] + '.xls' worksheet_before = xlrd.open_workbook(data_source_before) worksheet_after = xlrd.open_workbook(data_source_after) table_before = worksheet_before.sheet_by_index(int(record[1])) table_after = worksheet_after.sheet_by_index(int(record[5])) a = table_before.cell(record[3], record[2]).value b = table_after.cell(record[7], record[6]).value if a == '': a = a.replace('', '0') if b == '': b = b.replace('', '0') report_table = worksheet_stand_report.get_sheet(k + 1) report_table.write(4 + i , 1 , int(a)) report_table.write(4 + i , 2 , int(b)) report_table.write(4 + i , 3 , int(b) - int(a)) report_table.write(4 + i , 4 , ' ') report_table.write(4 + i, 0, dep_list[i]) worksheet_stand_report.save('./report/Stand_report.xls') # except: # print 'Some error occurred' worksheet_stand_report.save('./report/Stand_report.xls') f.close() # except: # print 'Stand Query failed' #Define Custom Query Model def CellCustomQuery(query_content): # Create a font to use with the style font0 = xlwt.Font() font0.name = u'ๅพฎ่ฝฏ้›…้ป‘' font0.colour_index = 2 font0.bold = True style = xlwt.XFStyle() style.font = font0 record_name = get_customrecords(query_content)[0] record_custom = get_customrecords(query_content)[1:] # print record_name, record_custom table_exist = 0 custom_report = xlrd.open_workbook('./report/Cell_Custom_report.xls', formatting_info=True) for table_exist in range(0, len(custom_report.sheet_names())): # print table_exist, record_name, custom_report.sheet_names()[table_exist] if custom_report.sheet_names()[table_exist] == record_name: write_custom(record_custom, table_exist) break elif table_exist == len(custom_report.sheet_names()) - 1: cell_custom_report.add_sheet(record_name, cell_overwrite_ok=True) cell_custom_report.save('./report/Cell_Custom_report.xls') write_custom(record_custom, len(custom_report.sheet_names())) break # table_exist += 1 # def WSCustomQuery(v, xy, year, threshold): index = index_init(ws_cells_conf) record_custom = get_customrecords(xy)[1:] # print record_custom.deco record_name = get_customrecords(xy)[0] # print record_name.decode('utf-8') for i in range(0, len(dep_list_ws)): datasource = location_ws + dep_list_ws[i].decode('gbk') + '//' + year + '.xls' if i == 0: # print dep_list_ws[i].decode('gbk') ws_report_xls = xlrd.open_workbook(datasource, formatting_info=True) ws_custom_xls = copy(ws_report_xls) else: ws_report_xls = xlrd.open_workbook('./report/' + dep_list_ws[i].decode('gbk') + '_' + record_name + '_WS_custom_report.xls', formatting_info=True) ws_custom_xls = copy(ws_report_xls) for j in range(0, len(record_custom), 2): # print j f = file(ws_cells_conf, 'r') # print index[record_custom[j]] # print index[ record_custom[len(record_custom) - 1]] for line in f.readlines()[index[record_custom[j]]:]: f1 = file(ws_cells_conf, 'r') for k in f1.readlines()[index[ record_custom[len(record_custom) - 1]]:]: # print record_custom[len(record_custom) - 1] + '.' + line.split('=')[0].split('.')[1] if k.decode('gbk').startswith(record_custom[len(record_custom) - 1] + '.' + line.split('=')[0].split('.')[1]): record_result = get_allcells_xy(k) # print k.decode('gbk'), record_result break else: continue f1.close() if len(line) == 0: break if line.decode('gbk').split('=')[0].startswith(record_custom[j]) != 1: # print 'diff' break else: # print 'same' record = get_allcells_xy(line) # print record_custom[j], record ws_worksheet = xlrd.open_workbook(datasource) table = ws_worksheet.sheet_by_index(record[1] + 1) b = table.cell(record[3], record[2]).value if b == '': b = b.replace('', '0') elif b == '-': b = b.replace('-', '0') # print b ws_report_table = ws_custom_xls.get_sheet(len(ws_worksheet.sheet_names()) - 1) # ws_report_table.get if j == 0: result = int(b) ws_report_table.write(record_result[3], record_result[2], result) ws_custom_xls.save('./report/' + dep_list_ws[i].decode('gbk') + '_' + record_name + '_WS_custom_report.xls') elif j < len(record_custom) : ws_result = xlrd.open_workbook('./report/' + dep_list_ws[i].decode('gbk') + '_' + record_name + '_WS_custom_report.xls') table_result = ws_result.sheet_by_index(len(ws_result.sheet_names()) - 1) c = table_result.cell(record_result[3], record_result[2]).value # print 'b-c:' , b, c if c == '': c = c.replace('', '0') elif b == '-': c = c.replace('-', '0') if record_custom[j - 1] == '+': result = int(b) + int(c) else: result = int(c) - int(b) if result > threshold: ws_report_table.write(record_result[3], record_result[2], result, style) ws_custom_xls.save('./report/' + dep_list_ws[i].decode('gbk') + '_' + record_name + '_WS_custom_report.xls') else: ws_report_table.write(record_result[3], record_result[2], result) ws_custom_xls.save('./report/' + dep_list_ws[i].decode('gbk') + '_' + record_name + '_WS_custom_report.xls') # ws_custom_xls.save('./report/' + dep_list_ws[i].decode('gbk') + '_WS_custom_report.xls') def write_custom(record_custom, table_index): report_table_custom = cell_custom_report.get_sheet(table_index) report_table_custom.write(1, 1 + len(record_custom) / 2 + 1, u'ๅˆ่ฎก') # print record_custom for k in range(0, len(dep_list)): # print k result = 0 report_table_custom.write(2 + k, 0, dep_list[k]) for i in range(0, len(record_custom) + 1, 2): # print i f = file(cell_cells_conf, 'r') while True: line = f.readline() if len(line) == 0: break # print line.decode('gbk').split(':')[0], record_custom[i][5:].replace('\n', '') + '=' if line.decode('gbk').split(':')[0].startswith(record_custom[i][5:].replace('\n', '') + '=') != 1: # print 'diff' pass else: # print 'same' record = get_customcells_xy(line.decode('gbk')) # print record data_source = location + dep_list[k].decode('gbk') + '\\' + record_custom[i][0:4] + '.xls' worksheet_custom = xlrd.open_workbook(data_source) table_after = worksheet_custom.sheet_by_index(record[1]) b = table_after.cell(record[3], record[2]).value # print b report_table_custom.write(1, 1 + i / 2, record_custom[i]) report_table_custom.write(2 + k, 1 + i / 2, b) cell_custom_report.save('./report/Cell_Custom_report.xls') if b == '': b = b.replace('', '0') # print i if i == 0: result = b # print b, result elif i < len(record_custom) : if record_custom[i - 1] == '+': result += int(b) else: result -= int(b) # print b, record_custom[i - 1], result report_table_custom.write(2 + k, 1 + len(record_custom) / 2 + 1, result) cell_custom_report.save('./report/Cell_Custom_report.xls') break f.close() # break cell_custom_report.save('./report/Cell_Custom_report.xls') def PercentQuery(v, check_percent, xy): index = index_init(cell_cells_conf) for i in range(0, len(dep_list)): t = 0 # print location + dep_list[i].decode('gbk') + '\\' + years[0] + '.xls' data_source_before = location + dep_list[i] + '//' + years[0] + '.xls' data_source_after = location + dep_list[i] + '//' + years[1] + '.xls' if v == 0: report_xls = xlrd.open_workbook(data_source_after, formatting_info=True) per_report_xls = copy(report_xls) else: report_xls = xlrd.open_workbook('./report/' + dep_list[i] + '_Percent_report.xls', formatting_info=True) per_report_xls = copy(report_xls) worksheet_before = xlrd.open_workbook(data_source_before) worksheet_after = xlrd.open_workbook(data_source_after) f = file(cell_cells_conf, 'r') # while False: for line in f.readlines()[index[xy]:]: # print t # line = f.readline() if len(line) == 0: break # print line.decode('gbk').split('=')[0], xy if line.decode('gbk').split('=')[0].startswith(xy) != 1: # print 'diff' break else: # print 'same' record = get_allcells_xy(line) # print record table_before = worksheet_before.sheet_by_index(int(record[1])) table_after = worksheet_after.sheet_by_index(int(record[1])) a = table_before.cell(record[3], record[2]).value b = table_after.cell(record[3], record[2]).value # print a, b if a == '': a = a.replace('', '0') elif a == '-': a = a.replace('-', '0') if b == '': b = b.replace('', '0') elif b == '-': b = b.replace('-', '0') # print a, b, int(b) - int(a) report_table = per_report_xls.get_sheet(record[1]) if int(a) == 0: if int(b) != 0: report_table.write(record[3], record[2], 100, style) per_report_xls.save('./report/' + dep_list[i] + '_Percent_report.xls') else: report_table.write(record[3], record[2], 0) per_report_xls.save('./report/' + dep_list[i] + '_Percent_report.xls') elif (int(b) - int(a)) > 0: b_big_a = round(Decimal(int(b) - int(a)) / Decimal(a) * 100, 2) if b_big_a >= check_percent: report_table.write(record[3], record[2], b_big_a, style) per_report_xls.save('./report/' + dep_list[i] + '_Percent_report.xls') else: report_table.write(record[3], record[2], b_big_a) per_report_xls.save('./report/' + dep_list[i] + '_Percent_report.xls') elif (int(b) - int(a)) < 0: a_big_b = round(Decimal(int(a) - int(b)) / Decimal(a) * 100, 2) if a_big_b >= check_percent: report_table.write(record[3], record[2], -1 * a_big_b, style) per_report_xls.save('./report/' + dep_list[i] + '_Percent_report.xls') else: report_table.write(record[3], record[2], -1 * a_big_b) per_report_xls.save('./report/' + dep_list[i] + '_Percent_report.xls') else: report_table.write(record[3], record[2], 0) per_report_xls.save('./report/' + dep_list[i] + '_Percent_report.xls') t += 1 f.close() #End
import yaml import os import json import codecs def test_read_data_from_json_yaml(data_file): return_value = [] data_file_path = os.path.abspath(data_file) print(data_file_path) _is_yaml_file = data_file_path.endswith((".yml", ".yaml")) with codecs.open(data_file_path, 'r', 'utf-8') as f: # ไปŽYAMLๆˆ–JSONๆ–‡ไปถไธญๅŠ ่ฝฝๆ•ฐๆฎ if _is_yaml_file: data = yaml.safe_load(f) else: data = json.load(f) for i, elem in enumerate(data): if isinstance(data, dict): key, value = elem, data[elem] if isinstance(value, dict): case_data = [] for v in value.values(): case_data.append(v) return_value.append(tuple(case_data)) else: return_value.append((value,)) return return_value
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 17 12:20:57 2021 @author: hernando """ import numpy as np import clouds.dclouds as dclouds def mcimg(img, mccoors, mcenes, steps = None, x0 = None): bins = dclouds._bins(img, steps, x0) mcimg, _ = np.histogramdd(mccoors, bins, weights = mcenes) return mcimg def mcblobs(img, mccoors, mcenes, mcids, steps = None, x0 = None): bins = dclouds._bins(img, steps, x0) mcblob = np.zeros(img.shape).flatten() for i in (1, 2): sel = mcids == i if (np.sum(sel) <= 0): continue icoors = dclouds.cells_selection(mccoors, sel) etrk, _ = np.histogramdd(icoors, bins, weights = mcenes[sel]) imask = np.argmax(etrk) mcblob[imask] = etrk.flatten()[imask] #print(etrk.flatten()[imask]) #print(mcblob.flatten()[imask]) return mcblob.reshape(img.shape)
import numpy as np A250000 = (0, 0, 1, 2, 4, 5, 7, 9, 12, 14, 17, 21, 24, 28, 32) def exclude_squares(pos): row = pos // n col = pos - (row * n) # Eight directions: up, down, left, right, leftup, leftdown, rightup, rightdown return {i for i in range(pos, -1, -n)} | \ {i for i in range(pos, n * n, n)} | \ {i for i in range(pos, int(np.floor(pos / n) * n) - 1, -1)} | \ {i for i in range(pos, int(np.ceil((pos + 1) / n) * n), 1)} | \ {pos - (i * (n + 1)) for i in range(col + 1)} | \ {pos + (i * (n - 1)) for i in range(col + 1)} | \ {pos - (i * (n - 1)) for i in range(n - col)} | \ {pos + (i * (n + 1)) for i in range(n - col)} def transform(config, sym='i', bw=False): board_w = np.asarray([0 if i in config[1] else 1 for i in range(n * n)]).reshape((n, n)) board_b = np.asarray([0 if i in config[2] else 1 for i in range(n * n)]).reshape((n, n)) if bw: board_w, board_b = board_b, board_w if sym == 'i': return [config[0], set(np.where(board_w == 0)[0]), set(np.where(board_b == 0)[0])] if sym == 'x': return [config[0], set(np.where(board_w[::-1, ::] == 0)[0]), set(np.where(board_b[::-1, ::] == 0)[0])] if sym == 'y': return [config[0], set(np.where(board_w[::, ::-1] == 0)[0]), set(np.where(board_b[::, ::-1] == 0)[0])] if sym == 'd1': return [config[0], set(np.where(board_w.T == 0)[0]), set(np.where(board_b.T == 0)[0])] if sym == 'd2': return [config[0], set(np.where(board_w[::-1, ::-1].T == 0)[0]), set(np.where(board_b[::-1, ::-1].T == 0)[0])] if sym == 'r90': return [config[0], set(np.where(np.rot90(board_w, k=1) == 0)[0]), set(np.where(np.rot90(board_b, k=1) == 0)[0])] if sym == 'r180': return [config[0], set(np.where(np.rot90(board_w, k=2) == 0)[0]), set(np.where(np.rot90(board_b, k=2) == 0)[0])] if sym == 'r270': return [config[0], set(np.where(np.rot90(board_w, k=3) == 0)[0]), set(np.where(np.rot90(board_b, k=3) == 0)[0])] def hash_board(board): symmetries = ['i', 'x', 'y', 'd1', 'd2', 'r90', 'r180', 'r270'] configs = [transform(board, sym=sym) for sym in symmetries] + \ [transform(board, sym=sym, bw=True) for sym in symmetries] return min(hash((frozenset(config[1]), frozenset(config[2]))) for config in configs) def max_army(board): #global num_leaves color = 1 if board[0] % 2 == 0 else 2 moves = board[color] if len(moves) < 1: #num_leaves += 1 return board[0] children = [] if color == 1: children = [[board[0] + 1, board[1] - {move}, board[2] - exclude_squares(move)] for move in moves] if color == 2: children = [[board[0] + 1, board[1] - exclude_squares(move), board[2] - {move}] for move in moves] hash_set = set() for i in range(len(children)-1, -1, -1): if hash_board(children[i]) in hash_set: del children[i] else: hash_set.add(hash_board(children[i])) return max(max_army(child) for child in children) n = 4 num_leaves = 0 # [depth, white's moves, black's moves] board = [0, set(range(n * n)), set(range(n * n))] import time start = time.clock() ans = max_army(board) // 2 elapsed = time.clock() - start print(ans, ans == A250000[n-1]) #print(num_leaves) print(elapsed)
# Generated by Django 2.2.3 on 2019-08-01 10:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('openbook_moderation', '0010_auto_20190601_1909'), ] operations = [ migrations.AddField( model_name='moderationcategory', name='description_de', field=models.CharField(max_length=255, null=True, verbose_name='description'), ), migrations.AddField( model_name='moderationcategory', name='title_de', field=models.CharField(max_length=64, null=True, verbose_name='title'), ), ]
#!/usr/bin/env python from setuptools import setup setup(name='neo-observer', py_modules=['neo_observer'], packages=[], install_requires=[], version='1.0.1', description='Python module implementing the observer pattern using a centralized registry', keywords=['messaging'], author='Pierre Thibault', author_email='pierre.thibault1@gmail.com', url='https://github.com/Pierre-Thibault/neo-observer', test_suite='test_neo_observer', license='MIT', classifiers=['License :: OSI Approved :: MIT License', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', ], )
from setuptools import setup import os import io here = os.path.abspath(os.path.dirname(__file__)) with io.open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = '\n' + f.read() VERSION = '0.8.0' setup( name='vertis_periodtask', description='Periodic task with timezone', long_description=long_description, version=VERSION, url='https://github.com/vertisfinance/periodtask', author='Egyed Gรกbor', author_email='gabor.egyed@vertis.com', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.8' ], install_requires=[ 'pytz >= 2021.1', 'mako == 1.1.4', ], license='MIT', packages=['periodtask'], package_data={ '': ['templates/*', 'VERSION'], } )
german = {'รค':100, 'ร„':100, 'รฉ':50, 'รถ':100, 'ร–':100, 'รผ':50, 'รœ':100, 'รŸ':100} french = {'รจ':50, 'ร ':50, 'รฉ':50, 'ล“':50,'ร‡':100, 'รป':100, 'รด':100,'รฎ':100,'รช':100,'รข':100,'ร†':100,'ล’':100} spanish = {'รฑ':100,'รก':50,'รฉ':50,'รญ':50,'รผ':50, 'ยก':100, 'ยฟ':200} g=0 f=0 s=0 A=raw_input() # for i in range(len(A)): # #print A[i] # if A[i] in german.keys(): # g+=german[A[i]] # elif A[i] in french.keys(): # f+=french[A[i]] # elif A[i] in spanish.keys(): # s+=spanish[A[i]] for x in A: print x, if x in german: print 'g' g += german[x] if x in french: print 'f' f += french[x] if x in spanish: print 's' s += spanish[x] #print g,f,s if (g==0 and s==0 and f==0): print "English" elif (g>=f and g>=s): print "German" elif (f>=g and f>=s): print "French" else: print "Spanish"
from distutils.core import setup from Cython.Build import cythonize setup(ext_modules=cythonize("gen_chunks.pyx")) # complilation: python gen_chunks_setup.py build_ext --inplace
from django.contrib.auth import login, authenticate from django.urls import reverse_lazy from django.views.generic.edit import CreateView from .forms import CustomUserForm class SignUpView(CreateView): form_class = CustomUserForm success_url = reverse_lazy('index') template_name = 'registration/signup.html' def form_valid(self, form): valid = super().form_valid(form) email, password = form.cleaned_data.get('email'), form.cleaned_data.get('password1') new_user = authenticate(email=email, password=password) login(self.request, new_user) return valid
from _mystruct import ffi, lib p1 = ffi.new('struct MyStruct*'); p1.a = 1; print p1.a; lib.ChangeStruct(p1, 10); print p1.a;
from qtpy import QtCore, QtWidgets, QtGui class Assets: @staticmethod def load_icon() -> QtGui.QIcon: """ Loads the time capture icons. :return app_icon """ app_icon = QtGui.QIcon() app_icon.addFile("assets/icons/16x16.jpeg", QtCore.QSize(16, 16)) app_icon.addFile("assets/icons/24x24.jpeg", QtCore.QSize(24, 24)) app_icon.addFile("assets/icons/32x32.jpeg", QtCore.QSize(32, 32)) app_icon.addFile("assets/icons/48x48.jpeg", QtCore.QSize(48, 48)) app_icon.addFile("assets/icons/64x64.jpeg", QtCore.QSize(64, 64)) app_icon.addFile("assets/icons/128x128.png", QtCore.QSize(128, 128)) return app_icon @staticmethod def load_tray_icon(parent=None) -> QtWidgets.QSystemTrayIcon: """ Load the system tray icon of time capture. :param parent: :return tray_icon: """ tray_icon = QtWidgets.QSystemTrayIcon(Assets.load_icon(), parent) return tray_icon
from flask import Flask from flask import request app = Flask(__name__) @app.route("/hello-world", methods=['GET', 'POST']) def hello(): if request.method == 'POST': return "Hello %s" % request.form["name"] else: return "Hello World"
from scryfall_image_crop_downloader import * # Scan every card in a set page = 1 cardnames = [] cardnumbers = [] totalcards = 0 more = True expansion = input("Type the three-character set code for the set you want to scan: ") # ensure we get every card from the set (multiple search result pages) while more: time.sleep(0.1) cardset = scrython.cards.Search(q="set:" + expansion, page=page) more = cardset.has_more() totalcards = cardset.total_cards() cardnames = cardnames + [cardset.data()[x]["name"] for x in range(len(cardset.data()))] cardnumbers = cardnumbers + [cardset.data()[x]["collector_number"] for x in range(len(cardset.data()))] page += 1 print("Collected search results for set: " + expansion) print("Total number of cards:") print(totalcards) for cardname in sorted(set(cardnames)): process_card(cardname, expansion=expansion)
''' Created on 21 nov. 2015 @author: Vlad ''' class IDObject(object): ''' Base class for all objects having unique id within the application ''' def __init__(self, objectID): ''' Constructor for IDObject Class objectID - the unique objectID of the object in the application ''' self._ID = objectID def getId(self): ''' Return the object's unique id ''' return self._ID def setId(self, ID): self._ID = ID
# -*- coding:utf-8 -*- import re import pandas as pd import numpy as np import datetime import os.path import glob from sklearn.externals import joblib from mean_data import mean_data from operator import itemgetter def printu(data): print(unicode(data, 'utf-8')) DEBUG = False class RaceDetail: def __init__(self): # [date, course, s1f, g1f, g3f] self.data = dict() def parse_race_detail(self, filename): in_data = open(filename) data = dict() while True: line = in_data.readline() line = unicode(line, 'euc-kr').encode('utf-8') if line is None or len(line) == 0: break # ์ œ๋ชฉ : 16๋…„12์›”25์ผ(์ผ) ์ œ15๊ฒฝ์ฃผ date = int(re.search(r'\d{8}', filename).group()) if re.search(r'\(์„œ์šธ\)', line) is not None: course = int(re.search(r'\d+00*(?=M)', line).group()) if re.search(r'๊ฒฝ์ฃผ์กฐ๊ฑด', line) is not None and re.search(r'์ฃผ๋กœ', line) is not None: try: humidity = int(re.search(r'(?<=\()[\d ]+(?=\%\))', line).group()) except: humidity = 10 # read name if re.search(r'๋ถ€๋‹ด์ค‘๋Ÿ‰', line) is not None and re.search(r'์‚ฐ์ง€', line) is not None: name_list = [] while re.search(r'[-โ”€]{5}', line) is None: line = in_data.readline() break while True: line = in_data.readline() line = unicode(line, 'euc-kr').encode('utf-8') if re.search(r'[-โ”€]{5}', line) is not None: res = re.search(r'[-โ”€]{5}', line).group() if DEBUG: print("break: %s" % res) break try: name = re.findall(r'\S+', line)[2].replace('โ˜…', '') except: print("except: in %s : %s" % (filename, line)) name_list.append(name) data[name] = [date, course, humidity] if DEBUG: print("name: %s" % unicode(name, 'utf-8')) # read score if re.search(r'๋‹จ์Šน์‹', line) is not None: while re.search(r'[-โ”€]{10}', line) is None: line = in_data.readline() break i = 0 while True: line = in_data.readline() line = unicode(line, 'euc-kr').encode('utf-8') if re.search(r'[-โ”€]{10}', line) is not None: res = re.search(r'[-โ”€]{10}', line).group() #print("result: %s" % res) break words = re.findall(r'\S+', line) s1f, g1f, g2f, g3f = -1, -1, -1, -1 if len(words) == 9: if DEBUG: print("s1f: %s, g1f: %s, g3f: %s" % (words[3], words[6], words[2])) try: g1f = float(re.search(r'\d{2}\.\d', words[6]).group())*10 except: print("parsing error in race_detail - 1") g1f = -1 elif len(words) == 11: if DEBUG: print("s1f: %s, g1f: %s, g3f: %s" % (words[3], words[8], words[2])) try: g1f = float(re.search(r'\d{2}\.\d', words[8]).group())*10 except: print("parsing error in race_detail - 3") g1f = -1 elif len(words) < 9: #print("unexpected line: %s" % line) continue try: s1f = float(re.search(r'\d{2}\.\d', words[3]).group())*10 except: s1f = 150 try: g3f = float(re.search(r'\d{2}\.\d', words[2]).group())*10 except: g3f = 400 if s1f < 100 or s1f > 200: s1f = -1 if g1f < 100 or g1f > 200: g1f = -1 if g3f < 300 or g3f > 500: g3f = -1 data[name_list[i]].extend([s1f, g1f, g3f]) i += 1 for k,v in data.iteritems(): if len(v) < 5: continue if self.data.has_key(k): self.data[k].append(v) else: self.data[k] = [v] def parse_ap_rslt(self, filename): in_data = open(filename) data = dict() course = 900 while True: line = in_data.readline() line = unicode(line, 'euc-kr').encode('utf-8') if line is None or len(line) == 0: break # ์ œ๋ชฉ : 16๋…„12์›”25์ผ(์ผ) ์ œ15๊ฒฝ์ฃผ date = int(re.search(r'\d{8}', filename).group()) if re.search(r'์ฃผ๋กœ์ƒํƒœ', line) is not None and re.search(r'๋‚ .+์”จ', line) is not None: try: humidity = int(re.search(r'(?<=\()[\d ]+(?=\%\))', line).group()) except: humidity = 10 # read name if re.search(r'์‚ฐ์ง€', line) is not None and (re.search(r'์„ ์ˆ˜๋ช…', line) is not None or re.search(r'๊ธฐ์ˆ˜๋ช…', line) is not None): name_list = [] while re.search(r'[-โ”€]{5}', line) is None: line = in_data.readline() break while True: line = in_data.readline() line = unicode(line, 'euc-kr').encode('utf-8') if re.search(r'[-โ”€]{5}', line) is not None: res = re.search(r'[-โ”€]{5}', line).group() if DEBUG: print("break: %s" % res) break try: name = re.findall(r'\S+', line)[2].replace('โ˜…', '') except: print("except: in %s : %s" % (filename, line)) name_list.append(name) data[name] = [date, course, humidity] if DEBUG: print("name: %s" % unicode(name, 'utf-8')) # read score if re.search(r'S-1F', line) is not None: while re.search(r'[-โ”€]{10}', line) is None: line = in_data.readline() break i = 0 while True: line = in_data.readline() line = unicode(line, 'euc-kr').encode('utf-8') if re.search(r'[-โ”€]{10}', line) is not None: res = re.search(r'[-โ”€]{10}', line).group() if DEBUG: print("break: %s" % res) break words = re.findall(r'\S+', line) if len(words) < 9: i += 1 continue if DEBUG: print("s1f: %s, g1f: %s, g3f: %s" % (words[3], words[6], words[2])) try: s1f = float(re.search(r'\d{2}\.\d', words[3]).group())*10 except: print("parsing error in ap s1f") s1f = -1 try: g1f = float(re.search(r'\d{2}\.\d', words[6]).group())*10 except: print("parsing error in ap g1f") g1f = -1 try: g3f = float(re.search(r'\d{2}\.\d', words[2]).group())*10 except: print("parsing error in ap g3f") g3f = -1 if s1f < 100 or s1f > 200: s1f = -1 if g1f < 100 or g1f > 200: g1f = -1 if g3f < 300 or g3f > 500: g3f = -1 data[name_list[i]].extend([s1f, g1f, g3f]) i += 1 for k,v in data.iteritems(): if len(v) < 5: continue if k in self.data: self.data[k].append(v) else: self.data[k] = [v] def get_data(self, name, date, md=mean_data()): name = name.replace('โ˜…', '') date = int(date) res = [] rs = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]] course_list = [900, 1000, 1200, 1300, 1400, 1700] means_course = [[], [], []] if self.data.has_key(name): self.data[name] = sorted(self.data[name], key=itemgetter(0)) for data in self.data[name]: if data[0] < date and data[1] in course_list: c = course_list.index(data[1]) humidity = int(data[2]) if data[3] != -1: value = norm_racescore(data[0]/100%100-1, humidity, data[3], md) rs[3*c+0].append(value) # s1f means_course[0].append(value / md.race_detail[data[1]][0]) if data[4] != -1: value = norm_racescore(data[0]/100%100-1, humidity, data[4], md) rs[3*c+1].append(value) # g1f means_course[1].append(value / md.race_detail[data[1]][1]) if data[5] != -1: value = norm_racescore(data[0]/100%100-1, humidity, data[5], md) rs[3*c+2].append(value) # g3f means_course[2].append(value / md.race_detail[data[1]][2]) else: print("%s is not in race_detail" % name) m_course = [0, 0, 0] for i in range(len(rs)): if len(rs[i]) == 0: res.append(-1) else: res.append(np.mean(rs[i])) if len(means_course[0]) == 0: print("can not find race_detail of %s" % name) for i in range(len(means_course)): if len(means_course[i]) == 0: m_course[i] = 1.0 else: m_course[i] = np.mean(means_course[i]) for j in range(len(means_course[i])): m_course[i] += 0.2*(means_course[i][j] - m_course[i]) for i in range(len(rs)): for j in rs[i]: res[i] += 0.2*(j - res[i]) if res[i] == -1: #res[i] = -1 #res[i] = md.race_detail[course_list[i/3]][i%3] res[i] = m_course[i%3] * md.race_detail[course_list[i/3]][i%3] return map(lambda x: float(x), res) # len: 18 def norm_racescore(month, humidity, value, md=mean_data()): humidity = min(humidity, 20) - 1 try: m = np.array(md.race_score[0])[:,20].mean() return value * m / md.race_score[0][month][humidity] except KeyError: return value if __name__ == '__main__': DEBUG = True rd = RaceDetail() #for year in range(2007,2017): # filelist1 = glob.glob('../txt/1/ap-check-rslt/ap-check-rslt_1_%d*.txt' % year) # filelist2 = glob.glob('../txt/1/rcresult/rcresult_1_%d*.txt' % year) # for fname in filelist1: # print("processed ap %s" % fname) # rd.parse_ap_rslt(fname) # for fname in filelist2: # print("processed rc in %s" % fname) # rd.parse_race_detail(fname) fname1 = '../txt/1/ap-check-rslt/ap-check-rslt_1_20070622.txt' fname2 = '../txt/1/rcresult/rcresult_1_20091213.txt' rd.parse_ap_rslt(fname1) rd.parse_race_detail(fname2) print(rd.get_data("๋“ฑํƒœ์‚ฐ", 20110612)) #joblib.dump(rd, '../data/1_2007_2016_rd.pkl')
import astropy.units as u from copy import deepcopy from ruamel.yaml import YAML import logging log = logging.getLogger(__name__) yaml = YAML(typ='safe') class Config: def __init__(self, config_dict): self.n_burn_steps = config_dict.get('n_burn_steps', 10000) self.n_used_steps = config_dict.get('n_burn_steps', 1000) self.e_ref = config_dict.get('e_ref', 1 * u.GeV) self.threshold = config_dict.get('threshold', 0.85) self.theta2_cut = config_dict.get('theta2_cut', 0.025) self.e_true_low = config_dict.get('e_true_low', 450 * u.GeV) self.e_true_high = config_dict.get('e_true_high', 30 * u.TeV) self.n_bins_true = config_dict.get('n_bins_true', 10) self.e_est_low = config_dict.get('e_est_low', 400 * u.GeV) self.e_est_high = config_dict.get('e_est_high', 30 * u.TeV) self.n_bins_est = config_dict.get('n_bins_est', 30) self.tau = config_dict.get('tau', None) self.background = config_dict.get('background', True) self.label = 'FACT Unfolding' @staticmethod def parse_units(d): d = deepcopy(d) for k in ('e_ref', 'e_true_low', 'e_true_high', 'e_est_low', 'e_est_high'): if k in d: d[k] = u.Quantity(d[k]['value'], d[k]['unit']) return d @classmethod def from_yaml(cls, path): log.info('Loading config from ' + path) with open(path, 'r') as f: d = yaml.load(f) d = cls.parse_units(d) return cls(d)
import numpy as np import PIL as pil from functools import reduce import functools import os from PIL import Image import imageio from skimage import io import types os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" d = {"3": 4, 4: 4, int(input()) + 3: 6} print(d[d["3"]]) print(d) def power(x, n=2): s = 1 tmp = x while n: if n & 1: s *= tmp tmp *= tmp n >>= 1 return s print(power(5)) print(power(3, 8)) def sum_square(*numbers): sum = 0 for number in numbers: sum += number * number return sum print(sum_square(1, 2, 3)) d = (1, 2, 3) print(sum_square(*d)) def test_keyword(name, **kk): print(name, kk) d = {1: 11, 2: 22} test_keyword("rsy", a="hhh", b=2, c=d) test_keyword("rsy", **{'a': "hhh", 'b': 2, 'c': d}) """ *args ๆ˜ฏๅฏๅ˜ๅ‚ๆ•ฐ๏ผŒargs ๆŽฅๆ”ถ็š„ๆ˜ฏไธ€ไธช tuple๏ผ› **kw ๆ˜ฏๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ๏ผŒkw ๆŽฅๆ”ถ็š„ๆ˜ฏไธ€ไธช dictใ€‚ ไปฅๅŠ่ฐƒ็”จๅ‡ฝๆ•ฐๆ—ถๅฆ‚ไฝ•ไผ ๅ…ฅๅฏๅ˜ๅ‚ๆ•ฐๅ’Œๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐ็š„่ฏญๆณ•๏ผš ๅฏๅ˜ๅ‚ๆ•ฐๆ—ขๅฏไปฅ็›ดๆŽฅไผ ๅ…ฅ๏ผšfunc(1, 2, 3)๏ผ› ๅˆๅฏไปฅๅ…ˆ็ป„่ฃ… list ๆˆ– tuple๏ผŒๅ†้€š่ฟ‡*args ไผ ๅ…ฅ๏ผšfunc(*(1, 2, 3))๏ผ› ๅ…ณ้”ฎๅญ—ๅ‚ๆ•ฐๆ—ขๅฏไปฅ็›ดๆŽฅไผ ๅ…ฅ๏ผšfunc(a=1, b=2)๏ผ› ๅˆๅฏไปฅๅ…ˆ็ป„่ฃ… dict๏ผŒๅ†้€š่ฟ‡**kw ไผ ๅ…ฅ๏ผšfunc(**{'a': 1, 'b': 2})ใ€‚ """ # recursion def power_(x, n=2): if n == 1: return x v = power_(x, n >> 1) if n & 1: return v * v * x else: return v * v l_range = range(100)[7:15] print([d for d in os.listdir(".")]) generator = (x * x for x in range(10)) for x in range(10): print(generator.__next__()) for x in generator: print(x) def fib_g(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 a = fib_g(6) for x in a: print(x) # ๅ‡ฝๆ•ฐๅผ็ผ–็จ‹ def str2int(str): def char2num(ch): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[ch] return reduce(lambda x, y: 10 * x + y, map(char2num, str)) print(str2int("00106893")) def is_odd(n): return n % 2 == 1 d = filter(is_odd, [1, 2, 3, 4, 5, 6]) for x in d: print(x) def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum f = lazy_sum(*(1, 2, 3, 4, 5)) print(f) print(f()) # output 25 def count1(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs f1, f2, f3 = count1() print(f1()) # output 9 print(f2()) # output 9 print(f3()) # output 9 def count2(): fs = [] for x in range(1, 4): def f(i): def g(): return i * i return g fs.append(f(x)) return fs f1, f2, f3 = count2() print(f1()) # output 1 print(f2()) # output 4 print(f3()) # output 9 def count3(): fs = [] for x in range(1, 4): def f(i): return lambda: i * i fs.append(f(x)) return fs f1, f2, f3 = count3() print(f1()) # output 1 print(f2()) # output 4 print(f3()) # output 9 def log(func): def wrapper(*args, **kw): print("call %s():" % func.__name__) func(*args, **kw) print("call finished") return wrapper @log def now(): print("123456") now() int2 = functools.partial(int, base=2) print(int2("10001")) im1 = io.imread("./img_0394.jpg") im2 = imageio.imread("./img_0394.jpg") im3 = Image.open("./img_0394.jpg") print(im3.format, im3.size, im3.mode) # ้ขๅ‘ๅฏน่ฑก class Student(object): def __init__(self, name, sex): self.__name = name self.__sex = sex def info(self): print(self.__name, self.__sex) @property def name(self): return self.__name @name.setter def name(self, name): if not isinstance(name, str): raise ValueError("string needed") self.__name = name me = Student("rsy", "M") me.name = "asd" print(me.name) me.info() # output "rsy M" me.__name = "aaa" me.info() # output "rsy M" print(me.__name) # output "aaa" print(isinstance(me, Student)) print(type(me)) print(dir(type(me))) print(hasattr(me, "__name")) # output "False" print(hasattr(me, "age")) # output "False" setattr(me, "age", 21) print(getattr(me, "age")) # output "21" class B1(object): __slots__ = ("id") class D1(B1): __slots__ = ("hh") b1 = B1() b1.id = 1 d1 = D1() d1.id = 2 d1.hh = "asd"
# https://programmers.co.kr/learn/courses/30/lessons/12953?language=python3 def compute_gcd(x, y): while y: x, y = y, x % y return x def compute_lcm(x, y): return x * y // compute_gcd(x, y) def solution(arr): lcm = arr[0] for a in arr[1:]: lcm = compute_lcm(lcm, a) return lcm if __name__ == "__main__": print(solution([2, 6, 8, 14])) print(solution([2, 6, 8, 14]) == 168) print(solution([1, 2, 3])) print(solution([1, 2, 3]) == 6)
# Script to execute previously build models on a testing dataset import sys; import numpy sys.path.append("loader/") sys.path.append("preprocess/") sys.path.append("ml/") sys.path.append("configs/") sys.path.append("utils/") import logging import data_load import data_load_csv import datetime import utils import settings import model_testing_functions as mexec def score_csv(): #Setup the logger print '%s' %settings.logging_file_scoring logger = utils.setLog(settings.logging_file_scoring, logtype='Exec') logger = logging.getLogger('model-learner.test') logger.info('Start testing: %s', datetime.datetime.now().time().isoformat()) logger.info('==> Load Data.') data = data_load_csv.csv_score_file(settings.INPUT_DIR, settings.score_file_name) logger.info('==> Preprocessing data.') logger.info('==> Apply Data.') output,clf = mexec.applyModel(settings.MODELS_OUTPUT_DIR +'model_'+ settings.model_pickle_file, data, settings.RESULTS_OUTPUT_DIR, settings.MODELS_OUTPUT_DIR + 'test_data.pkl') logger.info('Finish testing: %s', datetime.datetime.now().time().isoformat()) #print output[0] print score_normalization(300,900,output[0][0]) #print('model testing complete') def score_one_iterm_online(model_path,feature_string): #feature_string = "1,1,1,-1,1,1"; logger = utils.setLog(settings.logging_file_scoring, logtype='Exec') logger = logging.getLogger('model-learner.test') logger.info('Start testing: %s', datetime.datetime.now().time().isoformat()) # transform string to numpy array np_data = numpy.fromstring(feature_string, dtype=int, sep=",") np_data = np_data.reshape(1,-1) #print np_data.shape output,clf = mexec.applyModel(model_path, np_data, settings.RESULTS_OUTPUT_DIR, settings.MODELS_OUTPUT_DIR + 'test_data.pkl') #print np_data print "returnValue:",score_normalization(300,900,output[0][0]) logger.info('Finish testing: %s', datetime.datetime.now().time().isoformat()) def score_normalization(min_v,max_v,current_v): return min_v + (max_v - min_v)*current_v if len(sys.argv) < 3: print "error: need 3 arguments" else: model_path = sys.argv[1] feature_string = sys.argv[2] score_one_iterm_online(model_path,feature_string) #score_csv() #score_one_iterm_online("")
import glob import os import tensorflow as tf FLAGS = tf.app.flags.FLAGS def read_and_decode(filename_queue): reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, features={ 'height': tf.FixedLenFeature([], tf.int64), 'width': tf.FixedLenFeature([], tf.int64), 'depth': tf.FixedLenFeature([], tf.int64), 'num_labels': tf.FixedLenFeature([], tf.int64), 'img_name': tf.FixedLenFeature([], tf.string), 'rgb': tf.FixedLenFeature([], tf.string), 'label_weights': tf.FixedLenFeature([], tf.string), 'labels': tf.FixedLenFeature([], tf.string), }) image = tf.decode_raw(features['rgb'], tf.uint8) labels_unary = tf.decode_raw(features['labels'], tf.uint8) weights = tf.decode_raw(features['label_weights'], tf.float32) img_name = features['img_name'] image = tf.reshape( image, shape=[FLAGS.img_height, FLAGS.img_width, FLAGS.num_channels]) image = tf.to_float(image) num_pixels = FLAGS.img_height * FLAGS.img_width labels = tf.reshape( labels_unary, shape=[ num_pixels, ]) labels = tf.to_float(labels) labels = tf.cast(labels, tf.int32) weights = tf.reshape( weights, shape=[ num_pixels, ]) return (image, labels, img_name, weights) def get_filenames(dataset_partition): return glob.glob(os.path.join(FLAGS.dataset_dir, dataset_partition, '*')) def inputs(shuffle=True, num_epochs=False, dataset_partition='train'): if not num_epochs: num_epochs = None files = get_filenames(dataset_partition) with tf.name_scope('input'): filename_queue = tf.train.string_input_producer( files, num_epochs=num_epochs, shuffle=shuffle, capacity=len(files)) (image, labels, img_name, weights) = read_and_decode(filename_queue) # import pdb # pdb.set_trace() (image, labels, img_name, weights) = tf.train.batch( [image, labels, img_name, weights], batch_size=FLAGS.batch_size, num_threads=8) return (image, labels, img_name, weights)
''' Okay, you have just built an autoencoder model. Let's see how it handles a more challenging task. First, you will build a model that encodes images, and you will check how different digits are represented with show_encodings(). You can change the number parameter of this function to check other digits in the console. Then, you will apply your autoencoder to noisy images from MNIST, it should be able to clean the noisy artifacts. X_test_noise is loaded in your workspace. The digits in this data look like this: Apply the power of the autoencoder! ''' # Build your encoder encoder = Sequential() encoder.add(autoencoder.layers[0]) # Encode the images and show the encodings preds = encoder.predict(X_test_noise) show_encodings(preds) # Predict on the noisy images with your autoencoder decoded_imgs = autoencoder.predict(X_test_noise) # Plot noisy vs decoded images compare_plot(X_test_noise, decoded_imgs)
import setuptools import sys try: with open("version.txt", "r") as f: version = f.read() except FileNotFoundError: print('You must either provide the file version.txt or build using make') sys.exit(1) with open("README.md", "r") as f: long_description = f.read() with open("requirements.txt", "r") as f: install_requires = list() for requirement in f.readlines(): requirement = requirement.strip().split('#')[0].strip() if len(requirement) > 0: install_requires.append(requirement) setuptools.setup( name = "hypernet", version = version, author = "Olivier de BLIC", author_email = "odeblic@gmail.com", description = "A framework exposing different services over multiple networks", long_description = long_description, long_description_content_type = "text/markdown", url = "https://github.com/odeblic/hypernet", license = "MIT License", python_requires = '>=3.6, <4', packages = setuptools.find_packages(), py_modules = ['hypernet'], install_requires = install_requires, classifiers = [ "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], )
import SimpleHTTPServer import SocketServer import logging import cgi import serial import sys import json import signal import time PORT = 3000 planted = False myinst = 0 #If we ctrl+C out of python, make sure we close the serial port first #handler catches and closes it def signal_handler(signal, frame): ser.close() sys.exit(0) class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) #SimpleHTTPServer doesn't handle post by default. Hacked up way to do it here def do_POST(self): global myinst time.sleep(0.3) length = int(self.headers["Content-Length"]) jsonString = str(self.rfile.read(length)) #print jsonString print myinst myinst = myinst + 1 jsonDict = json.loads(jsonString) #From here we have a JSON dict, that has whatever data CS is sending #fo.write(str(myinst)) #For the timer, all we care about is the the 'round' key if 'round' in jsonDict: rounds = jsonDict['round'] if 'bomb' in rounds: #print myinst #If bomb has been planted, then send the 'P' message if rounds['bomb'] == "planted": planted = True #print "Bomb has been planted" #fo.write("P9\n") ser.write('P') #If bomb has been defused, then send the 'C' message if rounds['bomb'] == "defused": planted = False ser.write('C') #fo.write("C9\n") print ("bomb has been defused") if 'phase' in rounds: if rounds['phase'] == "over": planted = False ser.write('C') print ("Time Over") #if the round ends, either bomb exploded or everyone died. #Send the 'C' message to stop timer. if 'previously' in jsonDict: if 'round' in jsonDict['previously']: if 'bomb' in jsonDict['previously']['round']: planted = False print ("Round ran out") #fo.write("Round ran out\n") ser.write('C') Handler = ServerHandler #On windows, Serial ports are usually COM1-3 #On mac/linux this will be different ser = serial.Serial('COM5') #Set up our handler for ctrl+c signal.signal(signal.SIGINT, signal_handler) #fo = open("foo23.txt", "wb") #Start server httpd = SocketServer.TCPServer(("127.0.0.1", PORT), Handler) #Run server httpd.serve_forever()
import pygame #import all the resources and utilities from pygame pygame.init() #initialize pygame resources # set mode will set the information regarding our game window and initializes it gamewindow = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Pong") clock = pygame.time.Clock() # Initialize a font (font name, font size) game_font = pygame.font.SysFont(None, 45) title_font = pygame.font.SysFont(None, 36) white = (255, 255, 255) red = (255, 0, 0) black = (0, 0, 0) gameRunning = True paused = False player_width = 10 player_height = 50 player_one_y = 275 player_two_y = 275 player_update_y = 0 player_two_update_y = 0 first_player_score = 0 second_player_score = 0 ball_x = 390 ball_y = 290 ball_width = 10 ball_height = 10 ball_speed = 5 ball_x_move = -ball_speed ball_y_move = ball_speed pong_title = title_font.render(" Pong ", True, white) # Define new function (a set of instructions) and have one parameter (score) def render_score(score, second_player): # Render the font (text, antialias flag, color) text = game_font.render(str(score), True, white) if not second_player: gamewindow.blit(text, (345, 75)) else: gamewindow.blit(text, (401, 75)) while gameRunning: #while our game is running, this is all going to happen for event in pygame.event.get(): #handles all sort of user input print event if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: player_update_y = -10 if event.key == pygame.K_s: player_update_y = 10 if event.key == pygame.K_UP: player_two_update_y = -10 if event.key == pygame.K_DOWN: player_two_update_y = 10 if event.key == pygame.K_ESCAPE: paused = not paused if event.type == pygame.KEYUP: if event.key == pygame.K_w or event.key == pygame.K_s: player_update_y = 0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: player_two_update_y = 0 #a condition that checks whether the event type is a quit event if event.type == pygame.QUIT: gameRunning = False if not paused: player_one_y += player_update_y player_two_y += player_two_update_y if player_one_y <= 0: player_one_y = 0 if player_one_y >= 550: player_one_y = 550 if player_two_y <= 0: player_two_y = 0 if player_two_y >= 550: player_two_y = 550 ball_x += ball_x_move ball_y += ball_y_move if ball_y >= 600 - ball_width: ball_y_move = -ball_speed if ball_y <= 0: ball_y_move = ball_speed if ball_x >= 800: ball_x = 390 ball_y = 290 first_player_score += 1 ball_x_move = -ball_x_move ball_y_move = -ball_y_move if ball_x <= 0 - ball_width: ball_x = 390 ball_y = 290 second_player_score += 1 ball_x_move = -ball_x_move ball_y_move = -ball_y_move if ball_x == 50 + player_width and ball_y >= player_one_y and ball_y + ball_width <= player_one_y + player_height: ball_x_move = ball_speed if ball_x == 750 - ball_width and ball_y >= player_two_y and ball_y + ball_height <= player_two_y + player_height: ball_x_move = -ball_speed gamewindow.fill(black) render_score(first_player_score, False) render_score(second_player_score, True) pygame.draw.rect(gamewindow, white, (50, player_one_y, player_width, player_height)) pygame.draw.rect(gamewindow, white, (750, player_two_y, player_width, player_height)) pygame.draw.rect(gamewindow, white, (ball_x, ball_y, ball_width, ball_height)) if not paused: gamewindow.blit(pong_title, (220, 25)) clock.tick(60) pygame.display.update() #updates all the graphic components in the game window pygame.quit() #shuts down all the pygame resources and closes the game window quit() #quits the python process #End of pong game
#!/bin/python array = ["a", "abcd", "az", "bcd", "bcda"] a = dict() for w in array: key = ''.join(sorted(w)) print (key) if key in a: v = a[key] v.append(w) else: v = [] v.append(w) a[key] = v for k, v in a.items(): print (v)
import numpy as np import abc import util from game import Agent, Action import math class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def get_action(self, game_state): """ You do not need to change this method, but you're welcome to. get_action chooses among the best options according to the evaluation function. get_action takes a game_state and returns some Action.X for some X in the set {UP, DOWN, LEFT, RIGHT, STOP} """ # Collect legal moves and successor states legal_moves = game_state.get_agent_legal_actions() # Choose one of the best actions scores = [self.evaluation_function(game_state, action) for action in legal_moves] best_score = max(scores) best_indices = [index for index in range(len(scores)) if scores[index] == best_score] chosen_index = np.random.choice(best_indices) # Pick randomly among the best "Add more of your code here if you want to" return legal_moves[chosen_index] def evaluation_function(self, current_game_state, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (GameState.py) and returns a number, where higher numbers are better. """ # Useful information you can extract from a GameState (game_state.py) successor_game_state = current_game_state.generate_successor(action=action) board = successor_game_state.board return np.sum(getChainedValueTable(board)) def score_evaluation_function(current_game_state): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return current_game_state.score def getChainedValueTable(board): t = np.zeros(board.shape) table = np.zeros(board.shape) raw,col = board.shape for x in range(raw): for y in range(col): table[x,y] = getChainedValue(x,y,board,t) return table def getChainedValue (x, y , board, table): if table[x,y]>0: return table[x,y] tileValue = board[x,y] value = 0 adjacentTiles = getAdjacentTiles(x,y,board) if tileValue != 0: for adjTileValue,adjTileCoor in adjacentTiles: value2 = 0 if tileValue == adjTileValue*2: value2 = getChainedValue(adjTileCoor[0],adjTileCoor[1],board,table) elif tileValue == adjTileValue: value2 = adjTileValue*2 elif tileValue == adjTileValue*4: value2 = adjTileValue if value2>value: value = value2 value += tileValue table[x,y] = value return value def getAdjacentTiles(x,y,board): deltas = np.array([[0,-1],[0,1],[-1,0],[1,0]]) return [(board[tuple(np.array([x,y])+delta)],tuple(np.array([x,y])+delta)) for delta in deltas if np.all(np.array([x,y])+delta<[4,4]) and np.all(np.array([x,y])+delta>=[0,0])] class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinmaxAgent, AlphaBetaAgent & ExpectimaxAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evaluation_function='scoreEvaluationFunction', depth=2): self.evaluation_function = util.lookup(evaluation_function, globals()) self.depth = depth @abc.abstractmethod def get_action(self, game_state): return def mainFunction(item, game_state): # Collect legal moves and successor states legal_moves = game_state.get_agent_legal_actions() # Choose one of the best actions scores = [item.getScore(game_state, action) for action in legal_moves] best_score = max(scores) best_indices = [index for index in range(len(scores)) if scores[index] == best_score] chosen_index = np.random.choice(best_indices) return legal_moves[chosen_index] class MinmaxAgent(MultiAgentSearchAgent): def get_action(self, game_state): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. game_state.get_legal_actions(agent_index): Returns a list of legal actions for an agent agent_index=0 means our agent, the opponent is agent_index=1 Action.STOP: The stop direction, which is always legal game_state.generate_successor(agent_index, action): Returns the successor game state after an agent takes an action """ return mainFunction(self, game_state) def getScore(self, current_game_state, action): successor_game_state = current_game_state.generate_successor(action=action) return self.minMax(successor_game_state, 1,False) def minMax(self,state,depth,isMax): if depth == 2*self.depth: return self.evaluation_function(state) if isMax: legal_moves = state.get_legal_actions(0) if len(legal_moves) == 0: return self.evaluation_function(state) successors = [state.generate_successor(0, action=action) for action in legal_moves] return max([self.minMax(succ,depth+1,False) for succ in successors]) else: legal_moves = state.get_legal_actions(1) if len(legal_moves) == 0: return self.evaluation_function(state) successors = [state.generate_successor(1, action=action) for action in legal_moves] return min([self.minMax(succ, depth + 1, True) for succ in successors]) class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def get_action(self, game_state): """ Returns the minimax action using self.depth and self.evaluationFunction """ return mainFunction(self, game_state) def getScore(self, current_game_state, action): successor_game_state = current_game_state.generate_successor(action=action) return self.alphaBeta(successor_game_state, 1, -math.inf, math.inf, False) def alphaBeta(self, state, depth, alpha, beta, isMax): if depth == 2*self.depth: return self.evaluation_function(state) if isMax: legal_moves = state.get_legal_actions(0) if len(legal_moves) == 0: return self.evaluation_function(state) successors = [state.generate_successor(0, action=action) for action in legal_moves] for succ in successors: alpha = max(alpha, self.alphaBeta(succ, depth+1, alpha, beta, not(isMax))) if alpha >= beta: break return alpha else: legal_moves = state.get_legal_actions(1) if len(legal_moves) == 0: return self.evaluation_function(state) successors = [state.generate_successor(1, action=action) for action in legal_moves] for succ in successors: beta = min(beta, self.alphaBeta(succ, depth+1, alpha, beta, not(isMax))) if alpha >= beta: break return beta class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def get_action(self, game_state): """ Returns the expectimax action using self.depth and self.evaluationFunction The opponent should be modeled as choosing uniformly at random from their legal moves. """ return mainFunction(self, game_state) def getScore(self, current_game_state, action): successor_game_state = current_game_state.generate_successor(action=action) return self.expectimax(successor_game_state, 1, False) def expectimax(self, state, depth, isMax): if depth == 2*self.depth: return self.evaluation_function(state) if isMax: legal_moves = state.get_legal_actions(0) if len(legal_moves) == 0: return self.evaluation_function(state) successors = [state.generate_successor(0, action=action) for action in legal_moves] value = -math.inf for succ in successors: value = max(value, self.expectimax(succ, depth+1, not(isMax))) return value else: legal_moves = state.get_legal_actions(1) if len(legal_moves) == 0: return self.evaluation_function(state) successors = [state.generate_successor(1, action=action) for action in legal_moves] value = 0 prob = (1 / len(successors)) for succ in successors: value += prob*(self.expectimax(succ, depth+1,not(isMax))) return value def better_evaluation_function(current_game_state): """ Your extreme 2048 evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ board = current_game_state.board kernel = np.array([1, -1]) col_conv = np.abs(np.apply_along_axis(np.convolve, 1, board, kernel, mode="valid")) row_conv = np.abs(np.apply_along_axis(np.convolve, 0, board, kernel, mode="valid")) smoothness = -(np.sum(col_conv) + np.sum(row_conv)) empty = len(current_game_state.get_empty_tiles()[0]) col_mono_diffs = (col_conv >= 0).astype(np.int32) row_mono_diffs = (row_conv >= 0).astype(np.int32) col_mono_violations = np.sum( np.abs(np.apply_along_axis(np.convolve, 1, col_mono_diffs, kernel, mode="valid"))) row_mono_violations = np.sum( np.abs(np.apply_along_axis(np.convolve, 0, row_mono_diffs, kernel, mode="valid"))) monotonicity = -(col_mono_violations + row_mono_violations) return smoothness + empty*10 + monotonicity # Abbreviation better = better_evaluation_function
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from azure.core.exceptions import HttpResponseError from .create import create_default_mac from ..helper import sanitize_resource_id, safe_key_check, safe_value_get from ..constants import MAC_API from ...._client_factory import cf_resources def get_amw_region(cmd, azure_monitor_workspace_resource_id): # Region of MAC can be different from region of RG so find the location of the azure_monitor_workspace_resource_id amw_subscription_id = azure_monitor_workspace_resource_id.split("/")[2] resources = cf_resources(cmd.cli_ctx, amw_subscription_id) try: resource = resources.get_by_id( azure_monitor_workspace_resource_id, MAC_API) amw_location = resource.location.replace(" ", "").lower() return amw_location except HttpResponseError as ex: raise ex def get_azure_monitor_workspace_resource(cmd, cluster_subscription, cluster_region, configuration_settings): azure_monitor_workspace_resource_id = "" if safe_key_check('azure-monitor-workspace-resource-id', configuration_settings): azure_monitor_workspace_resource_id = safe_value_get('azure-monitor-workspace-resource-id', configuration_settings) if azure_monitor_workspace_resource_id is None or azure_monitor_workspace_resource_id == "": azure_monitor_workspace_resource_id, azure_monitor_workspace_location = create_default_mac( cmd, cluster_subscription, cluster_region ) else: azure_monitor_workspace_resource_id = sanitize_resource_id(azure_monitor_workspace_resource_id) azure_monitor_workspace_location = get_amw_region(cmd, azure_monitor_workspace_resource_id) print(f"Using Azure Monitor Workspace (stores prometheus metrics) : {azure_monitor_workspace_resource_id}") return azure_monitor_workspace_resource_id, azure_monitor_workspace_location
from gensim.models import Word2Vec from gensim.models.word2vec import LineSentence from gensim.models.keyedvectors import KeyedVectors from data_utils import dump_pkl from annoy import AnnoyIndex import os # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # TODO: BASE_DIR = '/root/share/HCLG/ZN_qiye/week1/HCLG' def read_lines(path, col_sep=None): lines = [] with open(path, mode='r', encoding='utf-8') as f: for line in f: line = line.strip() if col_sep: if col_sep in line: lines.append(line) else: lines.append(line) return lines def extract_sentence(train_x_seg_path, train_y_seg_path, test_seg_path): ret = [] lines = read_lines(train_x_seg_path) lines += read_lines(train_y_seg_path) lines += read_lines(test_seg_path) for line in lines: ret.append(line) return ret def save_sentence(lines, sentence_path): with open(sentence_path, 'w', encoding='utf-8') as f: for line in lines: f.write('%s\n' % line.strip()) print('save sentence:%s' % sentence_path) # TODO: ๅฐ†่ฏๅ‘้‡ไฟๅญ˜ๆˆIndexๆ ผๅผ def save_index(w2v): wv_index = AnnoyIndex(256) i = 0 for key in w2v.vocab.keys(): v = w2v[key] wv_index.add_item(i, v) i += 1 wv_index.build(10) wv_index.save('wv_index_build10.index') # TODO: ๅŠ ่ฝฝๆต‹่ฏ• def test(): wv_index = AnnoyIndex(256) wv_index.load('/root/share/HCLG/ZN_qiye/week1/HCLG/work_of_word2vec/model/wv_index_build10.index', prefault=False) reverse_word_index = {} word_index = {} with open('/root/share/HCLG/ZN_qiye/week1/HCLG/data/reverse_vocab.txt', 'r', encoding='utf-8') as f: for line in f.readlines(): reverse_word_index[int(line.split()[0])] = line.split()[1] with open('/root/share/HCLG/ZN_qiye/week1/HCLG/data/vocab.txt', 'r', encoding='utf-8') as f: for line in f.readlines(): word_index[line.split()[0]] = int(line.split()[1]) for item in wv_index.get_nns_by_item(word_index[u'่ฝฆ'], 11): print(reverse_word_index[item]) def build(train_x_seg_path, train_y_seg_path, test_seg_path, out_path=None, sentence_path='', w2v_bin_path="w2v.bin", min_count=1): sentences = extract_sentence(train_x_seg_path, train_y_seg_path, test_seg_path) save_sentence(sentences, sentence_path) print('train w2v model...') # train model """ ้€š่ฟ‡gensimๅทฅๅ…ทๅฎŒๆˆword2vec็š„่ฎญ็ปƒ๏ผŒ่พ“ๅ…ฅๆ ผๅผ้‡‡็”จsentences๏ผŒไฝฟ็”จskip-gram๏ผŒembedding็ปดๅบฆ256 your code w2v = ๏ผˆone line๏ผ‰ """ # TODO: w2v = Word2Vec(sg=1, sentences=LineSentence(sentence_path), size=256, window=5) w2v.wv.save_word2vec_format(w2v_bin_path, binary=True) print("save %s ok." % w2v_bin_path) # test sim = w2v.wv.similarity('ๆŠ€ๅธˆ', '่ฝฆไธป') print('ๆŠ€ๅธˆ vs ่ฝฆไธป similarity score:', sim) # load model model = KeyedVectors.load_word2vec_format(w2v_bin_path, binary=True) word_dict = {} for word in model.vocab: word_dict[word] = model[word] dump_pkl(word_dict, out_path, overwrite=True) # TODO: ไฝฟ็”จannoyๅฐ†่ฏๅ‘้‡ไฟๅญ˜ๆˆ็ดขๅผ•ๆ–นๅผ save_index(w2v) if __name__ == '__main__': build('{}/data/train_set.seg_x.txt'.format(BASE_DIR), '{}/data/train_set.seg_y.txt'.format(BASE_DIR), '{}/data/test_set.seg_x.txt'.format(BASE_DIR), out_path='{}/data/word2vec.txt'.format(BASE_DIR), sentence_path='{}/data/sentences.txt'.format(BASE_DIR))
def solution(phone_book): length = len(phone_book) phone_book.sort() if length == 1: return True for i in range(length - 1): prefix = phone_book[i] prefix_len = len(prefix) for j in range(i + 1, length): # ๊ฐ ์ „ํ™”๋ฒˆํ˜ธ์˜ ๊ธธ์ด๊ฐ€ 1์ด์ƒ์ด๋ฏ€๋กœ 0์œผ๋กœ ํ•˜๋“œ์ฝ”๋”ฉ ๊ฐ€๋Šฅ if phone_book[i][0] != phone_book[j][0]: break # prefix์ธ์ง€ ํ™•์ธ if phone_book[j].find(phone_book[i]) != -1: return False return True
# -*- coding: utf-8 -*- import logging import math import random from Interfaces.AI.Human import sleep, random_lat_long_delta, action_delay from Interfaces.AI.Stepper.Normal import Normal from Interfaces.AI.Worker.Utils import encode_coords, distance, format_dist log = logging.getLogger(__name__) class Spiral(Normal): def take_step(self): position = [self.origin_lat, self.origin_lon, 0] coords = self.generate_coords(self.origin_lat, self.origin_lon, self.step, self.distance) self.metrica.take_position(position, self.geolocation.get_google_polilyne(coords)) self.api.set_position(*position) step = 1 for coord in coords: # starting at 0 index self.metrica.take_status(scanner_msg='ะกะฟะธั€ะฐะปัŒะฝะพะต ({} / {})'.format(step, len(coords))) log.info('ะกะฟะธั€ะฐะปัŒะฝะพะต ัะบะฐะฝะธั€ะพะฒะฐะฝะธะต ({} / {})'.format(step, len(coords))) position = (coord['lat'], coord['lng'], 0) if self.walk > 0: self._walk_to(self.walk, *position) else: self.api.set_position(*position) self.ai.heartbeat() self._work_at_position(position[0], position[1], position[2], seen_pokemon=True, seen_pokestop=True, seen_gym=True) action_delay(self.ai.delay_action_min, self.ai.delay_action_max) step += 1 @staticmethod def generate_coords(latitude, longitude, step_size, distance_limit): coords = [{'lat': latitude, 'lng': longitude}] for coord in Spiral.generate_spiral(step_size, step_size): lat = latitude + coord[0] + random_lat_long_delta() lng = longitude + coord[1] + random_lat_long_delta() coords.append({'lat': lat, 'lng': lng}) if distance(latitude, longitude, lat, lng) > distance_limit: break return coords @staticmethod def generate_spiral(arc=1, separation=1): """generate points on an Archimedes' spiral with `arc` giving the length of arc between two points and `separation` giving the distance between consecutive turnings - approximate arc length with circle arc at given distance - use a spiral equation r = b * phi """ def p2c(r, phi): """polar to cartesian """ return (r * math.cos(phi), r * math.sin(phi)) # yield a point at origin yield (0, 0) # initialize the next point in the required distance r = arc b = separation / (2 * math.pi) # find the first phi to satisfy distance of `arc` to the second point phi = float(r) / b while True: yield p2c(r, phi) # advance the variables # calculate phi that will give desired arc length at current radius # (approximating with circle) phi += float(arc) / r r = b * phi
# Solution of; # Project Euler Problem 736: Paths to Equality # https://projecteuler.net/problem=736 # # Define two functions on lattice points:$r(x,y) = (x+1,2y)$$s(x,y) = # (2x,y+1)$A path to equality of length $n$ for a pair $(a,b)$ is a sequence # $\Big((a_1,b_1),(a_2,b_2),\ldots,(a_n,b_n)\Big)$, where:$(a_1,b_1) = # (a,b)$$(a_k,b_k) = r(a_{k-1},b_{k-1})$ or $(a_k,b_k) = s(a_{k-1},b_{k-1})$ # for $k > 1$$a_k \ne b_k$ for $k < n$$a_n = b_n$$a_n = b_n$ is called the # final value. For example,$(45,90)\xrightarrow{r} # (46,180)\xrightarrow{s}(92,181)\xrightarrow{s}(184,182)\xrightarrow{s}(368,183)\xrightarrow{s}(736,184)\xrightarrow{r}$$(737,368)\xrightarrow{s}(1474,369)\xrightarrow{r}(1475,738)\xrightarrow{r}(1476,1476)$This # is a path to equality for $(45,90)$ and is of length 10 with final value # 1476. There is no path to equality of $(45,90)$ with smaller length. Find # the unique path to equality for $(45,90)$ with smallest odd length. Enter # the final value as your answer. # # by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ == '__main__': n = 1000 i = 10000 prob_id = 736 timed.caller(dummy, n, i, prob_id)
#!/usr/bin/python import sys, re, numpy, gzip import jkgenome from gzip import GzipFile class segInfo: def __init__(self,seg): self.seg = seg self.staOffset,self.endOffset = map(int,seg[1].split('..')) self.span = self.endOffset - self.staOffset + 1 self.numMatch = int(re.search('matches:([0-9]*),',seg[3]).group(1)) self.splice = True if 'splice_' in seg[3] else False self.len = len(seg[0]) rm = re.match('([+-])([^:]+):([0-9]+)\.\.([0-9]+)',seg[2]) self.chrom = rm.group(2) self.strand = rm.group(1) if self.strand == '+': self.segSta = int(rm.group(3)) self.segEnd = int(rm.group(4)) else: self.segSta = int(rm.group(4)) self.segEnd = int(rm.group(3)) if len(seg) > 4: self.mapq = int(re.search('mapq:([0-9]+)', seg[4]).group(1)) if self.span != 0: self.percMatch = float(self.numMatch) / self.span * 100. # deprecated else: self.percMatch = 0 self.numMismatch = self.span - self.numMatch # deprecated rm = re.search('label_[12]:([^,\t]*)',seg[3]) if rm: self.label = rm.group(1) else: self.label = '' rm = re.search('sub:([0-9]+)', seg[3]) if rm: self.nSub = int(rm.group(1)) else: rm = re.search('sub:[0-9]+\+[0-9]+=([0-9]+)', seg[3]) if rm: self.nSub = int(rm.group(1)) else: self.nSub = 0 rm = re.search('start:([0-9]+)\.\.', seg[3]) if rm: self.nClipS = int(rm.group(1)) else: self.nClipS = 0 rm = re.search('\.\.ins:([0-9]+),', seg[3]) if rm: self.nIns = int(rm.group(1)) else: self.nIns = 0 rm = re.search('\.\.del:([0-9]+),', seg[3]) if rm: self.nDel = int(rm.group(1)) else: self.nDel = 0 rm = re.search('\.\.(end|term):([0-9]+),', seg[3]) if rm: self.nClipE = int(rm.group(2)) else: self.nClipE = 0 # rm = re.search('donor:', seg[3]) # if rm: # self.donor = True # else: # self.donor = False # # rm = re.search('acceptor:', seg[3]) # if rm: # self.acceptor = True # else: # self.acceptor = False def __print__(self): print self.seg def toCIGAR_trans(self): strand = self.seg[2][0] (pos1, pos2) = re.search('([0-9]+)\.\.([0-9]+)', self.seg[1]).groups() rm = re.search('(start|term):([0-9]+)\.\.', self.seg[3]) if rm: start = int(rm.group(2)) else: start = -1 rm = re.search('(end|term):([0-9]+),', self.seg[3]) if rm: end = int(rm.group(2)) else: end = -1 match = int(pos2) - int(pos1) + 1 if start >= 0 and end < 0: ## first half clip = len(self.seg[0]) - int(pos2) if start > 0: cigar = str(start) + 'S' else: cigar = '' if strand == '-': cigar = str(clip) + 'H' + str(match) + 'M' + cigar else: cigar = cigar + str(match) + 'M' + str(clip) + 'H' clip = -1 * clip elif start < 0 and end >= 0: ## second half cigar = str(int(pos1) - 1) + 'H' if strand == '-': cigar = str(match) + 'M' + cigar if end > 0: cigar = str(end) + 'S' + cigar else: cigar = cigar + str(match) + 'M' if end > 0: cigar = cigar + str(end) + 'S' clip = int(pos1) - 1 return (cigar, clip) def toCIGAR(self, last=False): strand = self.seg[2][0] rm = re.search('(start|term):([0-9]+)\.\.', self.seg[3]) if rm: start = int(rm.group(2)) else: start = -1 if len(self.seg) > 4 and start < 0: start = int(re.search('([0-9]+)\.\.[0-9]+', self.seg[1]).group(1)) - 1 rm = re.search('del:([0-9]+),', self.seg[3]) if rm: deletion = int(rm.group(1)) else: deletion = 0 rm = re.search('ins:([0-9]+),', self.seg[3]) if rm: insertion = int(rm.group(1)) else: insertion = 0 rm = re.search('splice_dist_2:([0-9]+)', self.seg[3]) if rm: splice_dist_2 = int(rm.group(1)) else: splice_dist_2 = 0 rm = re.search('(end|term):([0-9]+),', self.seg[3]) if rm: end = int(rm.group(2)) else: end = -1 rm = re.search('([0-9]+)\.\.([0-9]+)', self.seg[1]) if last and end < 0: end = len(self.seg[0]) - int(rm.group(2)) seg_len = int(rm.group(2)) - int(rm.group(1)) + 1 + start + end match = seg_len - start - end cigar = '' if strand == '+': if start > 0: cigar = str(start) + 'S' if match > 0: cigar = cigar + str(match) + 'M' if deletion > 0: cigar = cigar + str(deletion) + 'D' if insertion > 0: cigar = cigar + str(insertion) + 'I' if splice_dist_2 > 0: cigar = cigar + str(splice_dist_2) + 'N' if end > 0: cigar = cigar + str(end) + 'S' else: if start > 0: cigar = str(start) + 'S' if match > 0: cigar = str(match) + 'M' + cigar if deletion > 0: cigar = str(deletion) + 'D' + cigar if insertion > 0: cigar = str(insertion) + 'I' + cigar if splice_dist_2 > 0: cigar = str(splice_dist_2) + 'N' + cigar if end > 0: cigar = str(end) + 'S' + cigar return cigar class seqMatch: def __init__(self,segL): # take newline- and tab-delimited list ''' __init__ ''' self.segL = segL self.locusL = [jkgenome.locus(s[2]) for s in segL] self.segObjL = self.getSegInfo() def getSegInfo(self): return [segInfo(seg) for seg in self.segL] # def mergedLocusL(self,gap=10): # # return jkgenome.mergeLoci(self.locusL, gap) def pairInfo(self): insertLen, pairType = None, None if len(self.segL[0]) >= 6: infoL = self.segL[0][5].split(',') insertLen = int(infoL[1].split(':')[1]) if len(infoL) >= 3: pairType = infoL[2].split(':')[1] return insertLen, pairType def score(self): return int(re.search('align_score:([0-9]*)',self.segL[0][4]).group(1)) def isSpliced(self): return True in [seg.splice for seg in self.segObjL] def spliceJuncL(self,wrtIntron=False): juncL = [] for i in range(len(self.segL)-1): # # for debugging: neither sense? nor antisense? no ambiguous strand in GSNAP # if re.search('splice_',self.segL[i][3]): # mo = re.search('dir:([^,]+)',self.segL[i][3]) # if not mo or mo.group(1) not in ('sense','antisense'): # print self.segL[i][3] # raise Exception if not (re.search('\.\.donor:',self.segL[i][3]) or re.search('\.\.acceptor:',self.segL[i][3])): continue direction = re.search('dir:([^,\t]*)', self.segL[i][3]).group(1) bp1 = re.match('([+-])([^:]+):[0-9]+..([0-9]+)',self.segL[i][2]) bp2 = re.match('([+-])([^:]+):([0-9]+)..[0-9]+',self.segL[i+1][2]) bp1 = [bp1.group(1),bp1.group(2),int(bp1.group(3))] bp2 = [bp2.group(1),bp2.group(2),int(bp2.group(3))] if wrtIntron: bp1[2] += 1 if bp1[0]=='+' else -1 bp2[2] += -1 if bp2[0]=='+' else 1 if (bp1[0],direction) in (('+','sense'),('-','antisense')): trans_strand1 = '+' elif (bp1[0],direction) in (('+','antisense'),('-','sense')): trans_strand1 = '-' else: raise Exception if (bp2[0],direction) in (('+','sense'),('-','antisense')): trans_strand2 = '+' elif (bp2[0],direction) in (('+','antisense'),('-','sense')): trans_strand2 = '-' else: raise Exception if direction=='sense': key = [trans_strand1,]+bp1[1:]+[trans_strand2,]+bp2[1:] elif direction=='antisense': key = [trans_strand2,]+bp2[1:]+[trans_strand1,]+bp1[1:] else: raise Exception juncL.append(tuple(key)) return juncL def numMatch(self,seq_read): return sum(self.posProfile(seq_read)) - len(self.segL) + 1 #return sum([int(re.search('matches:([0-9]*)',seg[3]).group(1)) for seg in self.segL]) def getPenalties(self): nSub = sum([s.nSub for s in self.segObjL]) nIns = sum([s.nIns for s in self.segObjL[:-1]]) nDel = sum([s.nDel for s in self.segObjL[:-1]]) nClipS = self.segObjL[0].nClipS nClipE = self.segObjL[-1].nClipE return {'nSub':nSub, 'nIns':nIns, 'nDel':nDel, 'nClipS':nClipS, 'nClipE':nClipE} def posProfile(self,seq_read): seqLen = len(seq_read) profile = [0,]*seqLen for seg in self.segL: seq_match = seg[0] for p in range(min(seqLen,len(seq_match))): if seq_match[p] == '-': continue profile[p] = int(seq_match[p].isupper() and seq_read[p]!='N') return profile def toCIGAR(self): segInfoL = self.getSegInfo() (strand, rname, pos1, pos2) = re.search('([\+\-])(.*):([0-9]+)\.\.([0-9]+)', segInfoL[0].seg[2]).groups() pos = min(pos1, pos2) if len(segInfoL) == 1: cigar = segInfoL[0].toCIGAR(True) else: cigar = segInfoL[0].toCIGAR() prev_cigar = cigar index = 0 for segInfo in segInfoL[1:]: index = index + 1 if index == (len(segInfoL) - 1): final = True else: final = False rm = re.search('([\+\-])(.*):([0-9]+)\.\.([0-9]+)', segInfo.seg[2]).groups() if pos == 0 or pos > min(rm[2], rm[3]): pos = min(rm[2], rm[3]) if strand == '-': dist = int(pos2) - int(rm[2]) - 1 else: dist = int(rm[2]) - int(pos2) - 1 pos1 = rm[2] pos2 = rm[3] cur_cigar = segInfo.toCIGAR(final) if strand == '-': if dist > 0 and 'D' not in prev_cigar and 'I' not in prev_cigar and 'N' not in prev_cigar: cigar = cur_cigar + str(dist) + 'N' + cigar else: cigar = cur_cigar + cigar else: if dist > 0 and 'D' not in prev_cigar and 'I' not in prev_cigar and 'N' not in prev_cigar: cigar = cigar + str(dist) + 'N' + cur_cigar else: cigar = cigar + cur_cigar return cigar class seqRead: def __init__(self,l): # take newline- and tab-delimited list self.raw = l self.nLoci = int(l[0][1].split(' ')[0]) if ' ' in l[0][1]: self.pairRel = l[0][1][l[0][1].find(' ')+1:] else: self.pairRel = '' def seq(self): return self.raw[0][0][1:] def rawText(self): return '\t'.join(self.raw[0][:2])+'\n' + '\n'.join(['\t'.join(t) for t in self.raw[1:]])+'\n' def matchL(self): return [seqMatch([l.split('\t') for l in m.lstrip().split('\n,')]) for m in '\n'.join(['\t'.join(t) for t in self.raw[1:]]).split('\n ')] def pairInfo(self): return self.matchL()[0].pairInfo() def qual(self): return self.raw[0][2] def rid(self): return self.raw[0][3] class gsnapFile(file): def __init__(self, fileName, paired=True): self.paired = paired if fileName[-3:] == '.gz': self.gzip = True self.gzfile = gzip.open(fileName) else: self.gzip = False return super(gsnapFile,self).__init__(fileName) def next(self): l1 = [] while 1: if self.gzip: line = self.gzfile.next() else: line = file.next(self) if line=='\n': break l1.append(line[:-1].split('\t')) if self.paired: l2 = [] while 1: if self.gzip: line = self.gzfile.next() else: line = file.next(self) if line=='\n': break l2.append(line[:-1].split('\t')) return seqRead(l1), seqRead(l2) else: return seqRead(l1)
from flask import Flask, redirect, render_template, request from flask.json import jsonify app = Flask(__name__) @app.route('/api/merge_tiffs', methods=('POST',)) def merge_tiffs(): uploaded_files = request.files.getlist('files[]') print(uploaded_files) return jsonify({ 'status': 'SUCCESS', 'file': 'http://localhost:3000/result/123.tiff', 'base64': 'asdfasfadfadsf' }) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=8000)
""" Hyperparameter tuning with scikit-learn ======================================= This tutorial shows you how to tune hyperparameters with scikit-learn (GridSearchCV) in the setting of trialwise decoding on dataset BCIC IV 2a. """ ###################################################################### # Loading and preprocessing the dataset # ------------------------------------- # ###################################################################### # Loading # ~~~~~~~ # ###################################################################### # First, we load the data. In this tutorial, we use the functionality of # braindecode to load datasets through # `MOABB <https://github.com/NeuroTechX/moabb>`__ to load the BCI # Competition IV 2a data. # # .. note:: # To load your own datasets either via mne or from # preprocessed X/y numpy arrays, see `MNE Dataset # Tutorial <./plot_mne_dataset_example.html>`__ and `Numpy Dataset # Tutorial <./plot_custom_dataset_example.html>`__. # from braindecode.datasets.moabb import MOABBDataset subject_id = 3 dataset = MOABBDataset(dataset_name="BNCI2014001", subject_ids=[subject_id]) ###################################################################### # Preprocessing # ~~~~~~~~~~~~~ # ###################################################################### # Now we apply preprocessing like bandpass filtering to our dataset. You # can either apply functions provided by # `mne.Raw <https://mne.tools/stable/generated/mne.io.Raw.html>`__ or # `mne.Epochs <https://mne.tools/0.11/generated/mne.Epochs.html#mne.Epochs>`__ # or apply your own functions, either to the MNE object or the underlying # numpy array. # # .. note:: # These prepocessings are now directly applied to the loaded # data, and not on-the-fly applied as transformations in # PyTorch-libraries like # `torchvision <https://pytorch.org/docs/stable/torchvision/index.html>`__. # from braindecode.preprocessing.preprocess import ( exponential_moving_standardize, preprocess, Preprocessor) from numpy import multiply low_cut_hz = 4. # low cut frequency for filtering high_cut_hz = 38. # high cut frequency for filtering # Parameters for exponential moving standardization factor_new = 1e-3 init_block_size = 1000 # Factor to convert from V to uV factor = 1e6 preprocessors = [ Preprocessor('pick_types', eeg=True, meg=False, stim=False), # Keep EEG sensors Preprocessor(lambda data: multiply(data, factor)), # Convert from V to uV Preprocessor('filter', l_freq=low_cut_hz, h_freq=high_cut_hz), # Bandpass filter Preprocessor(exponential_moving_standardize, # Exponential moving standardization factor_new=factor_new, init_block_size=init_block_size) ] # Transform the data preprocess(dataset, preprocessors) ###################################################################### # Cut Compute Windows # ~~~~~~~~~~~~~~~~~~~ # ###################################################################### # Now we cut out compute windows, the inputs for the deep networks during # training. In the case of trialwise decoding, we just have to decide if # we want to cut out some part before and/or after the trial. For this # dataset, in our work, it often was beneficial to also cut out 500 ms # before the trial. # from braindecode.preprocessing.windowers import create_windows_from_events trial_start_offset_seconds = -0.5 # Extract sampling frequency, check that they are same in all datasets sfreq = dataset.datasets[0].raw.info['sfreq'] assert all([ds.raw.info['sfreq'] == sfreq for ds in dataset.datasets]) # Calculate the trial start offset in samples. trial_start_offset_samples = int(trial_start_offset_seconds * sfreq) # Create windows using braindecode function for this. It needs parameters to define how # trials should be used. windows_dataset = create_windows_from_events( dataset, trial_start_offset_samples=trial_start_offset_samples, trial_stop_offset_samples=0, preload=True, ) ###################################################################### # Split dataset into train and valid # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ###################################################################### # We can easily split the dataset using additional info stored in the # description attribute, in this case ``session`` column. We select # ``session_T`` for training and ``session_E`` for evaluation. # splitted = windows_dataset.split('session') train_set = splitted['session_T'] eval_set = splitted['session_E'] ###################################################################### # Create model # ------------ # ###################################################################### # Now we create the deep learning model! Braindecode comes with some # predefined convolutional neural network architectures for raw # time-domain EEG. Here, we use the shallow ConvNet model from `Deep # learning with convolutional neural networks for EEG decoding and # visualization <https://arxiv.org/abs/1703.05051>`__. These models are # pure `PyTorch <https://pytorch.org>`__ deep learning models, therefore # to use your own model, it just has to be a normal PyTorch # `nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__. # import torch from braindecode.util import set_random_seeds from braindecode.models import ShallowFBCSPNet cuda = torch.cuda.is_available() # check if GPU is available, if True chooses to use it device = 'cuda' if cuda else 'cpu' if cuda: torch.backends.cudnn.benchmark = True seed = 20200220 # random seed to make results reproducible # Set random seed to be able to reproduce results set_random_seeds(seed=seed, cuda=cuda) n_classes = 4 # Extract number of chans and time steps from dataset n_chans = train_set[0][0].shape[0] input_window_samples = train_set[0][0].shape[1] model = ShallowFBCSPNet( n_chans, n_classes, input_window_samples=input_window_samples, final_conv_length='auto', ) # Send model to GPU if cuda: model.cuda() ###################################################################### # Training # -------- # ###################################################################### # Now we train the network! EEGClassifier is a Braindecode object # responsible for managing the training of neural networks. It inherits # from skorch.NeuralNetClassifier, so the training logic is the same as in # `Skorch <https://skorch.readthedocs.io/en/stable/>`__. # from skorch.callbacks import LRScheduler from braindecode import EEGClassifier batch_size = 16 n_epochs = 4 clf = EEGClassifier( model, criterion=torch.nn.NLLLoss, optimizer=torch.optim.AdamW, optimizer__lr=[], batch_size=batch_size, train_split=None, # train /test split is handled by GridSearchCV callbacks=[ "accuracy", ("lr_scheduler", LRScheduler('CosineAnnealingLR', T_max=n_epochs - 1)), ], device=device, ) ###################################################################### # Use scikit-learn GridSearchCV to tune hyperparameters. To be able # to do this, we slice the braindecode datasets that by default return # a 3-tuple to return X and y, respectively. # ###################################################################### # **Note**: The KFold object splits the datasets based on their # length which corresponds to the number of compute windows. In # this (trialwise) example this is fine to do. In a cropped setting # this is not advisable since this might split compute windows # of a single trial into both train and valid set. # from sklearn.model_selection import GridSearchCV, KFold from skorch.helper import SliceDataset from numpy import array import pandas as pd train_X = SliceDataset(train_set, idx=0) train_y = array([y for y in SliceDataset(train_set, idx=1)]) cv = KFold(n_splits=2, shuffle=True, random_state=42) fit_params = {'epochs': n_epochs} param_grid = { 'optimizer__lr': [0.00625, 0.000625, 0.0000625], } search = GridSearchCV( estimator=clf, param_grid=param_grid, cv=cv, return_train_score=True, scoring='accuracy', refit=True, verbose=1, error_score='raise' ) search.fit(train_X, train_y, **fit_params) search_results = pd.DataFrame(search.cv_results_) best_run = search_results[search_results['rank_test_score'] == 1].squeeze() print(f"Best hyperparameters were {best_run['params']} which gave a validation " f"accuracy of {best_run['mean_test_score']*100:.2f}% (training " f"accuracy of {best_run['mean_train_score']*100:.2f}%).") eval_X = SliceDataset(eval_set, idx=0) eval_y = SliceDataset(eval_set, idx=1) score = search.score(eval_X, eval_y) print(f"Eval accuracy is {score*100:.2f}%.")
from gans.utils import data_loader, sample_noise, show_images, show_cifar import torch import torch.nn as nn import torch.optim as optim from torch.nn import init from torch.autograd import Variable num_train=50000 num_val=5000 noise_dim=96 batch_size=128 loader_train, loader_val = data_loader() def initialize_weights(m): """m is a layer""" if isinstance(m, nn.Linear) or isinstance(m, nn.ConvTranspose2d): init.xavier_uniform(m.weight.data) def discriminator(): """Discrinator nn""" model = nn.Sequential( nn.Linear(28**2, 256), nn.LeakyReLU(0.01), nn.Linear(256, 256), nn.LeakyReLU(0.01), nn.Linear(256, 1) ) return model.type(torch.FloatTensor) def discriminator_loss(logits_real, logits_fake): loss = -torch.mean(logits_real) + torch.mean(logits_fake) return loss def generator(noise_dimension=noise_dim): model = nn.Sequential( # spherical shape might be better nn.Linear(noise_dimension, 1024), nn.ReLU(), nn.Linear(1024, 1024), nn.ReLU(), nn.Linear(1024, 28**2), nn.Tanh() ) return model.type(torch.FloatTensor) def generator_loss(score_discriminator): """Calculate loss for the generator The objective is to maximise the error rate of the discriminator """ loss = - torch.mean(score_discriminator) return loss def optimizer_gen(model): """Return optimizer""" optimizer = optim.RMSprop(model.parameters(), lr=5e-5) return optimizer def optimizer_dis(model): """Return optimizer""" optimizer = optim.RMSprop(model.parameters(), lr=5e-5) return optimizer def init_networks(resume=False, label=''): if resume: generator_n = torch.load('../../results/models/generator' + label + '.pt') discriminator_n = torch.load( '../../results/models/discriminator' + label + '.pt') else: generator_n = generator() discriminator_n = discriminator() generator_n.label = label discriminator_n.label = label return generator_n, discriminator_n def train(discriminator, generator, show_every=250, num_epochs=100, save_every=2000): iter_count = 0 dis_optimizer = optimizer_dis(discriminator) gen_optimizer = optimizer_gen(generator) for epoch in range(num_epochs): for x, _ in loader_train: if len(x) != batch_size: continue dis_optimizer.zero_grad() real_data = Variable(x).type(torch.FloatTensor) logits_real = discriminator(2 * (real_data.view(batch_size, -1) - 0.5)).type(torch.FloatTensor) # g_fake_seed = Variable(sample_noise(batch_size, noise_dim)).type(torch.FloatTensor) # fake_images = generator(g_fake_seed) for _ in range(5): g_fake_seed = Variable(sample_noise(batch_size, noise_dim)).type(torch.FloatTensor) fake_images = generator(g_fake_seed) logits_fake = discriminator(fake_images.detach().view(batch_size, -1)) d_total_error = discriminator_loss(logits_real, logits_fake) d_total_error.backward(retain_graph=True) dis_optimizer.step() # weight clipping for p in discriminator.parameters(): p.data.clamp_(-0.01, 0.01) gen_optimizer.zero_grad() gen_logits_fake = discriminator(fake_images.view(batch_size, -1)) g_loss = generator_loss(gen_logits_fake) g_loss.backward() gen_optimizer.step() if iter_count % show_every == 0: print('Iter: {}, D: {:.4}, G:{:.4}'.format(iter_count, d_total_error.data[0], g_loss.data[0])) imgs_numpy = fake_images.data.cpu().numpy() show_images(imgs_numpy[0:16], iter_count, save=True, model=generator.label) iter_count += 1 if iter_count % save_every == 0: torch.save(discriminator, 'results/weights/discriminator' + discriminator.label + '.pt') torch.save(generator, 'results/weights/generator' + generator.label + '.pt') iter_count += 1 if __name__ == '__main__': generator, discriminator = init_networks(label='wgan_mnist_00') train(discriminator, generator)
import SoftLayer import json def main(args): name = args namejson = name virtualGuestName = namejson["vsiname"] print("VSI Name: " + virtualGuestName) power = namejson["poweraction"] print("Power Action: " + power) ibmcloud_iaas_user = namejson["username"] print("Username: " + ibmcloud_iaas_user) ibmcloud_iaas_key = namejson["key"] print("API Key: " + ibmcloud_iaas_key) username = ibmcloud_iaas_user key = ibmcloud_iaas_key client = SoftLayer.Client(username=username, api_key=key) try: virtualGuests = client['SoftLayer_Account'].getVirtualGuests() print(virtualGuests) except SoftLayer.SoftLayerAPIError as e: print("Unable to retrieve hardware. ") virtualGuestId = namejson["vsiid"] # for virtualGuest in virtualGuests: # if virtualGuest['hostname'] == virtualGuestName: # virtualGuestId = virtualGuest['id'] # print("VSI ID:" + str(virtualGuestId)) if power == "off": virtualMachines = client['SoftLayer_Virtual_Guest'].powerOff(id=virtualGuestId) print (virtualGuestName + " powered off") return { "Status": "OK" } elif power == "on": try: virtualMachines = client['SoftLayer_Virtual_Guest'].powerOn(id=virtualGuestId) print (virtualGuestName + " powered off") return { "Status": "OK" } except SoftLayer.SoftLayerAPIError as e: print("Unable to power on/off the virtual guest")
from django.db import models from blog.models import Post from django.conf import settings # Create your models here. class LikeQuerySet(models.QuerySet): def post_like_count(self, post_id): return self.filter(post__id=post_id).count() class Like(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name="post_likes") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) objects = models.Manager() likes = LikeQuerySet.as_manager() def set_post(self, post): self.post = post def get_post(self): return self.post def set_user(self, user): self.user = user def get_user(self): return self.user def __str__(self): return f"{self.post} {self.user}"
"""Contains the Serve class""" import os from nltk.tokenize import word_tokenize, sent_tokenize import seq2seq class Serve: """Serve an instance of the trained model""" def __init__(self, sess, model_name, checkpoint): os.makedirs(os.path.join('training', 'data', 'dataset', model_name), exist_ok=True) data_dir = os.path.join('training', 'data', 'dataset', model_name) model_dir = os.path.join('training', 'model', model_name) hparams = seq2seq.utils.load_hparams(os.path.join(model_dir, 'char_level_hparams.json')) self.normalizer = seq2seq.predictor.Predictor(sess, dataset_dir=data_dir, output_dir=model_dir, output_file=checkpoint, hparams=hparams) def model_api(self, input_data): """Does all the preprocessing before prediction. 1. Split into sentences 2. Tokenize to words 3. Tokenize into characters 4. encode ' ' into <space> Args: input_data (string): informal text Returns: string: normalized text """ output = "" for sentence in sent_tokenize(input_data): tokens = ' '.join(word_tokenize(sentence)) normalized = self.normalizer.predict(self._char_emb_format(tokens)) output += normalized.replace(' ', '').replace('<space>', ' ') return output @staticmethod def _char_emb_format(text): return ' '.join(list(text)).replace(' ' * 3, ' <space> ')
#PyAutoGUI๏ผŒ่‡ชๅ‹•ๆŽงๅˆถๆป‘้ผ ่ˆ‡้ต็›ค # ๆœ‰ๅ•้กŒ from selenium import webdriver import pyautogui as auto import pandas as pd import time import sys # ๅปบ็ซ‹็€่ฆฝๅ™จ็‰ฉไปถ driver = webdriver.Chrome() #ไฝฟ็”จChrome #driver = webdriver.Firefox() #ไฝฟ็”จFirefox driver.set_window_position(0, 0) #่จญๅฎš่ฆ–็ช—ไฝ็ฝฎ driver.set_window_size(800, 600) #่จญๅฎš่ฆ–็ช—ๅคงๅฐ driver.maximize_window() #ๅ…จ่žขๅน•้กฏ็คบ #ๅฐ็ฃ่ญ‰ๅˆธไบคๆ˜“ๆ‰€ url = "https://www.twse.com.tw/zh/page/trading/exchange/STOCK_DAY.html" driver.get(url) time.sleep(3) auto.PAUSE = 3 auto.moveTo(1263, 438, 2) auto.click() auto.typewrite("2330") auto.moveTo(1461, 438, 2) auto.click() time.sleep(5) html = driver.page_source data = pd.read_html(html) print(data) print('ๅฎŒๆˆ') sys.exit() from selenium import webdriver import pyautogui as auto import pandas as pd import time stocks = [ { "name": "่ฏ้›ป", "id": "2303" }, { "name": "ๅฐ็ฉ้›ป", "id": "2330" }, { "name": "่ฏ็ขฉ", "id": "2357" } ] # ๅปบ็ซ‹็€่ฆฝๅ™จ็‰ฉไปถ driver = webdriver.Chrome() #ไฝฟ็”จChrome #driver = webdriver.Firefox() #ไฝฟ็”จFirefox driver.set_window_position(0, 0) #่จญๅฎš่ฆ–็ช—ไฝ็ฝฎ driver.set_window_size(800, 600) #่จญๅฎš่ฆ–็ช—ๅคงๅฐ driver.maximize_window() #ๅ…จ่žขๅน•้กฏ็คบ #ๅฐ็ฃ่ญ‰ๅˆธไบคๆ˜“ๆ‰€ url = "https://www.twse.com.tw/zh/page/trading/exchange/STOCK_DAY.html" driver.get(url) auto.PAUSE = 3 for stock in stocks: auto.moveTo(1263, 438, 2) auto.doubleClick() auto.typewrite(stock["id"]) auto.moveTo(1461, 438, 2) auto.click() time.sleep(5) html = driver.page_source data = pd.read_html(html) print(stock["name"]) print(data[0]) print('------------------------------------------------------------') #60ๅ€‹ print('ๅฎŒๆˆ') ''' print('ๆบ–ๅ‚™้—œ้–‰็€่ฆฝๅ™จ') for i in range(0, 10): print(i, '็ง’') # 0~9 time.sleep(1) #print('้—œ้–‰็€่ฆฝๅ™จ') #driver.close() #้—œ้–‰็€่ฆฝๅ™จ print('้—œ้–‰็€่ฆฝๅ™จไธฆไธ”้€€ๅ‡บ้ฉ…ๅ‹•็จ‹ๅบ') driver.quit() #้—œ้–‰็€่ฆฝๅ™จไธฆไธ”้€€ๅ‡บ้ฉ…ๅ‹•็จ‹ๅบ '''
import enum class Place: """ A place is a general concept of a physical location, such as a powerplant, a weather station, a position on a river etc. """ def __init__(self, kind, key, name, unit=None, fuels=None, area=None, location=None, children=None, curves=None): #: The place type. See :py:class:`PlaceType`. self.kind = kind #: The identifier self.key = key #: The name of the place self.name = name #: The unit name (if it is a powerplant unit) self.unit = unit #: The fuel types (if it is a powerplant unit) self.fuels = fuels or [] #: The area in which this place lies, see :py:class:`Area`. self.area = area #: The geolocation of this place: ``(latitude, longitude)`` self.location = location or None #: A list of children (typically used for a powerplants with sub-units) self.children = children or [] #: A list of curves with data for this place. See :py:class:`Curve`. self.curves = curves or [] @property def latitude(self): """ The latitude of this place. """ return self.location[0] @property def longitude(self): """ The longitude of this place. """ return self.location[1] def __str__(self): return self.__repr__() def __repr__(self): parts = [] parts.append(f"<Place: key=\"{self.key}\", name=\"{self.name}\"") if self.unit: parts.append(f", unit=\"{self.unit}\"") if self.kind: parts.append(f", kind={self.kind}") if self.fuels: parts.append(f", fuels={self.fuels}") if self.location: parts.append(f", location={self.location}") parts.append(">") return "".join(parts) _placetypes_lookup = {} class PlaceType(enum.Enum): """ Enumerator of place types. Used to describe type type of a :py:class:`Place`. """ #: A city CITY = ("city",) #: A power consumer, such as a factory CONSUMER = ("consumer",) #: A power producer (power plant) PRODUCER = ("producer",) #: A river location RIVER = ("river",) #: A weather station WEATHERSTATION = ("weatherstation",) #: Unspecified OTHER = ("other",) def __init__(self, tag): self.tag = tag _placetypes_lookup[tag.lower()] = self def __str__(self): return self.__repr__() def __repr__(self): return self.name @staticmethod def is_valid_tag(tag): """ Check whether a place type tag exists or not. :param tag: A place type tag :type tag: str :return: True if it exists, otherwise False :rtype: bool """ return tag.lower() in _placetypes_lookup @staticmethod def by_tag(tag): """ Look up place type by tag. :param tag: A place type tag :type tag: str :return: The place type for the given tag :rtype: PlaceType """ return _placetypes_lookup[tag.lower()]
# Generated by Django 3.0.2 on 2020-01-28 16:14 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('chat', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='conversation', name='name', ), ]
# https://leetcode.com/problems/design-tic-tac-toe/ class TicTacToe: def __init__(self, n: int): """ Initialize your data structure here. """ self.board = [[0] * n for _ in range(n)] def move(self, row: int, col: int, player: int) -> int: """ Player {player} makes a move at ({row}, {col}). @param row The row of the board. @param col The column of the board. @param player The player, can be either 1 or 2. @return The current winning condition, can be either: 0: No one wins. 1: Player 1 wins. 2: Player 2 wins. """ self.board[row][col] = player return self.check(row, col, player) def check(self, row, col, player): count = 0 n = len(self.board) #horizontal for i in range(n): if self.board[row][i] == player: count += 1 if count == n: return player count = 0 for i in range(n): if self.board[i][col] == player: count += 1 if count == n: return player # left to right cross if row - col == 0: count = 0 for i in range(n): if self.board[i][i] == player: count += 1 if count == n: return player # righ to left cross. if row + col == n - 1: count, i, j = 0, 0, n - 1 for k in range(n): if self.board[i][j] == player: count += 1 i, j = i + 1, j - 1 if count == n: return player return 0
# name = raw_input("what is your name ") # print("hello "+ str(name)) number = input("input a number: ") number = int(number) if number % 2 == 0: print(str(number) + " is a EVEN number.") else: # number %2 ==1 print(str(number)+ " is a ODD number.")
#Task 1 zoo_animals = ["tiger", "lion", "monkey"] if len(zoo_animals) > 2: print('the first animal at the zoo is the ' + zoo_animals[0]) print('the second animal at the zoo is the ' + zoo_animals[1]) print('the third animal at the zoo is the ' + zoo_animals[2]) zoo_animals[2] = "deer" print(zoo_animals) zoo_animals.append("Peacock") print(zoo_animals) start_list = [5, 3, 1, 2, 4] square_list = [] #Task 2 for x in start_list: square_list.append(x ** 2) square_list.sort() print(square_list) #Task 3 menu = {} # Empty dictionary menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair print(menu['Chicken Alfredo']) # Your code here: Add some dish-price pairs to menu! menu['Italian Pasta'] = 15.00 menu['Nepali Chowmein'] = 20 menu['Hot Pot'] = 25 menu['Momo'] = 30 print("There are " + str(len(menu)) + " items on the menu.") print(menu) del menu['Nepali Chowmein'] print(menu) #Task 4 inventory = { 'gold' : 500, 'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf'], 'pocket' : ['seashell','strange berry', 'lint']} inventory['backpack'].sort() # Adding a key 'burlap bag' and assigning a list to it inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth'] # Sorting the list found under the key 'pouch' inventory['pouch'].sort() # Your code here inventory['backpack'].remove('dagger') print(inventory['backpack']) inventory['gold'] += 50 print(inventory['gold'])
class Ruisekiwa: def __init__(self,lst): s = 0 self.r = [0] for i,_ in enumerate(lst): self.r.append(s+lst[i]) s += lst[i] def query(self,a,b): #ใƒชใ‚นใƒˆๅ†…ใฎๅŠ้–‹ๅŒบ้–“[a,b)ใฎ็ทๅ’Œ return self.r[b] - self.r[a] def main(): pass ##def ruisekiwa(l): ## #้–ขๆ•ฐใƒใƒผใ‚ธใƒงใƒณ ## lst = [0] ## s = 0 ## for i,v in enumerate(l): ## lst.append(s + v) ## s += v ## return lst if __name__ == '__main__': main()
# Generated by Django 2.1.7 on 2019-03-16 18:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quiz', '0004_auto_20190316_1722'), ] operations = [ migrations.AlterField( model_name='quiz', name='course', field=models.ManyToManyField(to='users.ProfileCourse'), ), ]
from __future__ import absolute_import from django.http import HttpResponse from django.test import TestCase from django.test.utils import override_settings from django.utils.deprecation import MiddlewareMixin from corsheaders.middleware import ( ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_MAX_AGE ) from tests.utils import append_middleware, prepend_middleware, temporary_check_request_hander class ShortCircuitMiddleware(MiddlewareMixin): def process_request(self, request): return HttpResponse('short-circuit-middleware-response') class CorsMiddlewareTests(TestCase): def test_get_no_origin(self): resp = self.client.get('/') assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp def test_get_origin_vary_by_default(self): resp = self.client.get('/') assert resp['Vary'] == 'Origin' @override_settings(CORS_ORIGIN_WHITELIST=['http://example.com']) def test_get_not_in_whitelist(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.org') assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp @override_settings(CORS_ORIGIN_WHITELIST=['https://example.org']) def test_get_not_in_whitelist_due_to_wrong_scheme(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.org') assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp @override_settings(CORS_ORIGIN_WHITELIST=['http://example.com', 'http://example.org']) def test_get_in_whitelist(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.org') assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'http://example.org' @override_settings(CORS_ORIGIN_WHITELIST=['http://example.com', 'null']) def test_null_in_whitelist(self): resp = self.client.get('/', HTTP_ORIGIN='null') assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'null' @override_settings( CORS_ORIGIN_ALLOW_ALL=True, CORS_EXPOSE_HEADERS=['accept', 'origin', 'content-type'], ) def test_get_expose_headers(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.com') assert resp[ACCESS_CONTROL_EXPOSE_HEADERS] == 'accept, origin, content-type' @override_settings(CORS_ORIGIN_ALLOW_ALL=True) def test_get_dont_expose_headers(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.com') assert ACCESS_CONTROL_EXPOSE_HEADERS not in resp @override_settings( CORS_ALLOW_CREDENTIALS=True, CORS_ORIGIN_ALLOW_ALL=True, ) def test_get_allow_credentials(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.com') assert resp[ACCESS_CONTROL_ALLOW_CREDENTIALS] == 'true' @override_settings(CORS_ORIGIN_ALLOW_ALL=True) def test_get_dont_allow_credentials(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.com') assert ACCESS_CONTROL_ALLOW_CREDENTIALS not in resp @override_settings( CORS_ALLOW_HEADERS=['content-type', 'origin'], CORS_ALLOW_METHODS=['GET', 'OPTIONS'], CORS_PREFLIGHT_MAX_AGE=1002, CORS_ORIGIN_ALLOW_ALL=True, ) def test_options_allowed_origin(self): resp = self.client.options( '/', HTTP_ORIGIN='http://example.com', ) assert resp[ACCESS_CONTROL_ALLOW_HEADERS] == 'content-type, origin' assert resp[ACCESS_CONTROL_ALLOW_METHODS] == 'GET, OPTIONS' assert resp[ACCESS_CONTROL_MAX_AGE] == '1002' @override_settings( CORS_ALLOW_HEADERS=['content-type', 'origin'], CORS_ALLOW_METHODS=['GET', 'OPTIONS'], CORS_PREFLIGHT_MAX_AGE=0, CORS_ORIGIN_ALLOW_ALL=True, ) def test_options_no_max_age(self): resp = self.client.options('/', HTTP_ORIGIN='http://example.com') assert resp[ACCESS_CONTROL_ALLOW_HEADERS] == 'content-type, origin' assert resp[ACCESS_CONTROL_ALLOW_METHODS] == 'GET, OPTIONS' assert ACCESS_CONTROL_MAX_AGE not in resp @override_settings( CORS_ALLOW_METHODS=['OPTIONS'], CORS_ALLOW_CREDENTIALS=True, CORS_ORIGIN_WHITELIST=['http://localhost:9000'], ) def test_options_whitelist_with_port(self): resp = self.client.options('/', HTTP_ORIGIN='http://localhost:9000') assert resp[ACCESS_CONTROL_ALLOW_CREDENTIALS] == 'true' @override_settings( CORS_ALLOW_METHODS=['OPTIONS'], CORS_ALLOW_CREDENTIALS=True, CORS_ORIGIN_REGEX_WHITELIST=[r'^http?://(\w+\.)?example\.com$'], ) def test_options_adds_origin_when_domain_found_in_origin_regex_whitelist(self): resp = self.client.options('/', HTTP_ORIGIN='http://foo.example.com') assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'http://foo.example.com' @override_settings( CORS_ALLOW_METHODS=['OPTIONS'], CORS_ALLOW_CREDENTIALS=True, CORS_ORIGIN_REGEX_WHITELIST=(r'^http?://(\w+\.)?example\.org$',), ) def test_options_will_not_add_origin_when_domain_not_found_in_origin_regex_whitelist(self): resp = self.client.options('/', HTTP_ORIGIN='http://foo.example.com') assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp def test_options(self): resp = self.client.options( '/', HTTP_ACCESS_CONTROL_REQUEST_METHOD='value', ) assert resp.status_code == 200 def test_options_empty_request_method(self): resp = self.client.options( '/', HTTP_ACCESS_CONTROL_REQUEST_METHOD='', ) assert resp.status_code == 200 def test_options_no_header(self): resp = self.client.options('/') assert resp.status_code == 404 @override_settings( CORS_ALLOW_CREDENTIALS=True, CORS_ORIGIN_ALLOW_ALL=True, ) def test_allow_all_origins_get(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.com') assert resp.status_code == 200 assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'http://example.com' assert resp['Vary'] == 'Origin' @override_settings( CORS_ALLOW_CREDENTIALS=True, CORS_ORIGIN_ALLOW_ALL=True, ) def test_allow_all_origins_options(self): resp = self.client.options( '/', HTTP_ORIGIN='http://example.com', HTTP_ACCESS_CONTROL_REQUEST_METHOD='value', ) assert resp.status_code == 200 assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'http://example.com' assert resp['Vary'] == 'Origin' @override_settings( CORS_ALLOW_CREDENTIALS=True, CORS_ORIGIN_ALLOW_ALL=True, ) def test_non_200_headers_still_set(self): """ It's not clear whether the header should still be set for non-HTTP200 when not a preflight request. However this is the existing behaviour for django-cors-middleware, so at least this test makes that explicit, especially since for the switch to Django 1.10, special-handling will need to be put in place to preserve this behaviour. See `ExceptionMiddleware` mention here: https://docs.djangoproject.com/en/1.10/topics/http/middleware/#upgrading-pre-django-1-10-style-middleware """ resp = self.client.get('/test-401/', HTTP_ORIGIN='http://example.com') assert resp.status_code == 401 assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'http://example.com' @override_settings( CORS_ALLOW_CREDENTIALS=True, CORS_ORIGIN_ALLOW_ALL=True, ) def test_auth_view_options(self): """ Ensure HTTP200 and header still set, for preflight requests to views requiring authentication. See: https://github.com/ottoyiu/django-cors-headers/issues/3 """ resp = self.client.options( '/test-401/', HTTP_ORIGIN='http://example.com', HTTP_ACCESS_CONTROL_REQUEST_METHOD='value', ) assert resp.status_code == 200 assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'http://example.com' assert resp['Content-Length'] == '0' def test_signal_handler_that_returns_false(self): def handler(*args, **kwargs): return False with temporary_check_request_hander(handler): resp = self.client.options( '/', HTTP_ORIGIN='http://example.com', HTTP_ACCESS_CONTROL_REQUEST_METHOD='value', ) assert resp.status_code == 200 assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp def test_signal_handler_that_returns_true(self): def handler(*args, **kwargs): return True with temporary_check_request_hander(handler): resp = self.client.options( '/', HTTP_ORIGIN='http://example.com', HTTP_ACCESS_CONTROL_REQUEST_METHOD='value', ) assert resp.status_code == 200 assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'http://example.com' @override_settings(CORS_ORIGIN_WHITELIST=['http://example.com']) def test_signal_handler_allow_some_urls_to_everyone(self): def allow_api_to_all(sender, request, **kwargs): return request.path.startswith('/api/') with temporary_check_request_hander(allow_api_to_all): resp = self.client.options( '/', HTTP_ORIGIN='http://example.org', HTTP_ACCESS_CONTROL_REQUEST_METHOD='value', ) assert resp.status_code == 200 assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp resp = self.client.options( '/api/something/', HTTP_ORIGIN='http://example.org', HTTP_ACCESS_CONTROL_REQUEST_METHOD='value', ) assert resp.status_code == 200 assert resp[ACCESS_CONTROL_ALLOW_ORIGIN] == 'http://example.org' @override_settings(CORS_ORIGIN_WHITELIST=['http://example.com']) def test_signal_called_once_during_normal_flow(self): def allow_all(sender, request, **kwargs): allow_all.calls += 1 return True allow_all.calls = 0 with temporary_check_request_hander(allow_all): self.client.get('/', HTTP_ORIGIN='http://example.org') assert allow_all.calls == 1 @override_settings(CORS_ORIGIN_WHITELIST=['http://example.com']) @prepend_middleware('tests.test_middleware.ShortCircuitMiddleware') def test_get_short_circuit(self): """ Test a scenario when a middleware that returns a response is run before the ``CorsMiddleware``. In this case ``CorsMiddleware.process_response()`` should ignore the request if MIDDLEWARE setting is used (new mechanism in Django 1.10+). """ resp = self.client.get('/', HTTP_ORIGIN='http://example.com') assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp @override_settings( CORS_ORIGIN_WHITELIST=['http://example.com'], CORS_URLS_REGEX=r'^/foo/$', ) @prepend_middleware(__name__ + '.ShortCircuitMiddleware') def test_get_short_circuit_should_be_ignored(self): resp = self.client.get('/', HTTP_ORIGIN='http://example.com') assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp @override_settings( CORS_ORIGIN_WHITELIST=['http://example.com'], CORS_URLS_REGEX=r'^/foo/$', ) def test_get_regex_matches(self): resp = self.client.get('/foo/', HTTP_ORIGIN='http://example.com') assert ACCESS_CONTROL_ALLOW_ORIGIN in resp @override_settings( CORS_ORIGIN_WHITELIST=['http://example.com'], CORS_URLS_REGEX=r'^/not-foo/$', ) def test_get_regex_doesnt_match(self): resp = self.client.get('/foo/', HTTP_ORIGIN='http://example.com') assert ACCESS_CONTROL_ALLOW_ORIGIN not in resp @override_settings( CORS_ORIGIN_WHITELIST=['http://example.com'], CORS_URLS_REGEX=r'^/foo/$', ) def test_get_regex_matches_path_info(self): resp = self.client.get('/foo/', HTTP_ORIGIN='http://example.com', SCRIPT_NAME='/prefix/') assert ACCESS_CONTROL_ALLOW_ORIGIN in resp @override_settings(CORS_ORIGIN_WHITELIST=['http://example.com']) def test_cors_enabled_is_attached_and_bool(self): """ Ensure that request._cors_enabled is available - although a private API someone might use it for debugging """ resp = self.client.get('/', HTTP_ORIGIN='http://example.com') request = resp.wsgi_request assert isinstance(request._cors_enabled, bool) assert request._cors_enabled @override_settings(CORS_ORIGIN_WHITELIST=['http://example.com']) def test_works_if_view_deletes_cors_enabled(self): """ Just in case something crazy happens in the view or other middleware, check that get_response doesn't fall over if `_cors_enabled` is removed """ resp = self.client.get( '/delete-is-enabled/', HTTP_ORIGIN='http://example.com', ) assert ACCESS_CONTROL_ALLOW_ORIGIN in resp @override_settings( CORS_REPLACE_HTTPS_REFERER=True, CORS_ORIGIN_REGEX_WHITELIST=(r'.*example.*',), ) class RefererReplacementCorsMiddlewareTests(TestCase): def test_get_replaces_referer_when_secure(self): resp = self.client.get( '/', HTTP_FAKE_SECURE='true', HTTP_HOST='example.com', HTTP_ORIGIN='https://example.org', HTTP_REFERER='https://example.org/foo' ) assert resp.status_code == 200 assert resp.wsgi_request.META['HTTP_REFERER'] == 'https://example.com/' assert resp.wsgi_request.META['ORIGINAL_HTTP_REFERER'] == 'https://example.org/foo' @append_middleware('corsheaders.middleware.CorsPostCsrfMiddleware') def test_get_post_middleware_rereplaces_referer_when_secure(self): resp = self.client.get( '/', HTTP_FAKE_SECURE='true', HTTP_HOST='example.com', HTTP_ORIGIN='https://example.org', HTTP_REFERER='https://example.org/foo' ) assert resp.status_code == 200 assert resp.wsgi_request.META['HTTP_REFERER'] == 'https://example.org/foo' assert 'ORIGINAL_HTTP_REFERER' not in resp.wsgi_request.META def test_get_does_not_replace_referer_when_insecure(self): resp = self.client.get( '/', HTTP_HOST='example.com', HTTP_ORIGIN='https://example.org', HTTP_REFERER='https://example.org/foo' ) assert resp.status_code == 200 assert resp.wsgi_request.META['HTTP_REFERER'] == 'https://example.org/foo' assert 'ORIGINAL_HTTP_REFERER' not in resp.wsgi_request.META @override_settings(CORS_REPLACE_HTTPS_REFERER=False) def test_get_does_not_replace_referer_when_disabled(self): resp = self.client.get( '/', HTTP_FAKE_SECURE='true', HTTP_HOST='example.com', HTTP_ORIGIN='https://example.org', HTTP_REFERER='https://example.org/foo', ) assert resp.status_code == 200 assert resp.wsgi_request.META['HTTP_REFERER'] == 'https://example.org/foo' assert 'ORIGINAL_HTTP_REFERER' not in resp.wsgi_request.META def test_get_does_not_fail_in_referer_replacement_when_referer_missing(self): resp = self.client.get( '/', HTTP_FAKE_SECURE='true', HTTP_HOST='example.com', HTTP_ORIGIN='https://example.org', ) assert resp.status_code == 200 assert 'HTTP_REFERER' not in resp.wsgi_request.META assert 'ORIGINAL_HTTP_REFERER' not in resp.wsgi_request.META def test_get_does_not_fail_in_referer_replacement_when_host_missing(self): resp = self.client.get( '/', HTTP_FAKE_SECURE='true', HTTP_ORIGIN='https://example.org', HTTP_REFERER='https://example.org/foo', ) assert resp.status_code == 200 assert resp.wsgi_request.META['HTTP_REFERER'] == 'https://example.org/foo' assert 'ORIGINAL_HTTP_REFERER' not in resp.wsgi_request.META @override_settings(CORS_ORIGIN_REGEX_WHITELIST=()) def test_get_does_not_replace_referer_when_not_valid_request(self): resp = self.client.get( '/', HTTP_FAKE_SECURE='true', HTTP_HOST='example.com', HTTP_ORIGIN='https://example.org', HTTP_REFERER='https://example.org/foo', ) assert resp.status_code == 200 assert resp.wsgi_request.META['HTTP_REFERER'] == 'https://example.org/foo' assert 'ORIGINAL_HTTP_REFERER' not in resp.wsgi_request.META
""" Custom decorators ================= Custom decorators for various tasks and to bridge Flask with Eve """ from flask import current_app as app, request, Response, abort from functools import wraps from ext.auth.tokenauth import TokenAuth from ext.auth.helpers import Helpers # Because of circular import in context from ext.app.eve_helper import eve_abort class AuthenticationFailed(Exception): """Raise custom error""" class AuthenticationNoToken(Exception): """Raise custom error""" def require_token(allowed_roles=None): """ Custom decorator for token auth Wraps the custom TokenAuth class used by Eve and sends it the required param """ def decorator(f): @wraps(f) def wrapped(*args, **kwargs): try: # print(request.headers.get('User-Agent')) # No authorization in request # Let it raise an exception try: authorization_token = request.authorization.get('username', None) except Exception as e: raise AuthenticationFailed # Do the authentication # Need to remove prefix + / for request.path auth = TokenAuth() auth_result = auth.check_auth(token=authorization_token, # Token method=request.method, resource=request.path[len(app.globals.get('prefix')) + 1:], allowed_roles=allowed_roles) if auth_result is not True: raise AuthenticationFailed # Catch exceptions and handle correctly except AuthenticationFailed: eve_abort(401, 'Please provide proper credentials') except Exception as e: eve_abort(500, 'Server error') return f(*args, **kwargs) return wrapped return decorator def require_superadmin(): """Require user to be in a group of hardcoded user id's Should use Helpers then get administrators @TODO: use a switch for ref [superadmin, admin,..]? @TODO: in ext.auth.helpers define a get_users_in_roles_by_ref(ref)? """ def decorator(f): @wraps(f) def wrapped(*args, **kwargs): h = Helpers() if int(app.globals['user_id']) not in h.get_superadmins(): # [99999]: # # # eve_abort(401, 'You do not have sufficient privileges') return f(*args, **kwargs) return wrapped return decorator
#!/usr/bin/env python3 from os import execv from sys import argv from sys import exit from sys import maxsize import socket from subprocess import check_call from time import sleep from math import floor import struct import RPi.GPIO as GPIO from RPLCD.gpio import CharLCD import spidev from gpiozero import Button from gpiozero import DigitalInputDevice from gpiozero import DigitalOutputDevice from gpiozero import PWMOutputDevice # for programming without the instrument connected # not extensively tested, mostly used when developing the menu system SCOPELESS = False # LCD Characters CURSOR = 0x7F UP_ARROW = 0x00 DOWN_ARROW = 0x01 BLANK = 0x10 OMEGA = 0xF4 ACTIVE = 0x2A # I/O expander device register addresses IOCON_INITIAL = 0x0A IODIRA = 0x00 IPOLA = 0x01 GPINTENA = 0x02 DEFVALA = 0x03 INTCONA = 0x04 IOCON = 0x05 GPPUA = 0x06 INTFA = 0x07 INTCAPA = 0x08 GPIOA = 0x09 OLATA = 0x0A IODIRB = 0x10 IPOLB = 0x11 GPINTENB = 0x12 DEFVALB = 0x13 INTCONB = 0x14 GPPUB = 0x16 INTFB = 0X17 INTCAPB = 0x18 GPIOB = 0x19 OLATB = 0x1A SPI_WRITE = 0x40 SPI_READ = 0x41 SPI_MODE = 0b00 SPI_RATE = 10000000 # hertz DEBOUNCE = 0.035 # seconds CMD_WAIT = 0.01 # gives time for scope to update AUTOSCALE_WAIT = 1 # SPI device 2, port A # button matrix columns C1 = 1<<5 C2 = 1<<4 C3 = 1<<3 C4 = 1<<2 C5 = 1<<1 C6 = 1<<0 # SPI device 2, port B # button matrix rows R1 = 1<<5 R2 = 1<<4 R3 = 1<<3 R4 = 1<<2 R5 = 1<<1 R6 = 1<<0 # Encoders # SPI device 0, port A A_CH2_OS = 1 B_CH2_OS = 0 A_CH1_OS = 2 B_CH1_OS = 3 A_CH1_SC = 4 B_CH1_SC = 5 A_CH2_SC = 7 B_CH2_SC = 6 # SPI device 0, port B A_CH3_SC = 1 B_CH3_SC = 0 A_CH4_SC = 3 B_CH4_SC = 2 A_CH4_OS = 5 B_CH4_OS = 4 A_CH3_OS = 7 B_CH3_OS = 6 # SPI device 1, port A A_HORIZ = 2 B_HORIZ = 3 A_DELAY = 4 B_DELAY = 5 A_SEL = 6 B_SEL = 7 #SPI device 1, port B A_MATH_SC = 1 B_MATH_SC = 0 A_MATH_OS = 3 B_MATH_OS = 2 A_CURS = 4 B_CURS = 5 A_TRIG = 6 B_TRIG = 7 def disable_backlight(): bklt_en.off() print("backlight disabled") if(bklt_fault.value == True): cmd = b'SYST:DSP "An LCD backlight power fault has occurred"\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def pwm_backlight(f): # dimming possible but mostly unused if (bklt_fault.value == False): bklt_en.on() bklt_en.value = f print("backlight:", f) else: disable_backlight() def disable_power(): pwr_en.off() print("power disabled") if(pwr_fault.value == True): cmd = b'SYST:DSP "A fatal power fault has occurred"\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def enable_power(): if (pwr_fault.value == False): pwr_en.on() print("power enabled") else: disable_power() def init_spi(): spi_reset.on() sleep(0.001) spi_reset.off() #buttons spi.open(0, 0) spi.mode = SPI_MODE spi.max_speed_hz = SPI_RATE to_send = [SPI_WRITE, IOCON_INITIAL, 0xA3] # set up IOCON resgister cs2.on() spi.xfer2(to_send) cs2.off() to_send = [SPI_WRITE, IODIRA, 0xC0] # configure columns as outputs cs2.on() spi.xfer2(to_send) cs2.off() to_send = [SPI_WRITE, OLATA, 0x3F] # set columns high cs2.on() spi.xfer2(to_send) cs2.off() to_send = [SPI_WRITE, IPOLB, 0xFF] # invert the logic level of the row inputs cs2.on() spi.xfer2(to_send) cs2.off() to_send = [SPI_WRITE, GPINTENB, 0x3F] # enable interrupts for rows cs2.on() spi.xfer2(to_send) cs2.off() to_send = [SPI_WRITE, GPPUB, 0xFF] # enable pullups for rows cs2.on() spi.xfer2(to_send) cs2.off() spi.close() # encoder bank 0 spi.open(0, 0) spi.mode = SPI_MODE spi.max_speed_hz = SPI_RATE to_send = [SPI_WRITE, IOCON_INITIAL, 0xA2] spi.xfer2(to_send) to_send = [SPI_WRITE, GPINTENA, 0xFF] spi.xfer2(to_send) to_send = [SPI_WRITE, GPINTENB, 0xFF] spi.xfer2(to_send) spi.close() # encoder bank 1 spi.open(0, 1) spi.mode = SPI_MODE spi.max_speed_hz = SPI_RATE to_send = [SPI_WRITE, IOCON_INITIAL, 0xA2] spi.xfer2(to_send) to_send = [SPI_WRITE, GPINTENA, 0xFC] spi.xfer2(to_send) to_send = [SPI_WRITE, GPINTENB, 0xFF] spi.xfer2(to_send) to_send = [SPI_WRITE, GPPUA, 0x03] spi.xfer2(to_send) spi.close() def ascii_to_num(txt): sign = 1 if txt[0] == 43 else -1 try: decimal = txt.index(b'.') mult = 10 ** max(0,decimal - 2) except ValueError: mult = 10 ** (len(txt)-2) pass num = 0 for x in txt: if (x == 43 or x == 45 or x == 46): continue else: num += mult * (x-48) mult = mult / 10 return num * sign def num_to_ascii(num, is_integer): sign = b'+' if num >= 0 else b'-' if is_integer: return sign + str(abs(floor(num))).encode() else: return sign + str(num).encode() def update_select_funcs(): global ActiveMenu EncoderBank1A.encoders[2].cw_action = ActiveMenu.increment_cursor EncoderBank1A.encoders[2].ccw_action = ActiveMenu.decrement_cursor def init_encoders(): # Bank 0A Ch1Scale = Encoder(A_CH1_SC, B_CH1_SC) Ch1Scale.detent = True Ch1Scale.enabled = True Ch1Scale.cw_action = Scope.Channel1.cw_scale Ch1Scale.ccw_action = Scope.Channel1.ccw_scale Ch1Offset = Encoder(A_CH1_OS, B_CH1_OS) Ch1Offset.enabled = True Ch1Offset.cw_action = Scope.Channel1.cw_offset Ch1Offset.ccw_action = Scope.Channel1.ccw_offset Ch2Scale = Encoder(A_CH2_SC, B_CH2_SC) Ch2Scale.detent = True Ch2Scale.enabled = True Ch2Scale.cw_action = Scope.Channel2.cw_scale Ch2Scale.ccw_action = Scope.Channel2.ccw_scale Ch2Offset = Encoder(A_CH2_OS, B_CH2_OS) Ch2Offset.enabled = True Ch2Offset.cw_action = Scope.Channel2.cw_offset Ch2Offset.ccw_action = Scope.Channel2.ccw_offset bank0A = [Ch1Scale, Ch1Offset, Ch2Scale, Ch2Offset] EncoderBank0A.encoders = bank0A # Bank 0B Ch3Scale = Encoder(A_CH3_SC, B_CH3_SC) Ch3Scale.detent = True Ch3Scale.enabled = True Ch3Scale.cw_action = Scope.Channel3.cw_scale Ch3Scale.ccw_action = Scope.Channel3.ccw_scale Ch3Offset = Encoder(A_CH3_OS, B_CH3_OS) Ch3Offset.enabled = True Ch3Offset.cw_action = Scope.Channel3.cw_offset Ch3Offset.ccw_action = Scope.Channel3.ccw_offset Ch4Scale = Encoder(A_CH4_SC, B_CH4_SC) Ch4Scale.detent = True Ch4Scale.enabled = True Ch4Scale.cw_action = Scope.Channel4.cw_scale Ch4Scale.ccw_action = Scope.Channel4.ccw_scale Ch4Offset = Encoder(A_CH4_OS, B_CH4_OS) Ch4Offset.enabled = True Ch4Offset.cw_action = Scope.Channel4.cw_offset Ch4Offset.ccw_action = Scope.Channel4.ccw_offset bank0B = [Ch3Scale, Ch3Offset, Ch4Scale, Ch4Offset] EncoderBank0B.encoders = bank0B # Bank 1A Timebase = Encoder(A_HORIZ, B_HORIZ) Timebase.enabled = True Timebase.detent = True Timebase.cw_action = Scope.Timebase.cw_scale Timebase.ccw_action = Scope.Timebase.ccw_scale Delay = Encoder(A_DELAY, B_DELAY) Delay.enabled = True Delay.cw_action = Scope.Timebase.cw_delay Delay.ccw_action = Scope.Timebase.ccw_delay Select = Encoder(A_SEL, B_SEL) Select.enabled = True Select.sensitivity = 4 Select.cw_action = ActiveMenu.increment_cursor Select.ccw_action = ActiveMenu.decrement_cursor bank1A = [Timebase, Delay, Select] EncoderBank1A.encoders = bank1A # Bank 1B MathScale = Encoder(A_MATH_SC, B_MATH_SC) MathScale.detent = True MathOffset = Encoder(A_MATH_OS, B_MATH_OS) Cursor = Encoder(A_CURS, B_CURS) Cursor.enabled = True Cursor.cw_action = Scope.Cursor.cw_cursor Cursor.ccw_action = Scope.Cursor.ccw_cursor Trigger = Encoder(A_TRIG, B_TRIG) Trigger.enabled = True Trigger.cw_action = Scope.Trigger.cw_level Trigger.ccw_action = Scope.Trigger.ccw_level bank1B = [MathScale, MathOffset, Cursor, Trigger] EncoderBank1B.encoders = bank1B def get_reply(): reply = Sock.recv(4096) return reply def print_reply(): print(get_reply()) def button_press(row, col): global ActiveMenu if (row & R1): if (col & C1): # select ActiveMenu.select() elif (col & C2): # back ActiveMenu.back() elif (col & C3): # horizontal if (not Scope.Timebase.Menu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Timebase.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Timebase.Menu.is_active): ActiveMenu.disable() elif (col & C4): # delay knob Scope.Timebase.zero_delay() elif (col & C5): # run/stop cmd = b':OPER:COND?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] oscr = 0 mult = 1 for i in range(4, 9): if (reply[i] == 43): break else: oscr += mult * (reply[i]-48) mult *= 10 if (oscr & 1<<3): cmd = b':STOP\r\n' Sock.sendall(cmd) else: cmd = b'RUN\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) elif (col & C6): # single cmd = b':SINGLE\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) elif (row & R2): if (col & C1): # horizontal scale knob pass elif (col & C2): # zoom if (not Scope.Timebase.mode[0:1] == b'W'): Scope.Timebase.set_mode_window() else: Scope.Timebase.set_mode_main() elif (col & C3): # default setup cmd = b'*CLS\r\n' Sock.sendall(cmd) cmd = b'*RST\r\n' Sock.sendall(cmd) sleep(AUTOSCALE_WAIT) get_reply() Scope.get_state() elif (col & C4): # autoscale cmd = b':AUTOSCALE\r\n' Sock.sendall(cmd) sleep(AUTOSCALE_WAIT) get_reply() Scope.get_state() elif (col & C5): # math scale knob pass elif (col & C6): # invalid input pass elif (row & R3): if (col & C1): # trigger if (not Scope.Trigger.Menu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Trigger.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Trigger.Menu.is_active): ActiveMenu.disable() elif (col & C2): # trigger level knob Scope.Trigger.level = 0 cmd = b':TRIG:LFIF\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) elif (col & C3): # measure if (not Scope.Measure.Menu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Measure.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Measure.Menu.is_active): ActiveMenu.disable() elif (col & C4): # cursors if (not Scope.Cursor.Menu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Cursor.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Cursor.Menu.is_active): ActiveMenu.disable() elif (col & C5): # cursors knob if (Scope.Cursor.mode[0:1] == b'O'): Scope.Cursor.set_mode_manual() if (not Scope.Cursor.ActiveCursorMenu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Cursor.ActiveCursorMenu Scope.Cursor.cursor_select = True ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Cursor.ActiveCursorMenu.is_active and Scope.Cursor.cursor_select): ActiveMenu.select() Scope.Cursor.cursor_select = False elif (Scope.Cursor.ActiveCursorMenu.is_active and not Scope.Cursor.cursor_select): Scope.Cursor.cursor_select = True elif (col & C6): # math pass elif (row & R4): if (col & C1): # acquire pass elif (col & C2): # display pass elif (col & C3): # label pass elif (col & C4): # save/recall pass elif (col & C5): # utility pass elif (col & C6): # math offset knob pass elif (row & R5): if (col & C1): # ch1 scale knob pass elif (col & C2): # ch2 scale knob pass elif (col & C3): # ch2 scale knob pass elif (col & C4): # ch4 scale knob pass elif (col & C5): # ch3 if (Scope.Timebase.mode[0:1] != b'X'): # only channels 1/2 active in XY mode if (not Scope.Channel3.enabled.value): Scope.Channel3.enable() ActiveMenu.disable() ActiveMenu = Scope.Channel3.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Channel3.enabled.value and not Scope.Channel3.Menu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Channel3.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Channel3.enabled.value and Scope.Channel3.Menu.is_active): Scope.Channel3.disable() ActiveMenu.disable() elif (col & C6): # ch4 if (Scope.Timebase.mode[0:1] != b'X'): # only channels 1/2 active in XY mode if (not Scope.Channel4.enabled.value): Scope.Channel4.enable() ActiveMenu.disable() ActiveMenu = Scope.Channel4.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Channel4.enabled.value and not Scope.Channel4.Menu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Channel4.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Channel4.enabled.value and Scope.Channel4.Menu.is_active): Scope.Channel4.disable() ActiveMenu.disable() elif (row & R6): if (col & C1): # ch1 if (not Scope.Channel1.enabled.value): Scope.Channel1.enable() ActiveMenu.disable() ActiveMenu = Scope.Channel1.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Channel1.enabled.value and not Scope.Channel1.Menu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Channel1.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Channel1.enabled.value and Scope.Channel1.Menu.is_active): if (Scope.Timebase.mode[0:1] != b'X'): # can't disable channel 1 in xy mode Scope.Channel1.disable() ActiveMenu.disable() elif (col & C2): # ch2 if (not Scope.Channel2.enabled.value): Scope.Channel2.enable() ActiveMenu.disable() ActiveMenu = Scope.Channel2.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Channel2.enabled.value and not Scope.Channel2.Menu.is_active): ActiveMenu.disable() ActiveMenu = Scope.Channel2.Menu update_select_funcs() ActiveMenu.enable() ActiveMenu.display_menu() elif (Scope.Channel2.enabled.value and Scope.Channel2.Menu.is_active): if (Scope.Timebase.mode[0:1] != b'X'): # can't disable channel 2 in xy mode Scope.Channel2.disable() ActiveMenu.disable() elif (col & C3): #ch1 offset knob Scope.Channel1.zero_offset() elif (col & C4): # ch2 offset knob Scope.Channel2.zero_offset() elif (col & C5): # ch3 offset knob Scope.Channel3.zero_offset() elif (col & C6): # ch4 offset knob Scope.Channel4.zero_offset() # Set board power pwr_en = DigitalOutputDevice(5) pwr_fault = DigitalInputDevice(6, pull_up=True) pwr_fault.when_activated = disable_power enable_power() # Set up SPI and interrupt pins spi = spidev.SpiDev() # in case bit banging were necessary #cs0 = DigitalOutputDevice( 8, active_high=False) #cs1 = DigitalOutputDevice( 7, active_high=False) cs2 = DigitalOutputDevice(12, active_high=False) interrupt1 = DigitalInputDevice(13) interrupt2 = DigitalInputDevice(16) # cut trace on board and rerouted #interrupt3 = DigitalInputDevice(19) spi_reset = DigitalOutputDevice(19, active_high=False) interrupt4 = DigitalInputDevice(20) interrupt5 = DigitalInputDevice(26) interrupt6 = DigitalInputDevice(21) # Set up LCD lcd = CharLCD( pin_rs=25, pin_rw=24, pin_e=22, pins_data=[23, 27, 17, 18], cols=20, rows=4, numbering_mode=GPIO.BCM, auto_linebreaks = False, charmap = 'A02') up_arrow = ( 0b00000, 0b00000, 0b00100, 0b00100, 0b01110, 0b01110, 0b11111, 0b00000 ) lcd.create_char(0, up_arrow) down_arrow = ( 0b00000, 0b00000, 0b11111, 0b01110, 0b01110, 0b00100, 0b00100, 0b00000 ) lcd.create_char(1, down_arrow) bklt_en = PWMOutputDevice(4) bklt_fault = DigitalInputDevice(2, pull_up=True) bklt_fault.when_activated = disable_backlight bklt_en.on() if (SCOPELESS): class DummySocket: def sendall(self, data): return def close(self): return Sock = DummySocket() else: # Set up socket to scope # Code provided by Agilent/Keysight with minor modifications remote_ip = "169.254.254.254" port = 5024 #create an AF_INET, STREAM socket (TCP) Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #NODELAY turns of Nagle improves chatty performance Sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 0) if maxsize > 2**32: time = struct.pack(str("ll"), int(1), int(0)) else: time = struct.pack(str("ii"), int(1), int(0)) Sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, time) #Connect to remote server while True: try: print("Attempting to connect") lcd.clear() lcd.write_string("Trying to connect...\r\n") lcd.write_string("IP: " + remote_ip + '\r\n') lcd.write_string("Port: " + str(port) + '\r\n') Sock.connect((remote_ip , port)) break except OSError as e: # wait and try to connect again print(e) print("Unable to connect, trying again in 30s") lcd.clear() lcd.write_string("Unable to connect...\r\n") lcd.write_string("Trying again in ") for i in range(1, 30): lcd.cursor_pos = (1,16) lcd.write_string(str(30-i) + "s") if (30-i == 9): lcd.cursor_pos = (1,18) lcd.write(BLANK) sleep(1) print ('Socket Connected to ip ' + remote_ip) lcd.clear() lcd.write_string("Connected!") sleep(1) print_reply() # greeting message def main(): init_spi() init_encoders() lcd.clear() print("initialized") global ActiveMenu ActiveMenu.enable() ActiveMenu.display_menu() try: c = 0 while True: # drive button matrix columns if (c >= 6): c = 0 drive_col = ~(1 << c) c += 1 spi.open(0,0) spi.mode = SPI_MODE spi.max_speed_hz = SPI_RATE to_send = [SPI_WRITE, OLATA, drive_col] cs2.on() spi.xfer2(to_send) cs2.off() if (interrupt4.value): # button pressed to_send = [SPI_READ, INTFB] cs2.on() spi.xfer2(to_send) int_flag = spi.readbytes(1) cs2.off() sleep(DEBOUNCE) # debounce to_send = [SPI_READ, GPIOB] cs2.on() spi.xfer2(to_send) button_io = spi.readbytes(1) cs2.off() to_send = [SPI_READ, INTCAPB, 0x00] cs2.on() spi.xfer(to_send) cs2.off() if (int_flag[0] & button_io[0] > 0): # real press release = button_io to_send = [SPI_READ, GPIOB] cs2.on() spi.xfer2(to_send) while(release[0] != 0): # wait until release release = spi.readbytes(1) sleep(0.01) cs2.off() button_press(button_io[0], ~drive_col) # perform action spi.close() # check for encoder change if (interrupt5.value): EncoderBank0A.update_encoders() if (interrupt6.value): EncoderBank0B.update_encoders() if (interrupt1.value): EncoderBank1A.update_encoders() if (interrupt2.value): EncoderBank1B.update_encoders() except Exception as e: # restart the program if anything goes wrong print(e) # (usually happens when string parsing) ActiveMenu.disable() lcd.clear() lcd.write_string("An unexpected error\r\noccurred.\r\n\nRestarting...") sleep(3) disable_power() disable_backlight() Sock.close() GPIO.cleanup() execv(__file__, argv) class ToggleSetting: # used for toggle menus def __init__(self, bool_value): self.value = bool_value class MenuItem: text = "" def __init__(self, text): self.text = text def select(self): return class Menu: is_active = False def enable(self): raise NotImplementedError def disable(self): raise NotImplementedError def display_menu(self): raise NotImplementedError def display_cursor(self): raise NotImplementedError def increment_cursor(self): raise NotImplementedError def decrement_cursor(self): raise NotImplementedError def select(self): raise NotImplementedError def back(self): raise NotImplementedError class BlankMenu(Menu): def enable(self): return def disable(self): return def display_menu(self): lcd.clear() def display_cursor(self): return def increment_cursor(self): return def decrement_cursor(self): return def select(self): return def back(self): return class ToggleMenu(Menu): text = "" options_set = False is_active = False def __init__(self, text): super().__init__() self.text = text def set_options(self, option1, option2, setting): self.option1 = option1 self.option2 = option2 self.setting = setting self.options_set = True def enable(self): if (self.options_set): self.is_active = True def disable(self): if (self.is_active): self.is_active = False lcd.clear() def display_menu(self): if (self.is_active and self.options_set): lcd.clear() lcd.write_string(self.text) lcd.cursor_pos = (1,2) lcd.write_string(self.option1.text) lcd.cursor_pos = (2,2) lcd.write_string(self.option2.text) if (self.setting.value): lcd.cursor_pos = (1,1) lcd.write(ACTIVE) else: lcd.cursor_pos = (2,1) lcd.write(ACTIVE) def display_cursor(self): return def increment_cursor(self): return def decrement_cursor(self): return def select(self): if (not self.is_active): self.container.disable() global ActiveMenu ActiveMenu = self update_select_funcs() self.enable() self.display_menu() else: if (not self.setting.value): self.option1.select() else: self.option2.select() self.display_menu() def back(self): if (self.is_active): self.disable() global ActiveMenu ActiveMenu = self.container update_select_funcs() self.container.enable() self.container.display_menu() class ListMenu(Menu): cursor = 0 start_index = 0 max_index = -1 is_active = False text = "" def __init__(self): super().__init__() self.menu_items = [] def set_text(self, text): self.text = text def set_menu(self, menu_items): self.menu_items = menu_items self.max_index = len(self.menu_items) - 1 for x in menu_items: x.container = self def enable(self): if(self.max_index >= 0): self.start_index = 0 self.cursor = 0 self.is_active = True def disable(self): if(self.is_active): self.is_active = False lcd.clear() def display_menu(self): if (self.is_active and self.max_index >= 0): lcd.clear() for i in range(self.start_index, self.start_index + 4): if (i <= self.max_index): lcd.write_string(str(i + 1) + ".") lcd.write_string(self.menu_items[i].text) lcd.crlf() if (self.start_index > 0): lcd.cursor_pos = (0,19) lcd.write(UP_ARROW) if (self.start_index + 3 < self.max_index): lcd.cursor_pos = (3,19) lcd.write(DOWN_ARROW) self.display_cursor() def display_cursor(self): if (self.is_active and self.max_index >= 0): lcd.cursor_pos = (self.cursor - self.start_index, 18) lcd.write(CURSOR) def increment_cursor(self): if (self.is_active and self.cursor < self.max_index): self.cursor += 1 if (self.start_index < self.cursor - 3): self.start_index += 1 self.display_menu() else: lcd.cursor_pos = (self.cursor - 1 - self.start_index, 18) lcd.write(BLANK) self.display_cursor() def decrement_cursor(self): if (self.is_active and self.cursor > 0): self.cursor -= 1 if (self.start_index > self.cursor): self.start_index = self.cursor self.display_menu() else: lcd.cursor_pos = (self.cursor + 1 - self.start_index, 18) lcd.write(BLANK) self.display_cursor() def select(self): if (not self.is_active): self.container.disable() global ActiveMenu ActiveMenu = self update_select_funcs() self.enable() self.display_menu() else: self.menu_items[self.cursor].select() self.display_menu() def back(self): if (self.is_active): self.disable() global ActiveMenu ActiveMenu = self.container update_select_funcs() self.container.enable() self.container.display_menu() # with regards to the classes used within Scope, # a fair amount of refactoring can be done # e.g.: - For functions that modify the same parameter, # have them call a function for common code as in Measure # - Remove "SCOPELESS" clauses for functions that do not parse replies # - Formatting, naming convention, unused/unnecessary variables(?) # - Add a "send_cmd" function to Scope to eliminate all of the extra # "Sock.sendall(cmd)" "sleep(CMD_WAIT)" lines class Scope: # state modeling/commands def __init__(self): self.Trigger = Trigger(self) self.Cursor = Cursor(self) self.Measure = Measure() self.Timebase = Timebase() self.Channel1 = Channel(1) self.Channel2 = Channel(2) self.Channel3 = Channel(3) self.Channel4 = Channel(4) self.channels = [self.Channel1, self.Channel2, self.Channel3, self.Channel4] self.get_state() def get_state(self): if (not SCOPELESS): for c in self.channels: c.get_state() self.Timebase.get_state() self.Trigger.get_state() self.Cursor.get_state() class Channel: # implement: probe attenuation, vernier, units scale_base_b = b'+5' scale_base = 5 scale_exp_b = b'+0' scale_exp = 0 scale = 5 channel_range = 40 offset = 0 offset_b = b'+0E+0' def __init__(self, number): if (number >=1 and number <= 4): self.number = number self.enabled = ToggleSetting(True) self.ac_coupling = ToggleSetting(False) self.high_input_imped = ToggleSetting(True) self.bw_limit = ToggleSetting(False) self.inverted = ToggleSetting(False) # Menus associated with each channel CouplingMenu = ToggleMenu("Coupling") ACCoupling = MenuItem("AC") ACCoupling.select = self.set_ac_coupling DCCoupling = MenuItem("DC") DCCoupling.select = self.set_dc_coupling CouplingMenu.set_options(ACCoupling, DCCoupling, self.ac_coupling) ImpedanceMenu = ToggleMenu("Input Z") OneMeg = MenuItem("1 MOhm") OneMeg.select = self.set_impedance_high Fifty = MenuItem("50 Ohm") Fifty.select = self.set_impedance_low ImpedanceMenu.set_options(OneMeg, Fifty, self.high_input_imped) BWLimitMenu = ToggleMenu("Bandwidth Limit") BWLimitOn = MenuItem("On") BWLimitOn.select = self.set_bw_limit BWLimitOff = MenuItem("Off") BWLimitOff.select = self.unset_bw_limit BWLimitMenu.set_options(BWLimitOn, BWLimitOff, self.bw_limit) InvertMenu = ToggleMenu("Invert") InvertOn = MenuItem("On") InvertOn.select = self.set_invert InvertOff = MenuItem("Off") InvertOff.select = self.unset_invert InvertMenu.set_options(InvertOn, InvertOff, self.inverted) #ProbeSettingsMenu = MenuItem("Probe settings") #implement ClearProtection = MenuItem("Clear protection") ClearProtection.select = self.clear_protection ChannelMenuItems = [CouplingMenu, ImpedanceMenu, BWLimitMenu, InvertMenu, ClearProtection] #, ProbeSettingsMenu] self.Menu = ListMenu() self.Menu.set_menu(ChannelMenuItems) Menu.container = BlankMenu() else: raise ValueError('Invalid number used to initialize Channel class') def get_state(self): if (not SCOPELESS): cmd = b'CHAN' + str(self.number).encode() + b':DISP?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] if (reply[0:1] == b'0'): self.enabled.value = False elif (reply[0:1] == b'1'): self.enabled.value = True cmd = b'CHAN' + str(self.number).encode() + b':SCAL?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] num_end = reply.index(b'E') self.scale_base_b = reply[:num_end] self.scale_exp_b = reply[num_end+1:] self.scale_base = ascii_to_num(self.scale_base_b) self.scale_exp = ascii_to_num(self.scale_exp_b) self.scale = self.scale_base * 10 ** self.scale_exp self.channel_range = self.scale * 8 cmd = b'CHAN' + str(self.number).encode() + b':OFFS?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.offset_b = reply base_end = reply.index(b'E') base = reply[:base_end] exp = reply[base_end+1:] base = ascii_to_num(base) exp = ascii_to_num(exp) self.offset = base * 10 ** exp cmd = b'CHAN' + str(self.number).encode() + b':COUP?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] if (reply[0:1] == b'D'): self.ac_coupling.value = False elif (reply[0:1] == b'A'): self.ac_coupling.value = True cmd = b'CHAN' + str(self.number).encode() + b':IMP?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] if (reply[0:1] == b'O'): self.high_input_imped.value = True elif (reply[0:1] == b'F'): self.high_input_imped.value = False cmd = b'CHAN' + str(self.number).encode() + b':BWL?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] if (reply[0:1] == b'1'): self.bw_limit.value = True elif (reply[0:1] == b'0'): self.bw_limit.value = False cmd = b'CHAN' + str(self.number).encode() + b':INV?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] if (reply[0:1] == b'1'): self.inverted.value = True elif (reply[0:1] == b'0'): self.inverted.value = False def enable(self): if (not SCOPELESS): cmd = b':CHAN' + str(self.number).encode() + b':DISP 1\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.enabled.value = True def disable(self): if (not SCOPELESS): cmd = b':CHAN' + str(self.number).encode() + b':DISP 0\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.enabled.value = False def zero_offset(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode self.offset = 0 cmd = b'CHAN' + str(self.number).encode() + b':OFFS +0E+0V\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def clear_protection(self): if (self.enabled.value): cmd = b'CHAN' + str(self.number).encode() + b':PROT:CLE\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def cw_scale(self): # deal with probe attenuation factor here # fine adjustment? if (not SCOPELESS and self.enabled.value and self.scale < 5): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode if (self.scale_base_b[1:2] == b'1'): self.scale_base = self.scale_base * 2 self.offset = self.offset * 2 elif (self.scale_base_b[1:2] == b'2'): self.scale_base = self.scale_base * 2.5 self.offset = self.offset * 2.5 elif (self.scale_base_b[1:2] == b'5'): self.scale_base = self.scale_base * 2 / 10 self.offset = self.offset * 2 / 10 self.scale_exp += 1 #update state self.scale = self.scale_base * 10 ** self.scale_exp self.channel_range = self.scale * 8 self.scale_base_b = num_to_ascii(self.scale_base, False) self.scale_exp_b = num_to_ascii(self.scale_exp, True) cmd = b'CHAN' + str(self.number).encode() + b':SCAL ' + self.scale_base_b + b'E' + self.scale_exp_b + b'V\r\n' Sock.sendall(cmd) def ccw_scale(self): # deal with probe attenuation factor here # fine adjustment? if (not SCOPELESS and self.enabled.value and self.scale > 0.002): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode if (self.scale_base_b[1:2] == b'1'): self.scale_base = self.scale_base / 2 * 10 self.offset = self.offset * 2 / 10 self.scale_exp -= 1 elif (self.scale_base_b[1:2] == b'2'): self.scale_base = self.scale_base / 2 self.offset = self.offset / 2 elif (self.scale_base_b[1:2] == b'5'): self.scale_base = self.scale_base * 2 / 5 self.offset = self.offset * 2 / 5 #update state self.scale = self.scale_base * 10 ** self.scale_exp self.channel_range = self.scale * 8 self.scale_base_b = num_to_ascii(self.scale_base, False) self.scale_exp_b = num_to_ascii(self.scale_exp, True) cmd = b'CHAN' + str(self.number).encode() + b':SCAL ' + self.scale_base_b + b'E' + self.scale_exp_b + b'V\r\n' Sock.sendall(cmd) def cw_offset(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode step = 0.125 * self.scale self.offset -= step cmd = b'CHAN' + str(self.number).encode() + b':OFFS ' + "{:.6E}".format(self.offset).encode() + b'V\r\n' Sock.sendall(cmd) def ccw_offset(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode step = 0.125 * self.scale self.offset += step cmd = b'CHAN' + str(self.number).encode() + b':OFFS ' + "{:.6E}".format(self.offset).encode() + b'V\r\n' Sock.sendall(cmd) def set_ac_coupling(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode cmd = b'CHAN' + str(self.number).encode() + b':COUP AC\r\n' Sock.sendall(cmd) self.ac_coupling.value = True def set_dc_coupling(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode cmd = b'CHAN' + str(self.number).encode() + b':COUP DC\r\n' Sock.sendall(cmd) self.ac_coupling.value = False def set_impedance_high(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode cmd = b'CHAN' + str(self.number).encode() + b':IMP ONEM\r\n' Sock.sendall(cmd) self.high_input_imped.value = True def set_impedance_low(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode cmd = b'CHAN' + str(self.number).encode() + b':IMP FIFT\r\n' Sock.sendall(cmd) self.high_input_imped.value = False def set_bw_limit(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode cmd = b'CHAN' + str(self.number).encode() + b':BWL 1\r\n' Sock.sendall(cmd) self.bw_limit.value = True def unset_bw_limit(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode cmd = b'CHAN' + str(self.number).encode() + b':BWL 0\r\n' Sock.sendall(cmd) self.bw_limit.value = False def set_invert(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode cmd = b'CHAN' + str(self.number).encode() + b':INV 1\r\n' Sock.sendall(cmd) self.inverted.value = True def unset_invert(self): if (not SCOPELESS and self.enabled.value): if (not (Scope.Timebase.mode[0:1] == b'X' and (self.number == 3 or self.number == 4))): # only channels 1/2 active in XY mode cmd = b'CHAN' + str(self.number).encode() + b':INV 0\r\n' Sock.sendall(cmd) self.inverted.value = False class Timebase: # implement: vernier, window scale/position mode = b'MAIN' reference = b'CENT' scale_base_b = b'+5' scale_base = 5 scale_exp_b = b'+0' scale_exp = 0 scale = 5 position = 0 position_b = b'+0E+0' def __init__(self): MainMode = MenuItem("Main") MainMode.select = self.set_mode_main WindowMode = MenuItem("Window") WindowMode.select = self.set_mode_window XYMode = MenuItem("XY") XYMode.select = self.set_mode_xy RollMode = MenuItem("Roll") RollMode.select = self.set_mode_roll ModeMenuItems = [MainMode, WindowMode, XYMode, RollMode] ModeMenu = ListMenu() ModeMenu.set_menu(ModeMenuItems) ModeMenu.text = "Mode" RefLeft = MenuItem("Left") RefLeft.select = self.set_ref_left RefCent = MenuItem("Center") RefCent.select = self.set_ref_center RefRight = MenuItem("Right") RefRight.select = self.set_ref_right RefMenuItems = [RefLeft, RefCent, RefRight] RefMenu = ListMenu() RefMenu.set_menu(RefMenuItems) RefMenu.text = "Reference" TimebaseMenuItems = [ModeMenu, RefMenu] self.Menu = ListMenu() self.Menu.set_menu(TimebaseMenuItems) self.Menu.container = BlankMenu() def get_state(self): if (not SCOPELESS): cmd = b'TIM:MODE?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.mode = reply cmd = b'TIM:REF?\r\n' Sock.sendall(cmd) sleep(2*CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.reference = reply cmd = b'TIM:SCAL?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] num_end = reply.index(b'E') self.scale_base_b = reply[:num_end] self.scale_exp_b = reply[num_end+1:] self.scale_base = ascii_to_num(self.scale_base_b) self.scale_exp = ascii_to_num(self.scale_exp_b) self.scale = self.scale_base * 10 ** self.scale_exp cmd = b'TIM:POS?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.position_b = reply base_end = reply.index(b'E') base = reply[:base_end] exp = reply[base_end+1:] base = ascii_to_num(base) exp = ascii_to_num(exp) self.position = base * 10 ** exp def zero_delay(self): if (not SCOPELESS): self.position = 0 cmd = b'TIM:POS +0E+0\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def cw_delay(self): if (not SCOPELESS): step = 0.125 * self.scale self.position -= step cmd = b'TIM:POS ' + "{:.6E}".format(self.position).encode() + b'\r\n' Sock.sendall(cmd) def ccw_delay(self): if (not SCOPELESS): step = 0.125 * self.scale self.position += step cmd = b'TIM:POS ' + "{:.6E}".format(self.position).encode() + b'\r\n' Sock.sendall(cmd) def cw_scale(self): # fine adjustment? if (not SCOPELESS and self.mode[0:1] != b'X' and self.scale < 50): if (self.scale_base_b[1:2] == b'1'): self.scale_base = self.scale_base * 2 elif (self.scale_base_b[1:2] == b'2'): self.scale_base = self.scale_base * 2.5 elif (self.scale_base_b[1:2] == b'5'): self.scale_base = self.scale_base * 2 / 10 self.scale_exp += 1 #update state self.scale = self.scale_base * 10 ** self.scale_exp self.scale_base_b = num_to_ascii(self.scale_base, False) self.scale_exp_b = num_to_ascii(self.scale_exp, True) cmd = b'TIM:SCAL ' + self.scale_base_b + b'E' + self.scale_exp_b + b'\r\n' Sock.sendall(cmd) def ccw_scale(self): # fine adjustment? min_scale = 500 * (10 ** -12) if (self.mode[0:1] != b'R') else 100 * (10 ** -3) if (not SCOPELESS and self.mode[0:1] != b'X' and self.scale > min_scale): if (self.scale_base_b[1:2] == b'1'): self.scale_base = self.scale_base / 2 * 10 self.scale_exp -= 1 elif (self.scale_base_b[1:2] == b'2'): self.scale_base = self.scale_base / 2 elif (self.scale_base_b[1:2] == b'5'): self.scale_base = self.scale_base * 2 / 5 #update state self.scale = self.scale_base * 10 ** self.scale_exp self.scale_base_b = num_to_ascii(self.scale_base, False) self.scale_exp_b = num_to_ascii(self.scale_exp, True) cmd = b'TIM:SCAL ' + self.scale_base_b + b'E' + self.scale_exp_b + b'\r\n' Sock.sendall(cmd) def set_mode_main(self): if (not SCOPELESS and not self.mode[0:1] == b'M'): self.mode = b'MAIN' cmd = b'TIM:MODE '+ self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_mode_window(self): if (not SCOPELESS and not self.mode[0:1] == b'W'): self.mode = b'WIND' cmd = b'TIM:MODE '+ self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_mode_xy(self): if (not SCOPELESS and not self.mode[0:1] == b'X'): self.mode = b'XY' cmd = b'TIM:MODE '+ self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_mode_roll(self): if (not SCOPELESS and not self.mode[0:1] == b'R'): self.mode = b'ROLL' cmd = b'TIM:MODE '+ self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_state() def set_ref_left(self): if (not SCOPELESS and not (self.mode[0:1] == b'X' or self.mode[0:1] == b'R')): self.reference = b'LEFT' cmd = b'TIM:REF '+ self.reference + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_ref_center(self): if (not SCOPELESS and not (self.mode[0:1] == b'X' or self.mode[0:1] == b'R')): self.reference = b'CENT' cmd = b'TIM:REF '+ self.reference + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_ref_right(self): if (not SCOPELESS and not (self.mode[0:1] == b'X' or self.mode[0:1] == b'R')): self.reference = b'RIGH' cmd = b'TIM:REF '+ self.reference + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) class Trigger: # implement: holdoff, external probe sweep = b'AUTO' mode = b'EDGE' source = b'CHAN1' source_range = 40 level = 0 #holdoff = 0 def __init__(self, Scope): self.Scope = Scope self.HFReject = ToggleSetting(False) self.NReject = ToggleSetting(False) self.SweepIsAuto = ToggleSetting(True) # Most of these menus depend upon using 'edge' type triggering # There are many other trigger types available but this was most important ACCoupling = MenuItem("AC") ACCoupling.select = self.set_edge_coupling_ac DCCoupling = MenuItem("DC") DCCoupling.select = self.set_edge_coupling_dc LFCoupling = MenuItem("LF reject (50kHz)") LFCoupling.select = self.set_edge_coupling_lf CouplingMenuItems = [ACCoupling, DCCoupling, LFCoupling] CouplingMenu = ListMenu() CouplingMenu.set_menu(CouplingMenuItems) CouplingMenu.set_text("Coupling") RejectOff = MenuItem("Off") RejectOff.select = self.set_reject_off RejectLF = MenuItem("Low freq (50kHz)") RejectLF.select = self.set_reject_lf RejectHF = MenuItem("High freq (50kHz)") RejectHF.select = self.set_reject_hf RejectMenuItems = [RejectOff, RejectLF, RejectHF] RejectMenu = ListMenu() RejectMenu.set_menu(RejectMenuItems) RejectMenu.set_text("Reject") SlopePositive = MenuItem("Positive") SlopePositive.select = self.set_slope_positive SlopeNegative = MenuItem("Negative") SlopeNegative.select = self.set_slope_negative SlopeEither = MenuItem("Either") SlopeEither.select = self.set_slope_either SlopeAlternate = MenuItem("Alternate") SlopeAlternate.select = self.set_slope_alternate SlopeMenuItems = [SlopePositive, SlopeNegative, SlopeEither, SlopeAlternate] SlopeMenu = ListMenu() SlopeMenu.set_menu(SlopeMenuItems) SlopeMenu.set_text("Slope") SourceCh1 = MenuItem("Channel 1") SourceCh1.select = self.set_source_ch1 SourceCh2 = MenuItem("Channel 2") SourceCh2.select = self.set_source_ch2 SourceCh3 = MenuItem("Channel 3") SourceCh3.select = self.set_source_ch3 SourceCh4 = MenuItem("Channel 4") SourceCh4.select = self.set_source_ch4 #SourceExternal = MenuItem("External") #SourceExternal.select = self.set_source_external SourceLine = MenuItem("Line") SourceLine.select = self.set_source_line SourceMenuItems = [SourceCh1, SourceCh2, SourceCh3, SourceCh4, SourceLine] #, SourceExternal] SourceMenu = ListMenu() SourceMenu.set_menu(SourceMenuItems) SourceMenu.set_text("Source") """ HFRejectMenu = ToggleMenu("HF Reject (50 kHz)") HFRejectOn = MenuItem("On") HFRejectOn.select = self.enable_HFRej HFRejectOff = MenuItem("Off") HFRejectOff.select = self.disable_HFRej HFRejectMenu.set_options(HFRejectOn, HFRejectOff, self.HFReject) """ NRejectMenu = ToggleMenu("Noise Reject") NRejectOn = MenuItem("On") NRejectOn.select = self.enable_NRej NRejectOff = MenuItem("Off") NRejectOff.select = self.disable_NRej NRejectMenu.set_options(NRejectOn, NRejectOff, self.NReject) SweepMenu = ToggleMenu("Sweep") SweepAuto = MenuItem("Auto") SweepAuto.select = self.set_sweep_auto SweepNormal = MenuItem("Normal") SweepNormal.select = self.set_sweep_normal SweepMenu.set_options(SweepAuto, SweepNormal, self.SweepIsAuto) TriggerMenuItems = [SourceMenu, SweepMenu, CouplingMenu, RejectMenu, NRejectMenu, SlopeMenu] self.Menu = ListMenu() self.Menu.set_menu(TriggerMenuItems) Menu.container = BlankMenu() def get_state(self): if (not SCOPELESS): """ cmd = b':TRIG:HFR?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] if (reply[0:1] == b'0'): self.HFReject.value = False elif (reply[0:1] == b'1'): self.HFReject.value = True """ cmd = b':TRIG:NREJ?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] if (reply[0:1] == b'0'): self.NReject.value = False elif (reply[0:1] == b'1'): self.NReject.value = True cmd = b':TRIG:MODE?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.mode = reply cmd = b':TRIG:SWE?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.sweep = reply cmd = b':TRIG:EDGE:SOUR?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.source = reply self.get_source_range() self.get_level() def get_source_range(self): if (self.source[4:5] == b'1'): self.source_range = self.Scope.Channel1.channel_range if (self.source[4:5] == b'2'): self.source_range = self.Scope.Channel2.channel_range if (self.source[4:5] == b'3'): self.source_range = self.Scope.Channel3.channel_range if (self.source[4:5] == b'4'): self.source_range = self.Scope.Channel4.channel_range elif (self.source[0:1] == b'E'): cmd = self.source + b':RANG?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if (not SCOPELESS): reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] num_end = reply.index(b'E') range_base_b = reply[:num_end] range_exp_b = reply[num_end+1:] range_base = ascii_to_num(range_base_b) range_exp = ascii_to_num(range_exp_b) self.source_range = range_base * 10 ** range_exp def get_level(self): cmd = b'TRIG:EDGE:LEV?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if (not SCOPELESS): reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.offset_b = reply base_end = reply.index(b'E') base = reply[:base_end] exp = reply[base_end+1:] base = ascii_to_num(base) exp = ascii_to_num(exp) self.level = base * 10 ** exp def cw_level(self): if (self.source[0:1] == b'C' or self.source[0:1] == b'E'): self.get_source_range() step = 0.01 * self.source_range self.level += step if (self.source[0:1] == b'C'): if(self.level > self.source_range * 0.75): self.level = self.source_range * 0.75 cmd = b'TRIG:EDGE:LEV ' + "{:.6E}".format(self.level).encode() + b'V\r\n' Sock.sendall(cmd) elif (self.source[0:1] == b'E'): if (self.level > self.source_range * 1): self.level = self.source_range * 1 cmd = b'TRIG:EDGE:LEV ' + "{:.6E}".format(self.level).encode() + b'V\r\n' Sock.sendall(cmd) def ccw_level(self): if (self.source[0:1] == b'C' or self.source[0:1] == b'E'): self.get_source_range() step = 0.01 * self.source_range self.level -= step if (self.source[0:1] == b'C'): if(self.level < self.source_range * -0.75): self.level = self.source_range * -0.75 cmd = b'TRIG:EDGE:LEV ' + "{:.6E}".format(self.level).encode() + b'V\r\n' Sock.sendall(cmd) elif (self.source[0:1] == b'E'): if (self.level < self.source_range * -1): self.level = self.source_range * -1 cmd = b'TRIG:EDGE:LEV ' + "{:.6E}".format(self.level).encode() + b'V\r\n' Sock.sendall(cmd) """ def enable_HFRej(self): self.HFReject.value = True cmd = b':TRIG:HFR 1\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def disable_HFRej(self): self.HFReject.value = False cmd = b':TRIG:HFR 0\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) """ def enable_NRej(self): self.NReject.value = True cmd = b':TRIG:NREJ 1\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def disable_NRej(self): self.NReject.value = False cmd = b':TRIG:NREJ 0\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) """ def set_mode_edge(self): self.mode = b'EDGE' cmd = b':TRIG:MODE ' + self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) """ def set_sweep_auto(self): self.SweepIsAuto.value = True self.sweep = b'AUTO' cmd = b':TRIG:SWE ' + self.sweep + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_sweep_normal(self): self.SweepIsAuto.value = False self.sweep = b'NORM' cmd = b':TRIG:SWE ' + self.sweep + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_edge_coupling_ac(self): cmd = b':TRIG:EDGE:COUP AC\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_edge_coupling_dc(self): cmd = b':TRIG:EDGE:COUP DC\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_edge_coupling_lf(self): cmd = b':TRIG:EDGE:COUP LFR\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_reject_off(self): cmd = b':TRIG:EDGE:REJ OFF\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_reject_lf(self): cmd = b':TRIG:EDGE:REJ LFR\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_reject_hf(self): cmd = b':TRIG:EDGE:REJ HFR\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_slope_positive(self): cmd = b':TRIG:EDGE:SLOP POS\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_slope_negative(self): cmd = b':TRIG:EDGE:SLOP NEG\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_slope_either(self): cmd = b':TRIG:EDGE:SLOP EITH\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_slope_alternate(self): cmd = b':TRIG:EDGE:SLOP ALT\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_source_ch1(self): self.source = b'CHAN1' cmd = b':TRIG:EDGE:SOUR ' + self.source + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_source_range() self.get_level() def set_source_ch2(self): self.source = b'CHAN2' cmd = b':TRIG:EDGE:SOUR ' + self.source + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_source_range() self.get_level() def set_source_ch3(self): self.source = b'CHAN3' cmd = b':TRIG:EDGE:SOUR ' + self.source + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_source_range() self.get_level() def set_source_ch4(self): self.source = b'CHAN4' cmd = b':TRIG:EDGE:SOUR ' + self.source + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_source_range() self.get_level() def set_source_external(self): self.source = b'EXT' cmd = b':TRIG:EDGE:SOUR ' + self.source + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_source_range() self.get_level() def set_source_line(self): self.source = b'LINE' cmd = b':TRIG:EDGE:SOUR ' + self.source + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.level = 0 class Cursor: # update appropriate functions for Math class mode = b'OFF' source1 = b'NONE' source2 = b'NONE' active_cursor = b'X1' cursor_position = 0 cursor_select = False def __init__(self, Scope): #update for math self.Scope = Scope # menus ModeOff = MenuItem("Off") ModeOff.select = self.set_mode_off ModeManual = MenuItem("Manual") ModeManual.select = self.set_mode_manual ModeMeasure = MenuItem("Measurement") ModeMeasure.select = self.set_mode_measurement ModeWaveform = MenuItem("Waveform") ModeWaveform.select = self.set_mode_waveform ModeMenuItems = [ModeOff, ModeManual, ModeMeasure, ModeWaveform] ModeMenu = ListMenu() ModeMenu.set_menu(ModeMenuItems) ModeMenu.set_text("Mode") CursorX1 = MenuItem("X1") CursorX1.select = self.set_cursor_x1 CursorY1 = MenuItem("Y1") CursorY1.select = self.set_cursor_y1 CursorX2 = MenuItem("X2") CursorX2.select = self.set_cursor_x2 CursorY2 = MenuItem("Y2") CursorY2.select = self.set_cursor_y2 ActiveCursorMenuItems = [CursorX1, CursorY1, CursorX2, CursorY2] self.ActiveCursorMenu = ListMenu() self.ActiveCursorMenu.set_menu(ActiveCursorMenuItems) self.ActiveCursorMenu.set_text("Select cursor") Source1Ch1 = MenuItem("Channel 1") Source1Ch1.select = self.set_source1_ch1 Source1Ch2 = MenuItem("Channel 2") Source1Ch2.select = self.set_source1_ch2 Source1Ch3 = MenuItem("Channel 3") Source1Ch3.select = self.set_source1_ch3 Source1Ch4 = MenuItem("Channel 4") Source1Ch4.select = self.set_source1_ch4 #Source1Func = MenuItem("Math") #Source1Func.select = self.set_source1_func Source1MenuItems = [Source1Ch1, Source1Ch2, Source1Ch3, Source1Ch4] #, Source1Func] Source1Menu = ListMenu() Source1Menu.set_menu(Source1MenuItems) Source1Menu.set_text("X1Y1 source") Source2Ch1 = MenuItem("Channel 1") Source2Ch1.select = self.set_source2_ch1 Source2Ch2 = MenuItem("Channel 2") Source2Ch2.select = self.set_source2_ch2 Source2Ch3 = MenuItem("Channel 3") Source2Ch3.select = self.set_source2_ch3 Source2Ch4 = MenuItem("Channel 4") Source2Ch4.select = self.set_source2_ch4 #Source2Func = MenuItem("Math") #Source2Func.select = self.set_source2_func Source2MenuItems = [Source2Ch1, Source2Ch2, Source2Ch3, Source2Ch4] #, Source2Func] Source2Menu = ListMenu() Source2Menu.set_menu(Source2MenuItems) Source2Menu.set_text("X2Y2 source") Zero = MenuItem("Zero cursor") Zero.select = self.zero_cursor CursorMenuItems = [ModeMenu, Zero, self.ActiveCursorMenu, Source1Menu, Source2Menu] self.Menu = ListMenu() self.Menu.set_menu(CursorMenuItems) self.Menu.container = BlankMenu() def get_state(self): if (not SCOPELESS): cmd = b'MARK:MODE?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.mode = reply self.get_cursor_pos() self.get_cursor_source() def zero_cursor(self): if (not (self.mode[0:1] == b'O')): suffix = b's' if (self.active_cursor[0:1] == b'Y'): #Y1, Y2 suffix = b'V' self.cursor_position = 0 cmd = b'MARK:' + self.active_cursor + b'P ' + "{:.6E}".format(self.cursor_position).encode() + suffix + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def cw_cursor(self): #update for math if (not (self.mode[0:1] == b'O')): if (self.cursor_select and self.ActiveCursorMenu.is_active): ActiveMenu.increment_cursor() else: suffix = b's' scale = self.Scope.Timebase.scale if (self.active_cursor[0:1] == b'Y'): #Y1, Y2 suffix = b'V' source = self.source1 if (self.active_cursor[1:2] == b'1'): source = self.source1 else: source = self.source2 if (source[0:1] == b'C'): if (source[4:5] == b'1'): scale = self.Scope.Channel1.scale elif (source[4:5] == b'2'): scale = self.Scope.Channel2.scale elif (source[4:5] == b'3'): scale = self.Scope.Channel3.scale elif (source[4:5] == b'4'): scale = self.Scope.Channel4.scale else: # scale = self.Scope.Math.scale pass step = 0.125 * scale self.cursor_position += step cmd = b'MARK:' + self.active_cursor + b'P ' + "{:.6E}".format(self.cursor_position).encode() + suffix + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def ccw_cursor(self): #update for math if (not (self.mode[0:1] == b'O')): if (self.cursor_select and self.ActiveCursorMenu.is_active): ActiveMenu.decrement_cursor() else: suffix = b's' scale = self.Scope.Timebase.scale if (self.active_cursor[0:1] == b'Y'): #Y1, Y2 suffix = b'V' source = self.source1 if (self.active_cursor[1:2] == b'1'): source = self.source1 else: source = self.source2 if (source[0:1] == b'C'): if (source[4:5] == b'1'): scale = self.Scope.Channel1.scale elif (source[4:5] == b'2'): scale = self.Scope.Channel2.scale elif (source[4:5] == b'3'): scale = self.Scope.Channel3.scale elif (source[4:5] == b'4'): scale = self.Scope.Channel4.scale else: # scale = self.Scope.Math.scale pass step = 0.125 * scale self.cursor_position -= step cmd = b'MARK:' + self.active_cursor + b'P ' + "{:.6E}".format(self.cursor_position).encode() + suffix + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def get_cursor_pos(self): if (not self.mode[0:1] == b'O'): cmd = b'MARK:' + self.active_cursor + b'P?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if (not SCOPELESS): reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] num_end = reply.index(b'E') pos_base_b = reply[:num_end] pos_exp_b = reply[num_end+1:] pos_base = ascii_to_num(pos_base_b) pos_exp = ascii_to_num(pos_exp_b) self.cursor_position = pos_base * 10 ** pos_exp def get_cursor_source(self): cmd = b'MARK:X1Y1?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if (not SCOPELESS): reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.source1 = reply cmd = b'MARK:X2Y2?\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if (not SCOPELESS): reply = get_reply() reply = reply[::-1] reply = reply[4:] start = reply.index(b'\n') reply = reply[:start] reply = reply[::-1] self.source2 = reply def set_mode_off(self): self.mode = b'OFF' cmd = b'MARK:MODE ' + self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_mode_manual(self): self.mode = b'MAN' cmd = b'MARK:MODE ' + self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_cursor_pos() self.get_cursor_source() def set_mode_measurement(self): self.mode = b'MEAS' cmd = b'MARK:MODE ' + self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_cursor_pos() self.get_cursor_source() def set_mode_waveform(self): self.mode = b'WAV' cmd = b'MARK:MODE ' + self.mode + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) self.get_cursor_pos() self.get_cursor_source() def set_cursor_x1(self): self.active_cursor = b'X1' self.get_cursor_pos() def set_cursor_y1(self): self.active_cursor = b'Y1' self.get_cursor_pos() def set_cursor_x2(self): self.active_cursor = b'X2' self.get_cursor_pos() def set_cursor_y2(self): self.active_cursor = b'Y2' self.get_cursor_pos() def set_source1_ch1(self): if(self.Scope.Channel1.enabled.value): self.source1 = b'CHAN1' cmd = b'MARK:X1Y1 ' + self.source1 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source1_ch2(self): if(self.Scope.Channel2.enabled.value): self.source1 = b'CHAN2' cmd = b'MARK:X1Y1 ' + self.source1 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source1_ch3(self): if(self.Scope.Channel3.enabled.value): self.source1 = b'CHAN3' cmd = b'MARK:X1Y1 ' + self.source1 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source1_ch4(self): if(self.Scope.Channel2.enabled.value): self.source1 = b'CHAN4' cmd = b'MARK:X1Y1 ' + self.source1 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source1_func(self): # update for Math if(False): self.source1 = b'FUNC' cmd = b'MARK:X1Y1 ' + self.source1 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source2_ch1(self): if(self.Scope.Channel1.enabled.value): self.source2 = b'CHAN1' cmd = b'MARK:X2Y2 ' + self.source2 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source2_ch2(self): if(self.Scope.Channel2.enabled.value): self.source2 = b'CHAN2' cmd = b'MARK:X2Y2 ' + self.source2 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source2_ch3(self): if(self.Scope.Channel3.enabled.value): self.source2 = b'CHAN3' cmd = b'MARK:X2Y2 ' + self.source2 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source2_ch4(self): if(self.Scope.Channel2.enabled.value): self.source2 = b'CHAN4' cmd = b'MARK:X2Y2 ' + self.source2 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() def set_source2_func(self): # update for Math if(False): self.source2 = b'FUNC' cmd = b'MARK:X2Y2 ' + self.source2 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) if(not (self.mode[0:1] == b'W')): self.mode = b'MAN' self.get_cursor_pos() class Measure: # update appropriate functions for Math class # add ability to change thresholds, other settings if needed source1 = b'CHAN1' source2 = b'CHAN2' def __init__(self): #update for math Clear = MenuItem("Clear") Clear.select = self.clear S1Ch1 = MenuItem("Channel 1") S1Ch1.select = self.set_source1_ch1 S1Ch2 = MenuItem("Channel 2") S1Ch2.select = self.set_source1_ch2 S1Ch3 = MenuItem("Channel 3") S1Ch3.select = self.set_source1_ch3 S1Ch4 = MenuItem("Channel 4") S1Ch4.select = self.set_source1_ch4 #S1Func = MenuItem("Math") #S1Func.select = self.set_source1_func Source1MenuItems = [S1Ch1, S1Ch2, S1Ch3, S1Ch4] #, S1Func] # external probe is also an option Source1 = ListMenu() Source1.set_menu(Source1MenuItems) Source1.set_text("Source 1") S2Ch1 = MenuItem("Channel 1") S2Ch1.select = self.set_source2_ch1 S2Ch2 = MenuItem("Channel 2") S2Ch2.select = self.set_source2_ch2 S2Ch3 = MenuItem("Channel 3") S2Ch3.select = self.set_source2_ch3 S2Ch4 = MenuItem("Channel 4") S2Ch4.select = self.set_source2_ch4 #S2Func = MenuItem("Math") #S2Func.select = self.set_source2_func Source2MenuItems = [S2Ch1, S2Ch2, S2Ch3, S2Ch4] #, S2Func] Source2 = ListMenu() Source2.set_menu(Source2MenuItems) Source2.set_text("Source 2") ResetStat = MenuItem("Reset") ResetStat.select = self.reset_statistics WindowMain = MenuItem("Main") WindowMain.select = self.set_window_main WindowZoom = MenuItem("Zoom") WindowZoom.select = self.set_window_zoom WindowAuto = MenuItem("Auto") WindowAuto.select = self.set_window_auto WindowMenuItems = [WindowMain, WindowZoom, WindowAuto] Window = ListMenu() Window.set_menu(WindowMenuItems) Window.set_text("Window") Counter = MenuItem("Counter") Counter.select = self.counter Delay = MenuItem("Delay") Delay.select = self.delay DutyCycle = MenuItem("Duty cycle") DutyCycle.select = self.duty_cycle FallTime = MenuItem("Fall time") FallTime.select = self.fall_time Frequency = MenuItem("Frequency") Frequency.select = self.frequency NPulseWidth = MenuItem("Neg p width") NPulseWidth.select = self.neg_pulse_width Overshoot = MenuItem("Overshoot") Overshoot.select = self.overshoot Period = MenuItem("Period") Period.select = self.period Phase = MenuItem("Phase") Phase.select = self.phase Preshoot = MenuItem("Preshoot") Preshoot.select = self.preshoot PulseWidth = MenuItem("Pulse width") PulseWidth.select = self.pulse_width RiseTime = MenuItem("Rise time") RiseTime.select = self.rise_time StdDev = MenuItem("Std dev") StdDev.select = self.std_dev VAmp = MenuItem("V amplitude") VAmp.select = self.v_amp VAvg = MenuItem("V average") VAvg.select = self.v_avg VBase = MenuItem("V base") VBase.select = self.v_base VMax = MenuItem("V max") VMax.select = self.v_max VMin = MenuItem("V min") VMin.select = self.v_min VPP = MenuItem("V peak-peak") VPP.select = self.v_pp VRatio = MenuItem("V ratio") VRatio.select = self.v_ratio VRMS = MenuItem("V RMS") VRMS.select = self.v_rms VTop = MenuItem("V top") VTop.select = self.v_top XMax = MenuItem("X max") XMax.select = self.x_max XMin = MenuItem("X min") XMin.select = self.x_min MeasureMenuItems = [Clear, ResetStat, Source1, Source2, Window, Counter, Delay, DutyCycle, FallTime, Frequency, NPulseWidth, Overshoot, Period, Phase, Preshoot, PulseWidth, RiseTime, StdDev, VAmp, VAvg, VBase, VMax, VMin, VPP, VRatio, VRMS, VTop, XMax, XMin] self.Menu = ListMenu() self.Menu.set_menu(MeasureMenuItems) self.Menu.container = BlankMenu() def clear(self): cmd = b':MEAS:CLE\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def reset_statistics(self): cmd = b':MEAS:STAT:RES\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_source1(self): cmd = b':MEAS:SOUR ' + self.source1 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_source2(self): cmd = b':MEAS:SOUR ' + self.source1 + b',' + self.source2 + b'\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_source1_ch1(self): self.source1 = b'CHAN1' self.set_source1() def set_source1_ch2(self): self.source1 = b'CHAN2' self.set_source1() def set_source1_ch3(self): self.source1 = b'CHAN3' self.set_source1() def set_source1_ch4(self): self.source1 = b'CHAN4' self.set_source1() def set_source1_func(self): self.source1 = b'FUNC' self.set_source1() def set_source2_ch1(self): self.source2 = b'CHAN1' self.set_source2() def set_source2_ch2(self): self.source2 = b'CHAN2' self.set_source2() def set_source2_ch3(self): self.source2 = b'CHAN3' self.set_source2() def set_source2_ch4(self): self.source2 = b'CHAN4' self.set_source2() def set_source2_func(self): self.source2 = b'FUNC' self.set_source2() def set_window_main(self): cmd = b':MEAS:WIND MAIN\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_window_zoom(self): cmd = b':MEAS:WIND ZOOM\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def set_window_auto(self): cmd = b':MEAS:WIND AUTO\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def counter(self): cmd = b':MEAS:COUN\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def delay(self): cmd = b':MEAS:DEL\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def duty_cycle(self): cmd = b':MEAS:DUTY\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def fall_time(self): cmd = b':MEAS:FALL\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def frequency(self): cmd = b':MEAS:FREQ\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def neg_pulse_width(self): cmd = b':MEAS:NWID\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def overshoot(self): cmd = b':MEAS:OVER\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def period(self): cmd = b':MEAS:PER\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def phase(self): cmd = b':MEAS:PHAS\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def preshoot(self): cmd = b':MEAS:PRES\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def pulse_width(self): cmd = b':MEAS:PWID\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def rise_time(self): cmd = b':MEAS:RIS\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def std_dev(self): cmd = b':MEAS:SDEV\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_amp(self): cmd = b':MEAS:VAMP\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_avg(self): cmd = b':MEAS:VAV\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_base(self): cmd = b':MEAS:VBAS\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_max(self): cmd = b':MEAS:VMAX\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_min(self): cmd = b':MEAS:VMIN\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_pp(self): cmd = b':MEAS:VPP\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_ratio(self): cmd = b':MEAS:VRAT\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_rms(self): cmd = b':MEAS:VRMS\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def v_top(self): cmd = b':MEAS:VTOP\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def x_max(self): cmd = b':MEAS:XMAX\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) def x_min(self): cmd = b':MEAS:XMIN\r\n' Sock.sendall(cmd) sleep(CMD_WAIT) class Encoder: a = 0 b = 0 ppr = 24 raw_count = 0 clockwise = False sensitivity = 1 # higher = less sensitive, modify for instances (e.g. select knob) count = 0 detent = False detent_max = 4 detent_count = 0 enabled = False def __init__(self, a_bit, b_bit): self.a_bit = a_bit self.b_bit = b_bit def action(self): if self.detent: if ((self.detent_count >= self.detent_max) != (self.detent_count <= -1 * self.detent_max)): self.detent_count = 0 if (self.clockwise): self.cw_action() else: self.ccw_action() else: if ((self.count >= self.sensitivity) != (self.count <= -1 * self.sensitivity)): self.count = 0 if (self.clockwise): self.cw_action() else: self.ccw_action() def adjust_count(self): if (self.raw_count == 0 and not self.clockwise): self.raw_count = self.ppr - 1 elif (self.raw_count == self.ppr - 1 and self.clockwise): self.raw_count = 0 else : self.raw_count += 1 if self.clockwise else -1 if (self.detent_count < self.detent_max and self.clockwise): self.detent_count += 1 elif (self.detent_count > -1 * self.detent_max and not self.clockwise): self.detent_count += -1 if (self.count < self.sensitivity and self.clockwise): self.count += 1 elif (self.count > -1 * self.sensitivity and not self.clockwise): self.count += -1 def update(self, byte): a = (byte & (1<<self.a_bit)) >> self.a_bit b = (byte & (1<<self.b_bit)) >> self.b_bit if ((a != self.a) != (b != self.b)): if (a != self.a): self.clockwise = a != b elif (b != self.b): self.clockwise = a == b self.adjust_count() if self.enabled: self.action() else : pass #cmd = b'SYST:DSP "This control is disabled"\r\n' #Sock.sendall(cmd) self.a = a self.b = b class EncoderBank: def __init__(self, device, gpio_addr): self.device = device self.gpio_addr = gpio_addr self.encoders = [] def set_encoders(self, encoders): self.encoders = encoders def update_encoders(self): spi.open(0,self.device) spi.mode = SPI_MODE spi.max_speed_hz = SPI_RATE to_send = [SPI_READ, self.gpio_addr, 0x00] spi.xfer2(to_send) spi.close() for e in self.encoders: e.update(to_send[2]) ActiveMenu = BlankMenu() Scope = Scope() EncoderBank0A = EncoderBank(0, GPIOA) EncoderBank0B = EncoderBank(0, GPIOB) EncoderBank1A = EncoderBank(1, GPIOA) EncoderBank1B = EncoderBank(1, GPIOB) if __name__ == "__main__": main()
from random import randint p1Score=1001 p2Score=1001 p1Roll=0 p2Roll=0 p1Name=str(input("Player 1 enter your name: ")).capitalize() p2Name=str(input("Player 2 enter your name: ")).capitalize() dRound=1 while p1Score!=0 and p2Score!=0: print("\nRound No {}".format(dRound)) input("\n{} press ENTER to roll the dices".format(p1Name)) p1Roll=randint(1,6)+randint(1,6)+randint(1,6)+randint(1,6)+randint(1,6) print("{} rolls {}".format(p1Name,p1Roll)) if p1Score>0: p1Score-=p1Roll else: p1Score+=p1Roll #if p1Score==0: # break #else: # pass print("{} temp score is {}.".format(p1Name,p1Score)) input("\n{} press ENTER to roll the dices".format(p2Name)) p2Roll=randint(1,6)+randint(1,6)+randint(1,6)+randint(1,6)+randint(1,6) print("{} rolls {}".format(p2Name,p2Roll)) if p2Score>0: p2Score-=p2Roll else: p2Score+=p2Roll #if p2Score==0: # break #else: # pass print("{} temp score is {}.".format(p2Name,p2Score)) dRound+=1 print("\nGame OVER\n") if p1Score==0: print("{} score is {}".format(p1Name,p1Score)) print("{} score is {}".format(p2Name,p2Score)) print("{} is the winner".format(p1Name)) elif p2Score==0: print("{} score is {}".format(p1Name,p1Score)) print("{} score is {}".format(p2Name,p2Score)) print("{} is the winner".format(p2Name)) elif p1Score==0 and p2Score==0: print("{} and {} are even. Let's play again.".format(p1Name,p2Name))
#!/usr/bin/env python """ Returns: Given: """ from splat.SPLAT import SPLAT import splat.Util as Util from splat.parsers.TreeStringParser import TreeStringParser import splat.complexity as cUtil from splat.tokenizers.RawTokenizer import RawTokenizer import json, sys, traceback, re from linguine.transaction_exception import TransactionException class SplatDisfluency: def __init__(self): pass def run(self, data): results = [ ] try: for corpus in data: temp_bubble = SPLAT(corpus.contents) print(corpus.contents) print(temp_bubble.sents()) raw_disfluencies = Util.count_disfluencies(temp_bubble.sents()) print(raw_disfluencies) sentences = { } average_disfluencies = 0 um_count, uh_count, ah_count, er_count, hm_count, sl_count, rep_count, brk_count = (0,) * 8 # Sort the data so it looks better in JSON for i in raw_disfluencies[0]: temp_dis = {"UM": raw_disfluencies[0][i][0], "UH": raw_disfluencies[0][i][1], "AH": raw_disfluencies[0][i][2], "ER": raw_disfluencies[0][i][3], "HM": raw_disfluencies[0][i][4], "SILENT PAUSE": raw_disfluencies[0][i][5], "REPETITION": raw_disfluencies[0][i][6], "BREAK": raw_disfluencies[0][i][7]} sentences[i] = temp_dis for (k, v) in temp_dis.items(): # Gather total disfluencies for each disfluency type average_disfluencies += v if k == "UM": um_count += v elif k == "UH": uh_count += v elif k == "AH": ah_count += v elif k == "ER": er_count += v elif k == "HM": hm_count += v elif k == "SILENT PAUSE": sl_count += v elif k == "REPETITION": rep_count += v elif k == "BREAK": brk_count += v temp_total = average_disfluencies # Calculate the average disfluencies per sentence in the whole text average_disfluencies = float(average_disfluencies / len(raw_disfluencies[0])) total_disfluencies = {"UM": um_count, "UH": uh_count, "AH": ah_count, "ER": er_count, "HM": hm_count, "SILENT PAUSE": sl_count, "REPETITION": rep_count, "BREAK": brk_count, "TOTAL": temp_total} results.append({'corpus_id': corpus.id, 'sentences': sentences, 'average_disfluencies_per_sentence': average_disfluencies, 'total_disfluencies': total_disfluencies}) results = json.dumps(results) print(results) return results except TypeError: raise TransactionException('Corpus contents does not exist.') class SplatNGrams: def __init__(self): pass def run(self, data): results = [ ] try: for corpus in data: temp_bubble = SPLAT(corpus.contents) # Gather Unigram Frequencies temp_unigrams = temp_bubble.unigrams() unigrams = dict() for item in temp_unigrams: unigrams[item[0]] = unigrams.get(item[0], 0) + 1 # Gather Bigram Frequencies temp_bigrams = temp_bubble.bigrams() bigrams = dict() for item in temp_bigrams: parsed_item = ' '.join(item) bigrams[parsed_item] = bigrams.get(parsed_item, 0) + 1 # Gather Trigram Frequencies temp_trigrams = temp_bubble.trigrams() trigrams = dict() for item in temp_trigrams: parsed_item = ' '.join(item) trigrams[parsed_item] = trigrams.get(parsed_item, 0) + 1 results.append({'corpus_id': corpus.id, 'unigrams': unigrams, 'bigrams': bigrams, 'trigrams': trigrams}) results = json.dumps(results) print(results) return results except TypeError: raise TransactionException('Corpus contents does not exist.') class SplatComplexity: def __init__(self): pass def run(self, data): results = [ ] try: for corpus in data: split_string = corpus.contents.split(" ") temp_corpus = list(filter(("{SL}").__ne__, split_string)) temp_corpus = list(filter(("{sl}").__ne__, temp_corpus)) temp_corpus_contents = " ".join(temp_corpus) #print(corpus.contents) temp_bubble = SPLAT(temp_corpus_contents) temp_trees = TreeStringParser().get_parse_trees(temp_bubble.sents()) #print(temp_bubble.splat()) #cdensity = temp_bubble.content_density() cdensity = cUtil.calc_content_density(temp_trees) print(cdensity) #print(temp_bubble.treestrings()) #idensity = temp_bubble.idea_density() idensity = cUtil.calc_idea_density(temp_trees)[0] #print(idensity) flesch_score = temp_bubble.flesch_readability() #print(flesch_score) kincaid_score = temp_bubble.kincaid_grade_level() #print(kincaid_score) types = len(temp_bubble.types()) tokens = len(temp_bubble.tokens()) type_token_ratio = float(float(types)/float(tokens)) results.append({'corpus_id': corpus.id, 'content_density': cdensity, 'idea_density': idensity, 'flesch_score': flesch_score, 'kincaid_score': kincaid_score, 'types': types, 'tokens': tokens, 'type_token_ratio': type_token_ratio}) results = json.dumps(results) #print(results) return results except TypeError as e: print(e) raise TransactionException('Corpus contents does not exist.') #except Exception as e: # print(e) # traceback.print_stack() class SplatPOSFrequencies: def __init__(self): pass def run(self,data): results = [ ] pos_parsed = {} try: for corpus in data: temp_bubble = SPLAT(corpus.contents) pos_tags = temp_bubble.pos() pos_counts = temp_bubble.pos_counts() for tuple in pos_tags: k = tuple[0] v = tuple[1] if v in pos_parsed.keys(): if k not in pos_parsed[v]: pos_parsed[v].append(k) else: pos_parsed[v] = [ ] pos_parsed[v].append(k) results.append({'corpus_id': corpus.id, 'pos_tags': pos_parsed, 'pos_counts': pos_counts}) results = json.dumps(results) print(results) return results except TypeError as e: print(e) raise TransactionException('Failed to run SplatPOSFrequencies.') class SplatSyllables: def __init__(self): pass def run(self, data): results = [ ] syllables_parsed = { } try: for corpus in data: #temp_bubble = SPLAT(corpus.contents) split_string = re.split(r'\s|\n', corpus.contents) temp_corpus = list(filter(("{SL}").__ne__, split_string)) temp_corpus = list(filter(("{sl}").__ne__, temp_corpus)) temp_corpus_contents = " ".join(temp_corpus) temp_bubble = SPLAT(temp_corpus_contents.rstrip('\n')) temp_tokens = temp_bubble.tokens() temp_tokens = ' '.join(temp_tokens).strip("\n").split(' ') print(temp_tokens) for tok in temp_tokens: temp_tok = tok.strip("\n") temp_syll_count = cUtil.num_syllables([temp_tok]) if temp_syll_count == 0: temp_syll_count = 1 if str(temp_syll_count) in syllables_parsed.keys(): if tok not in syllables_parsed[str(temp_syll_count)]: syllables_parsed[str(temp_syll_count)].append(temp_tok) else: syllables_parsed[str(temp_syll_count)] = [ ] syllables_parsed[str(temp_syll_count)].append(temp_tok) print("Creating results...") results.append({'corpus_id': corpus.id, 'syllables': syllables_parsed}) results = json.dumps(results) print(results) return results except TypeError as e: print(e) raise TransactionException('Failed to run SplatSyllables.') class SplatPronouns: def __init__(self): pass def run(self, data): results = [ ] first = { } second = { } third = { } try: for corpus in data: temp_corpus = " ".join(re.split(r'\s|\n', corpus.contents)) temp_bubble = SPLAT(temp_corpus.rstrip("\n")) pronouns = temp_bubble.raw_pronouns() print(pronouns) sents = temp_bubble.sents() for p, v in pronouns.items(): if v[1] == "1st-Person": first[p] = v elif v[1] == "2nd-Person":second[p] = v elif v[1] == "3rd-Person":third[p] = v results.append({'corpus_id': corpus.id, 'first-person': first, 'second-person': second, 'third-person': third, 'sentences': sents}) results = json.dumps(results) print(results) return results except TypeError as e: print(e) raise TransactionException("Failed to run SplatPronouns.")
try: from PyQt4 import QtCore, QtGui except ImportError: from PySide import QtCore, QtGui from maya import OpenMayaUI as omui from shiboken import wrapInstance import maya.cmds as cmds def get_maya_window(): """ This gets a pointer to the Maya window. :return: A pointer to the Maya window. :type: pointer """ maya_main_window_ptr = omui.MQtUtil.mainWindow() return wrapInstance(long(maya_main_window_ptr), QtGui.QWidget) # A custom layout. class LineEditAndButton(QtGui.QHBoxLayout): def __init__(self, obj_name='This will be overwritten'): """ :param obj_name: The name of an object in Maya. :type: str """ QtGui.QHBoxLayout.__init__(self) self.obj_name = obj_name self.some_le = None def init_layout(self): """ This method will create the button and line edit. """ # Create a button. some_btn = QtGui.QPushButton('Print') # Create a line edit. self.some_le = QtGui.QLineEdit(self.obj_name) # Connect the button to the 'get_value' method. some_btn.clicked.connect(self.get_value) # Add the line edit and button to the layout. self.addWidget(self.some_le) self.addWidget(some_btn) # Return the layout. return self def get_value(self): """ This method will trigger when the button is clicked and it will print the value of the line edit. """ # Get the value of the text in the line edit. print "The value of the line edit is %s" % self.some_le.text() class DynamicLayouts(QtGui.QDialog): """ This layout makes line edits and buttons depending on the user selection. """ def __init__(self): QtGui.QDialog.__init__(self, parent=get_maya_window()) def init_gui(self): """ Shows the GUI to the user. """ # Create the main layout. main_vb = QtGui.QVBoxLayout(self) # Get all the stuff the user selected. objs = cmds.ls(selection=True) for obj in objs: # Create a custom layout using the LineEditAndButton class. custom_layout = LineEditAndButton(obj) custom_layout.init_layout() main_vb.addLayout(custom_layout) # Set up how the window looks. self.setGeometry(300, 300, 450, 300) self.setWindowTitle('Hello World') img_icon = 'C:/Users/caj150430/code/so_much_win.png' self.setWindowIcon(QtGui.QIcon(img_icon)) self.show() dynamic = DynamicLayouts() dynamic.init_gui() # Using args and kwargs. def print_function(obj, item): print "Here are the values '%s' and '%s'" % (obj, item) def print_function(food=None, car=None, *args): for value in args: print "Here is the value " + str(value) print "The value of food is %s" % food print "The value of car is %s" % car print_function('hello', 'goodbye', car='testing') def create_objs(obj_type=None, obj_scale=None): """ This function creates some objects. :param obj_type: The type of object to create, i.e. 'pSphere'. :type: str :param obj_scale: How much to scale the object. :type: float """ # Check the object type. new_obj = None if obj_type == 'pSphere': new_obj = cmds.polySphere()[0] if new_obj and obj_scale: cmds.scale(obj_scale, new_obj, scaleY=True) def create_objs(*args): """ This function creates some objects. """ # Check the object type. new_obj = None if args[0] == 'pSphere': new_obj = cmds.polySphere()[0] if new_obj and args[1]: cmds.scale(args[1], new_obj, scaleY=True) create_objs('pSphere', 5) def kwargs_test(*args, **kwargs): print "The args are %s" % str(args) print "The kwargs are %s" % kwargs kwargs_test('foo', 'blah', triangle='edges', hedges='trees') def create_objs(**kwargs): """ This function creates some objects. :param obj_type: The type of object to create, i.e. 'pSphere'. :type: str :param obj_scale: How much to scale the object. :type: float """ # Set up some defaults. obj_type = kwargs.setdefault('obj_type', None) obj_scale = kwargs.setdefault('obj_scale', None) obj_move = kwargs.setdefault('obj_move', None) # Check the object type. new_obj = None if obj_type == 'pSphere': new_obj = cmds.polySphere()[0] if new_obj and obj_scale: cmds.scale(obj_scale, new_obj, scaleY=True) if new_obj and obj_move: cmds.move(obj_move, new_obj, moveY=True) create_objs(obj_type='pSphere', triangle='edges', obj_move=5, hedges='trees') # Making a GUI that writes data to a text file. # Write a file to disk. text_file = 'C:/Users/caj150430/code/my_lyrics.txt' lyrics = ["On a warm summer's eve", "On a train bound for nowhere", "I met up with the gambler", "We were both too tired to sleep"] file_hdl = open(text_file, 'w') for lyric in lyrics: line = "%s\r\n" % lyric file_hdl.write(line) file_hdl.close() class WriteGUI(QtGui.QDialog): def __init__(self): QtGui.QDialog.__init__(self, parent=get_maya_window()) def init_gui(self): # Make a layout to use. main_vb = QtGui.QVBoxLayout(self) # Make some random buttons. btn_01 = QtGui.QPushButton('Write It') btn_01.clicked.connect(self.write_file) # Add the layouts to the main layout. main_vb.addLayout(btn_01) # Set up how the window looks. self.setGeometry(300, 300, 450, 300) self.setWindowTitle('Hello World') img_icon = 'C:/Users/caj150430/code/so_much_win.png' self.setWindowIcon(QtGui.QIcon(img_icon)) self.show() def write_file(self): """ This method will write out translation, rotation, and scale values. """
import os l = [] def find_files(suffix, path): """ Find all files beneath path with file name suffix. Note that a path may contain further subdirectories and those subdirectories may also contain further subdirectories. There are no limit to the depth of the subdirectories can be. Args: suffix(str): suffix if the file name to be found path(str): path of the file system Returns: a list of paths """ os_dir=os.listdir(path) for elem in os_dir: if os.path.isfile(path+"/"+elem): if elem.endswith(suffix): l.append(os.path.abspath(path + "/" + elem)) elif os.path.isdir(path+"/"+elem): find_files(suffix,path+"/"+elem) return l ###Test File Recursion### l = [] ##Getting all ".c" files starting with suffix ' ' in the directory path print("\n CALL: ","find_files(suffix=' ', path='./testdir')") print("\n Result: ", find_files(suffix=' ', path='./testdir'),"\n") l = [] ##Getting all ".c" files starting with suffix a in the directory path outer dir print("\n CALL: ","find_files(suffix='.c', path='./testdir/subdir1')") print("\n Result: ", find_files(suffix='.c', path='./testdir/subdir1'),"\n") l = [] ##Getting all ".c" files starting with suffix a in the directory path inner dir print("\n CALL: ","find_files(suffix='.c', path='./testdir/subdir5')") print("\n Result: ", find_files(suffix='.c', path='./testdir/subdir5'),"\n") l = [] ##Getting all ".c" files starting with suffix b in the directory path most inner dir print("\n CALL: ","find_files(suffix='.h', path='./testdir/subdir3')") print("\n Result: ", find_files(suffix='.h', path='./testdir/subdir3'),"\n") l = [] ##Getting all ".c" files starting with suffix ' ' in the directory path print("\n CALL: ","find_files(suffix='.c', path='./testdir')") print("\n Result: ", find_files(suffix='.c', path='./testdir'),"\n")
import sys import math lon = raw_input() lat = raw_input() lon = float(lon.replace(",",".")) lat = float(lat.replace(",",".")) n = int(raw_input()) defibList = [] for i in xrange(n): defib = raw_input() defibList.append(defib.split(";")) dmin = sys.maxint for i in xrange(len(defibList)): x = (float(defibList[i][4].replace(",",".")) - lon)*math.cos((lat + float(defibList[i][5].replace(",",".")))/2) y = float(defibList[i][5].replace(",",".")) - lat d = math.sqrt(x**2 + y**2)*6371 if d<dmin: dmin = d name = defibList[i][1] print name
from unittest import TestCase, TestSuite from time import sleep import random import shutil from os.path import join, dirname from os import mkdir import subprocess import tempfile import sqlite3 from sleekxmpp import ClientXMPP def filepath(name): return join(dirname(__file__), name) class ProsodyLiveTestCase(TestCase): """ Launch a live Prosody instance and run a basic test. """ def init_prosody_db(self, sqlite_filename): conn = sqlite3.connect(sqlite_filename) c = conn.cursor() c.execute('CREATE TABLE `prosody` (' '`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, ' '`type` TEXT, `value` TEXT' ')') c.execute('CREATE INDEX `prosody_index` ON `prosody` (' '`host`, `user`, `store`, `key`)') c.execute("INSERT INTO `prosody` VALUES (" "'localhost', 'admin', 'accounts', 'password', " "'string', 'password')") conn.commit() conn.close() def setUp(self): self.tempdir = tempfile.mkdtemp() self.port = random.randint(15200, 15300) # deleting users require data_path in prosody??? self.localhost_path = mkdir(join(self.tempdir, 'localhost')) self.cfgfile = join(self.tempdir, 'prosody.cfg.lua') self.pidfile = join(self.tempdir, 'prosody.pid') self.sqlitefile = join(self.tempdir, 'prosody.sqlite') self.prosody_logfile = join(self.tempdir, 'prosody.log') self.init_prosody_db(self.sqlitefile) with open(filepath('prosody.cfg.lua.template')) as f: template = f.read() cfg = template % { 'sqlite3': self.sqlitefile, 'pidfile': self.pidfile, 'prosody_logfile': self.prosody_logfile, 'prosody_datapath': self.tempdir, 'port': self.port, } with open(self.cfgfile, 'w') as f: f.write(cfg) self.p = subprocess.Popen(['prosody', '--config', self.cfgfile]) sleep(0.1) # to allow the server to start def make_client(self): jid = 'admin@localhost' password = 'password' client = ClientXMPP(jid, password) [client.register_plugin(plugin) for plugin in [ 'xep_0030', # Service discovery 'xep_0199', # XMPP Ping 'xep_0133', # Adhoc admin ]] client.connect(address=('localhost', self.port)) client.process(block=False) self.client = client return client def tearDown(self): try: self.client.disconnect() except: # no bot, who cares. pass self.p.terminate() shutil.rmtree(self.tempdir)
from django.db import models from django.contrib.auth.models import User from datetime import datetime, timedelta # Create your models here. class UserProfile(models.Model): STATUS_CHOICES = ( ('T', 'True'), ('F', 'False'), ) user = models.OneToOneField(User, related_name='user_profile', on_delete=models.CASCADE) def __str__(self): return self.user.email class Chatroom(models.Model): name = models.CharField(max_length=40, blank=False) start_time = models.DateTimeField(default=datetime.now) # def addSecs(secs): # tm = datetime.now() # fulldate = tm + timedelta(seconds=secs) # return fulldate.time() end_time = models.DateTimeField(default=datetime.now) def __str__(self): return str(self.name) class Message(models.Model): created_at = models.DateTimeField(default=datetime.now) messages = models.CharField(max_length=1000) # user_id = models.ForeignKey(to=UserProfile, on_delete=models.CASCADE) chat_id = models.ForeignKey(Chatroom, on_delete=models.CASCADE) def __str__(self): return str(self.messages) #return str(self.chat_id + self.user_id)
''' Created on 19-May-2018 @author: srinivasan ''' import logging import os from scrapy import signals from scrapy.exceptions import NotConfigured from Data_scuff.utils.fileutils import FileUtils logger = logging.getLogger(__name__) class ClearDownloadPath: def __init__(self, settings): self.settings = settings @classmethod def from_crawler(cls, crawler): if not crawler.settings.getbool('CLEAN_DOWNLOAD_PATH_ENABLED'): raise NotConfigured ext = cls(crawler.settings) crawler.signals.connect(ext.spider_closed, signal=signals.spider_closed) return ext def spider_closed(self, spider): logger.info("started to Clean the Download Folder in spider %s", spider.name) download_path = os.path.join(self.settings.get('SELENIUM_DOWNLOAD_PATH', '/tmp'), spider.name) if FileUtils.isExist(download_path): FileUtils.deletePath(download_path) class SpiderOpenCloseLogging: def __init__(self, item_count): self.item_count = item_count self.items_scraped = 0 @classmethod def from_crawler(cls, crawler): if not crawler.settings.getbool('MYEXT_ENABLED'): raise NotConfigured item_count = crawler.settings.getint('MYEXT_ITEMCOUNT', 1000) ext = cls(item_count) crawler.signals.connect(ext.spider_opened, signal=signals.spider_opened) crawler.signals.connect(ext.spider_closed, signal=signals.spider_closed) crawler.signals.connect(ext.item_scraped, signal=signals.item_scraped) return ext def spider_opened(self, spider): logger.info("opened spider %s", spider.name) def spider_closed(self, spider): logger.info("closed spider %s", spider.name) def item_scraped(self, item, spider): self.items_scraped += 1 if self.items_scraped % self.item_count == 0: logger.info("scraped %d items", self.items_scraped)
from django.shortcuts import render from django.views.generic.base import View from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Q from apps.courses.models import Course,CourseResource,Video from apps.operations.models import UserFavourite,UserCourses,CourseComments,UserMessage from pure_pagination import Paginator, EmptyPage, PageNotAnInteger #่ฏพ็จ‹่ง†้ข‘ๆ’ญๆ”พ class VideoView(LoginRequiredMixin,View): login_url = "/login/" def get(self,request,course_id,video_id,*args,**kwargs): course=Course.objects.get(id=int(course_id)) video=Video.objects.get(id=int(video_id)) return render(request,"course-play.html",{ "video":video, "course":course, }) #่ฏพ็จ‹็ซ ่Š‚่ฏ„่ฎบ class CourseCommentView(LoginRequiredMixin,View): login_url = "/login/" def get(self,request,course_id,*args,**kwargs): course=Course.objects.get(id=int(course_id)) #่ฏพ็จ‹่ฏ„่ฎบ course_comment=CourseComments.objects.filter(course=course) # ่ฏพ็จ‹่ต„ๆบ course_resource = CourseResource.objects.filter(course=course) # ๅญฆไน ่ฟ‡่ฏฅ่ฏพ็จ‹็š„ๅŒๅญฆ user_courses = UserCourses.objects.filter(course=course) user_ids = [user_course.user_id for user_course in user_courses] all_courses = UserCourses.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:3] related_couses = [user_course.course for user_course in all_courses] return render(request, "course-comment.html", { "course": course, "course_resource": course_resource, "all_courses": related_couses, "comments":course_comment, }) #่ฏพ็จ‹็ซ ่Š‚ไฟกๆฏ class CourseLessonView(LoginRequiredMixin,View): login_url = "/login/" def get(self,request,course_id,*args,**kwargs): course=Course.objects.get(id=int(course_id)) #็”จๆˆทไธŽ่ฏพ็จ‹็š„ๅ…ณ็ณป user_courses=UserCourses.objects.filter(user=request.user,course=course) if not user_courses: user_course=UserCourses(user=request.user,course=course) user_course.save() course.students_num+=1 course.save() # ๆฌข่ฟŽ็”จๆˆทๅŠ ๅ…ฅ่ฏพ็จ‹ message = UserMessage() message.user = request.user message.messgae = "ๆฌข่ฟŽๆ‚จๅŠ ๅ…ฅ่ฏพ็จ‹๏ผš{}็š„ๅญฆไน ๏ผ".format(course.name) message.has_read = False message.save() #่ฏพ็จ‹่ต„ๆบ course_resource=CourseResource.objects.filter(course=course) #ๅญฆไน ่ฟ‡่ฏฅ่ฏพ็จ‹็š„ๅŒๅญฆ user_courses=UserCourses.objects.filter(course=course) user_ids=[user_course.user_id for user_course in user_courses] all_courses=UserCourses.objects.filter(user_id__in=user_ids).order_by("-course__click_nums")[:3] related_couses=[user_course.course for user_course in all_courses] return render(request,"course-video.html",{ "course":course, "course_resource":course_resource, "all_courses":related_couses, }) #่ฏพ็จ‹่ฏฆๆƒ…้กต้ข class CourseDetailView(View): def get(self,request,course_id,*args,**kwargs): course=Course.objects.get(id=int(course_id)) course.click_nums+=1 course.save() has_fav_course=False has_fav_org=False if request.user.is_authenticated: if UserFavourite.objects.filter(user=request.user,fav_id=course.id,fav_type=1): has_fav_course=True if UserFavourite.objects.filter(user=request.user,fav_id=course.course_org.id,fav_type=2): has_fav_org=True #่ฏพ็จ‹ๆŽจ่ tag=course.tag related_course=[] if tag: related_course=Course.objects.filter(tag=tag)[:3] return render(request,"course-detail.html",{ "course":course, "has_fav_course":has_fav_course, "has_fav_org":has_fav_org, "related_course":related_course, }) #่ฏพ็จ‹ๅˆ—่กจ้กต้ข class CourseListView(View): def get(self,request,*args,**kwargs): all_courses=Course.objects.order_by("-add_time") hot_courses=Course.objects.order_by("-fav_num")[:3] #ๆœ็ดขๅ…ณ้”ฎๅญ— keywords=request.GET.get("keywords","") if keywords: all_courses=all_courses.filter(Q(name__icontains=keywords)|Q(desc__icontains=keywords)|Q(detail__icontains=keywords)) #่ฏพ็จ‹ๆŽ’ๅบ sort=request.GET.get("sort","") print(sort) if sort == "students": all_courses=all_courses.order_by("-students_num") elif sort=="hot": all_courses=all_courses.order_by("-click_nums") try: page = request.GET.get('page', 1) except PageNotAnInteger: page = 1 # Provide Paginator with the request object for complete querystring generation p = Paginator(all_courses, per_page=3, request=request) courses = p.page(page) return render(request,"course-list.html",{ "all_courses":courses, "sort":sort, "hot":hot_courses, })