text stringlengths 38 1.54M |
|---|
from collections import OrderedDict
import numpy as np
FACIAL_LANDMARKS_IDXS = {
"mouth": (48, 68),
"right_eyebrow": (17, 22),
"left_eyebrow": (22, 27),
"right_eye": (36, 42),
"left_eye": (42, 48),
"nose": (27, 36),
"jaw": (0, 17),
"right_side": (0),
"gonion_right": (4),
"menton": (8),
"gonion_left": (12),
"left_side": (16),
"frontal_breadth_right": (17),
"frontal_breadth_left": (26),
"sellion": (27),
"nose": (30),
"sub_nose": (33),
"right_eye_outer": (36),
"right_eye_inner": (39),
"left_eye_inner": (42),
"left_eye_outer": (45),
"lip_right": (48),
"lip_left": (54),
"stomion": (62),
}
TRACKED_FACIAL_LANDMARKS = [
FACIAL_LANDMARKS_IDXS["right_side"],
FACIAL_LANDMARKS_IDXS["gonion_right"],
FACIAL_LANDMARKS_IDXS["menton"],
FACIAL_LANDMARKS_IDXS["gonion_left"],
FACIAL_LANDMARKS_IDXS["left_side"],
FACIAL_LANDMARKS_IDXS["frontal_breadth_right"],
FACIAL_LANDMARKS_IDXS["frontal_breadth_left"],
FACIAL_LANDMARKS_IDXS["sellion"],
FACIAL_LANDMARKS_IDXS["nose"],
FACIAL_LANDMARKS_IDXS["sub_nose"],
FACIAL_LANDMARKS_IDXS["right_eye_outer"],
FACIAL_LANDMARKS_IDXS["right_eye_inner"],
FACIAL_LANDMARKS_IDXS["left_eye_inner"],
FACIAL_LANDMARKS_IDXS["left_eye_outer"],
# FACIAL_LANDMARKS_IDXS["lip_right"],
# FACIAL_LANDMARKS_IDXS["lip_left"],
FACIAL_LANDMARKS_IDXS["stomion"],
]
#Antropometric constant values of the human head.
#Found on wikipedia and on:
# "Head-and-Face Anthropometric Survey of U.S. Respirator Users"
#
#X-Y-Z with X pointing forward and Y on the left.
#The X-Y-Z coordinates used are like the standard
# coordinates of ROS (robotic operative system)
FACIAL_3D_LANDMARKS_MAPPING = {
"right_side": np.float32([-100.0, -77.5, -5.0]), #0
"gonion_right": np.float32([-110.0, -77.5, -85.0]), #4
"menton": np.float32([0.0, 0.0, -122.7]), #8
"gonion_left": np.float32([-110.0, 77.5, -85.0]), #12
"left_side": np.float32([-100.0, 77.5, -5.0]), #16
"frontal_breadth_right": np.float32([-20.0, -56.1, 10.0]), #17
"frontal_breadth_left": np.float32([-20.0, 56.1, 10.0]), #26
"sellion": np.float32([0.0, 0.0, 0.0]), #27
"nose": np.float32([21.1, 0.0, -48.0]), #30
"sub_nose": np.float32([5.0, 0.0, -52.0]), #33
"right_eye_outer": np.float32([-20.0, -65.5,-5.0]), #36
"right_eye_inner": np.float32([-10.0, -40.5,-5.0]), #39
"left_eye_inner": np.float32([-10.0, 40.5,-5.0]), #42
"left_eye_outer": np.float32([-20.0, 65.5,-5.0]), #45
# "lip_right": np.float32([-20.0, 65.5,-5.0]), #48
# "lip_left": np.float32([-20.0, 65.5,-5.0]), #54
"stomion": np.float32([10.0, 0.0, -75.0]), #62
}
FACIAL_3D_LANDMARKS = np.float32([
FACIAL_3D_LANDMARKS_MAPPING["right_side"],
FACIAL_3D_LANDMARKS_MAPPING["gonion_right"],
FACIAL_3D_LANDMARKS_MAPPING["menton"],
FACIAL_3D_LANDMARKS_MAPPING["gonion_left"],
FACIAL_3D_LANDMARKS_MAPPING["left_side"],
FACIAL_3D_LANDMARKS_MAPPING["frontal_breadth_right"],
FACIAL_3D_LANDMARKS_MAPPING["frontal_breadth_left"],
FACIAL_3D_LANDMARKS_MAPPING["sellion"],
FACIAL_3D_LANDMARKS_MAPPING["nose"],
FACIAL_3D_LANDMARKS_MAPPING["sub_nose"],
FACIAL_3D_LANDMARKS_MAPPING["right_eye_outer"],
FACIAL_3D_LANDMARKS_MAPPING["right_eye_inner"],
FACIAL_3D_LANDMARKS_MAPPING["left_eye_inner"],
FACIAL_3D_LANDMARKS_MAPPING["left_eye_outer"],
FACIAL_3D_LANDMARKS_MAPPING["stomion"],
])
|
import time
import array
import random
def tlist(b, x, y, n):
t1 = time.clock()
for n in xrange(n):
for j in range(y):
for i in range(x):
w = b[j][i]
t2 = time.clock()
print "0 - List[y][x]: ", round(t2-t1, 3)
return t2-t1
def tlist2(b, x, y, n):
t1 = time.clock()
for n in xrange(n):
for j in xrange(y):
for i in xrange(x):
w = b[j][i]
t2 = time.clock()
print "1 - List[y][x] + xrange: ", round(t2-t1, 3)
return t2-t1
def tlist3(b, x, y, n):
t1 = time.clock()
for n in xrange(n):
for i in xrange(x):
for j in xrange(y):
w = b[j][i]
t2 = time.clock()
print "2 - List[y][x] + xrange + x->y: ", round(t2-t1, 3)
return t2-t1
def tlist4(b, x, y, n):
t1 = time.clock()
for n in xrange(n):
for j in xrange(y):
w = min(b[j])
t2 = time.clock()
print "3 - List[y][x] + min (line scan) + xrange: ", round(t2-t1, 3)
return t2-t1
def tlist5(b, x, y, n):
t1 = time.clock()
for n in xrange(n):
for j in b:
for i in j:
w = i
t2 = time.clock()
print "4 - List in [y] in [x]: ", round(t2-t1, 3)
return t2-t1
def tlist6(b, x, y, n):
t1 = time.clock()
for n in xrange(n):
for j in xrange(y):
lineFull = True
for i in xrange(x):
w = b[i][j]
if w == 0:
lineFull = False
break
if lineFull:
pass
else:
pass
t2 = time.clock()
print "5 - List[x][y] + (line scan) + xrange: ", round(t2-t1, 3)
return t2-t1
def tarray(b, x, y, n):
t1 = time.clock()
for n in xrange(n):
for i in xrange(x*y):
w = b[i]
t2 = time.clock()
print "6 - Array[i] + xrange: ", round(t2-t1, 3)
return t2-t1
def tarray2(b, x, y, n):
t1 = time.clock()
for n in xrange(n):
for j in xrange(y):
for i in xrange(x):
w = b[i*j]
t2 = time.clock()
print "7 - Array[i*j] + xrange: ", round(t2-t1, 3)
return t2-t1
def perform(x, y, n, s):
b = [[random.randint(0,7) for col in xrange(x)] for row in xrange(y)]
#b = [[0 for col in xrange(x)] for row in xrange(y)]
s[0] += tlist(b, x, y, n)
s[1] += tlist2(b, x, y, n)
s[2] += tlist3(b, x, y, n)
s[3] += tlist4(b, x, y, n)
s[4] += tlist5(b, x, y, n)
b2 = [[b[row][col] for row in xrange(y)] for col in xrange(x)]
s[5] += tlist6(b2, x, y, n)
b1 = []
for i in xrange(x):
for j in xrange(y):
b1.append(b[j][i])
b3 = array.array('B', b1)
s[6] += tarray(b3, x, y, n)
s[7] += tarray2(b3, x, y, n)
s = [0.0 for i in xrange(10)]
t = 1
for i in xrange(t):
perform(10, 20, 100000, s)
for i in xrange(len(s)):
print "media teste ", i, " = ", (s[i] / t)
|
# Generated by Django 3.1.1 on 2020-09-23 10:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('testapp', '0003_auto_20200923_1518'),
]
operations = [
migrations.AlterField(
model_name='employee',
name='resume',
field=models.ImageField(null=True, upload_to='documents/'),
),
]
|
# -*- coding: latin-1 -*-
"""
XML object class
Hervé Déjean
cpy Xerox 2009
a class for object from a XMLDocument
"""
from XMLDSObjectClass import XMLDSObjectClass
from config import ds_xml_def as ds_xml
class XMLDSTOKENClass(XMLDSObjectClass):
"""
LINE class
"""
def __init__(self,domNode = None):
XMLDSObjectClass.__init__(self)
XMLDSObjectClass.id += 1
self._domNode = domNode
def fromDom(self,domNode):
"""
only contains TEXT?
"""
# must be PAGE
self.setName(domNode.name)
self.setNode(domNode)
# get properties
# all?
prop = domNode.properties
while prop:
self.addAttribute(prop.name,prop.getContent())
# add attributes
prop = prop.next
self.addContent(domNode.getContent().decode("UTF-8"))
self.addAttribute('x2', float(self.getAttribute('x'))+self.getWidth())
self.addAttribute('y2',float(self.getAttribute('y'))+self.getHeight() )
|
import socket
port=8081
host='localhost'
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.sendto(b'haha!',(host,port))
|
import pytest
import os
import json
import sys
VALUE_WITH_CHECKSUM = 0
VALUE_INITIAL = 1
EXPECTED_CHECK_DIGIT_LENGTH = 1
EXPECTED_VALUES = [
('1996012101289', '199601210128'),
('1960031203012', '196003120301'),
('1995050921153', '199505092115'),
('0000000000000', '000000000000')
]
sys.path.insert(1, '../src')
from algorithms import mod_11_algorithm
def test_mod11Algorithm():
for index, expectedValue in enumerate(EXPECTED_VALUES):
assert expectedValue[VALUE_WITH_CHECKSUM][-EXPECTED_CHECK_DIGIT_LENGTH:] == mod_11_algorithm(expectedValue[VALUE_INITIAL]), f'Check Sum Doesn''t Match Expected Value in Pair: {index}'
def test_mod11AlgorithReturnLength():
assert len(mod_11_algorithm('199601210128')) == EXPECTED_CHECK_DIGIT_LENGTH, f'Check Digits are Expected to be {EXPECTED_CHECK_DIGIT_LENGTH} Characters Long'
#non-digits should result in a ValueError
def test_mod11AlgorithValueError():
with pytest.raises(ValueError) as error_info:
mod_11_algorithm('1996012A0128')
#negative values should result in a ValueError
def test_mod11AlgorithNegativeValue():
with pytest.raises(ValueError) as error_info:
mod_11_algorithm('-199601210128')
def test_mod11AlgorithEmptyValue():
with pytest.raises(IndexError) as error_info:
mod_11_algorithm('')
|
from main import Node, traverse
import copy
def syntax(input):
input.reverse()
root = Node(None, 'A', 0, 'NT')
# Rules
def isType(type_check):
if len(input) > 0:
return input[-1].getType() == type_check
return False
def isVal(val_check):
if len(input) > 0:
return input[-1].getVal() == val_check
return False
def accept(currNode):
if len(input) > 0:
tok = input.pop()
d = currNode.depth + 1
node = Node(None, tok.val, d, 'T', tok)
currNode.addChild(node)
def empty(currNode):
d = currNode.depth + 1
node = Node(None, '@', d, 'T')
currNode.addChild(node)
def A():
return (B(root) and len(input) == 0)
def B(currNode):
d = currNode.depth + 1
node = Node(None, "B", d, 'NT')
currNode.addChild(node)
return C(node) and Bp(node)
def Bp(currNode):
d = currNode.depth + 1
node = Node(None, "Bp", d, 'NT')
currNode.addChild(node)
if isType('TYPE'):
if C(node):
Bp(node)
else:
return False
else:
empty(node)
return True
def C(currNode):
d = currNode.depth + 1
node = Node(None, "C", d, 'NT')
currNode.addChild(node)
if E(node):
if isType('IDENTIFIER'):
accept(node)
return Cp(node)
return False
def Cp(currNode):
d = currNode.depth + 1
node = Node(None, "Cp", d, 'NT')
currNode.addChild(node)
if isVal('('):
accept(node)
if G(node):
if isVal(')'):
accept(node)
return J(node)
else:
return Dp(node)
def D(currNode):
d = currNode.depth + 1
node = Node(None, "D", d, 'NT')
currNode.addChild(node)
if E(node):
if isType('IDENTIFIER'):
accept(node)
return Dp(node)
return False
def Dp(currNode):
d = currNode.depth + 1
node = Node(None, "Dp", d, 'NT')
currNode.addChild(node)
if isVal(';'):
accept(node)
return True
elif isVal('['):
accept(node)
if isType('NUM_I'):
accept(node)
if isVal(']'):
accept(node)
if isVal(';'):
accept(node)
return True
return False
def E(currNode):
d = currNode.depth + 1
node = Node(None, "E", d, 'NT')
currNode.addChild(node)
if isType('TYPE'):
accept(node)
return True
return False
def G(currNode):
d = currNode.depth + 1
node = Node(None, "G", d, 'NT')
currNode.addChild(node)
if isVal('void'):
accept(node)
return Gp(node)
elif isVal('int') or isVal('float'):
accept(node)
if isType('IDENTIFIER'):
accept(node)
return Ip(node) and Hp(node)
return False
def Gp(currNode):
d = currNode.depth + 1
node = Node(None, "Gp", d, 'NT')
currNode.addChild(node)
if isType('IDENTIFIER'):
return Ip(node) and Hp(node)
else:
empty(node)
return True
def Hp(currNode):
d = currNode.depth + 1
node = Node(None, "Hp", d, 'NT')
currNode.addChild(node)
if isVal(','):
accept(node)
return I(node) and Hp(node)
else:
empty(node)
return True
def I(currNode):
d = currNode.depth + 1
node = Node(None, "I", d, 'NT')
currNode.addChild(node)
if E(node):
if isType('IDENTIFIER'):
accept(node)
return Ip(node)
return False
def Ip(currNode):
d = currNode.depth + 1
node = Node(None, "Ip", d, 'NT')
currNode.addChild(node)
if isVal('['):
accept(node)
if isVal(']'):
accept(node)
return True
else:
return False
else:
empty(node)
return True
def J(currNode):
d = currNode.depth + 1
node = Node(None, "J", d, 'NT')
currNode.addChild(node)
if isVal('{'):
accept(node)
if K(node) and L(node):
if isVal('}'):
accept(node)
return True
return False
def K(currNode):
d = currNode.depth + 1
node = Node(None, "K", d, 'NT')
currNode.addChild(node)
if isType('TYPE'):
if D(node):
return K(node)
return False
else:
empty(node)
return True
def L(currNode):
d = currNode.depth + 1
node = Node(None, "L", d, 'NT')
currNode.addChild(node)
if not isVal('}'):
if M(node):
return L(node)
return False
else:
empty(node)
return True
def M(currNode):
d = currNode.depth + 1
node = Node(None, "M", d, 'NT')
currNode.addChild(node)
if isVal('{'):
return J(node)
elif isVal('if'):
return O(node)
elif isVal('while'):
return P(node)
elif isVal('return'):
return Q(node)
else:
return N(node)
def N(currNode):
d = currNode.depth + 1
node = Node(None, "N", d, 'NT')
currNode.addChild(node)
if isVal(';'):
accept(node)
return True
elif R(node):
if isVal(';'):
accept(node)
return True
return False
def O(currNode):
d = currNode.depth + 1
node = Node(None, "O", d, 'NT')
currNode.addChild(node)
if isVal('if'):
accept(node)
if isVal('('):
accept(node)
if R(node):
if isVal(')'):
accept(node)
return M(node) and Op(node)
return False
def Op(currNode):
d = currNode.depth + 1
node = Node(None, "Op", d, 'NT')
currNode.addChild(node)
if isVal('else'):
accept(node)
return M(node)
else:
empty(node)
return True
def P(currNode):
d = currNode.depth + 1
node = Node(None, "P", d, 'NT')
currNode.addChild(node)
if isVal('while'):
accept(node)
if isVal('('):
accept(node)
if R(node):
if isVal(')'):
accept(node)
return M(node)
return False
def Q(currNode):
d = currNode.depth + 1
node = Node(None, "Q", d, 'NT')
currNode.addChild(node)
if isVal('return'):
accept(node)
return Qp(node)
return False
def Qp(currNode):
d = currNode.depth + 1
node = Node(None, "Qp", d, 'NT')
currNode.addChild(node)
if isVal(';'):
accept(node)
return True
elif R(node):
if isVal(';'):
accept(node)
return True
return False
def R(currNode):
d = currNode.depth + 1
node = Node(None, "R", d, 'NT')
currNode.addChild(node)
if isType('IDENTIFIER'):
accept(node)
return Rp(node)
elif isVal('('):
accept(node)
if R(node):
if isVal(')'):
accept(node)
return Xp(node)and Vp(node) and Tp(node)
elif isType('NUM_I') or isType('NUM_F'):
accept(node)
return Xp(node) and Vp(node) and Tp(node)
return False
def Rp(currNode):
d = currNode.depth + 1
node = Node(None, "Rp", d, 'NT')
currNode.addChild(node)
if isVal('('):
accept(node)
if Beta(node):
if isVal(')'):
accept(node)
return Xp(node) and Vp(node) and Tp(node)
elif Sp(node):
return Re(node)
return False
def Re(currNode):
d = currNode.depth + 1
node = Node(None, "Re", d, 'NT')
currNode.addChild(node)
if isVal('='):
accept(node)
return R(node)
return Xp(node) and Vp(node) and Tp(node)
def Sp(currNode):
d = currNode.depth + 1
node = Node(None, "Sp", d, 'NT')
currNode.addChild(node)
if isVal('['):
accept(node)
if R(node):
if isVal(']'):
accept(node)
return True
return False
else:
empty(node)
return True
def Tp(currNode):
d = currNode.depth + 1
node = Node(None, "Tp", d, 'NT')
currNode.addChild(node)
if U(node):
return V(node)
else:
empty(node)
return True
def U(currNode):
d = currNode.depth + 1
node = Node(None, "U", d, 'NT')
currNode.addChild(node)
if isType('RELOP'):
accept(node)
return True
return False
def V(currNode):
d = currNode.depth + 1
node = Node(None, "V", d, 'NT')
currNode.addChild(node)
return X(node) and Vp(node)
def Vp(currNode):
d = currNode.depth + 1
node = Node(None, "Vp", d, 'NT')
currNode.addChild(node)
if W(node):
if X(node):
return Vp(node)
return False
else:
empty(node)
return True
def W(currNode):
d = currNode.depth + 1
node = Node(None, "W", d, 'NT')
currNode.addChild(node)
if isType('ADDOP'):
accept(node)
return True
return False
def X(currNode):
d = currNode.depth + 1
node = Node(None, "X", d, 'NT')
currNode.addChild(node)
return Z(node) and Xp(node)
def Xp(currNode):
d = currNode.depth + 1
node = Node(None, "Xp", d, 'NT')
currNode.addChild(node)
if Y(node):
if Z(node):
return Xp(node)
return False
else:
empty(node)
return True
def Y(currNode):
d = currNode.depth + 1
node = Node(None, "Y", d, 'NT')
currNode.addChild(node)
if isType('MULOP'):
accept(node)
return True
return False
def Z(currNode):
d = currNode.depth + 1
node = Node(None, "Z", d, 'NT')
currNode.addChild(node)
if isVal('('):
accept(node)
if R(node):
if isVal(')'):
accept(node)
return True
elif isType('IDENTIFIER'):
accept(node)
return Zp(node)
elif isType('NUM_I') or isType('NUM_F'):
accept(node)
return True
return False
def Zp(currNode):
d = currNode.depth + 1
node = Node(None, "Zp", d, 'NT')
currNode.addChild(node)
if isVal('('):
accept(node)
if Beta(node):
if isVal(')'):
accept(node)
return True
elif Sp(node):
return True
return False
def Beta(currNode):
d = currNode.depth + 1
node = Node(None, "BETA", d, 'NT')
currNode.addChild(node)
if Gamma(node):
return True
else:
empty(node)
return True
def Gamma(currNode):
d = currNode.depth + 1
node = Node(None, "GAMMA", d, 'NT')
currNode.addChild(node)
return R(node) and Gammap(node)
def Gammap(currNode):
d = currNode.depth + 1
node = Node(None, "GAMMAp", d, 'NT')
currNode.addChild(node)
if isVal(','):
accept(node)
if R(node):
return Gammap(node)
return False
else:
empty(node)
return True
# End rules
if A():
message = 'Syntax completed successfully.\n'
syn_pass = True
else:
message = 'Error during syntax analysis.\n'
syn_pass = False
newRoot = None
output = traverse(root)
return message, output, root, syn_pass |
from django.shortcuts import render, redirect
from .models import Product, Repair, Complaint
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.views.generic import (ListView,
DetailView,
UpdateView,
CreateView,
DeleteView)
from django.views.generic.base import ContextMixin, TemplateView
from django.urls import reverse
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic.base import ContextMixin, TemplateView
from django import forms
from django.db.models import Sum, Max, Avg, Min
def home(request):
context = {}
return render(request, 'center/home.html', context)
def about(request):
context = {}
return render(request, 'center/about.html', context)
def faq(request):
context = {}
return render(request, 'center/faq.html', context)
def bill_info(request):
obj = Product.objects.all()
# print(obj)
total_price = 0
if obj:
for i in obj:
if i.customer == request.user:
total_price += i.price
current_customer = 'default'
max_price_prod = 0
max_price_prodname = 'default'
for j in obj:
# print(j.customer)
if j.customer == request.user:
if j.price > max_price_prod:
current_customer = j.customer
max_price_prod = j.price
max_price_prodname = j.brand
min_price_prodname = 'default'
min_price_prod = 0
min_price_prod = 9999999
for j in obj:
if j.customer == request.user:
if j.price < min_price_prod:
min_price_prod = j.price
min_price_prodname = j.brand
prod_name = max_price_prodname
prod_name_min = min_price_prodname
repair_cost = float(total_price) *0.1 + float(total_price)
vat = 0.1* float(total_price)
context = {
'product' : Product.objects.all(),
'total_price' : Product.objects.aggregate(Sum('price')),
'avg_price' : Product.objects.aggregate(Avg('price')),
'max_price' : Product.objects.aggregate(Max('price')),
'min_price' : Product.objects.aggregate(Min('price')),
'repair_cost' : int(repair_cost),
'VAT' : int(vat),
'max_prod' : prod_name,
'min_prod' : prod_name_min,
'max_price_prod' : max_price_prod,
'min_price_prod' : min_price_prod,
'total_pricex' : total_price,
'current_customer' : current_customer
}
return render(request, 'center/bill_info.html', context)
class BillInfo(LoginRequiredMixin):
template_name = 'center/bill_info.html'
def get_context_data(self, **kwargs):
context = super(BillInfo, self).get_context_data(**kwargs)
context['product'] = Product.objects.all()
context['total_price'] = Product.objects.aggregate(Sum('price'))
context['average_price'] = Product.objects.aggregate(Avg('price'))
return context
class ProductCreateView(LoginRequiredMixin, CreateView):
model = Product
template_name = 'center/product_register.html'
fields = ['product_type', 'brand',
'model_no', 'product_retailer', 'purchase_date', 'city', 'zip_code', 'price']
widgets = {'purchase_date': forms.DateInput(attrs={'class': 'datepicker'}),
}
def form_valid(self, form):
form.instance.customer = self.request.user
messages.success(self.request, f'Your product has been registered!')
return super().form_valid(form)
class RepairCreateView(LoginRequiredMixin, CreateView):
model = Repair
template_name = 'center/product_repair.html'
fields = ['product_type', 'brand','phone_number', 'option_field','description', 'address']
def form_valid(self, form):
form.instance.customer = self.request.user
messages.success(self.request, f'Your product repair request has been registered!')
return super().form_valid(form)
class ComplaintCreateView(LoginRequiredMixin, CreateView):
model = Complaint
template_name = 'center/product_complaint.html'
fields = ['product_type', 'brand', 'choice_field' ,'complaint_description', 'purchase_date', 'phone_no', 'suggestions']
widgets = {'purchase_date': forms.DateInput(attrs={'class': 'datepicker'})}
def form_valid(self, form):
form.instance.customer = self.request.user
messages.success(self.request, f'Your complaint has been registered!')
return super().form_valid(form)
class ProductDetailView(LoginRequiredMixin, DetailView):
model = Product
template_name = 'center/product_detail.html'
class RepairDetailView(LoginRequiredMixin, DetailView):
model = Repair
template_name = 'center/repair_detail.html'
class ComplaintDetailView(LoginRequiredMixin ,DetailView):
model = Complaint
template_name = 'center/complaint_detail.html'
ordering = ['-purchase_date']
class ProductUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Product
template_name = 'center/product_register.html'
fields = ['product_type', 'brand',
'model_no', 'product_retailer', 'purchase_date', 'city', 'zip_code']
def form_valid(self, form):
form.instance.customer = self.request.user
messages.success(self.request, f'Your product details have been updated!')
return super().form_valid(form)
def test_func(self):
product = self.get_object()
return self.request.user == product.customer
class RepairUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Repair
template_name = 'center/product_repair.html'
fields = ['product_type', 'brand','phone_number', 'description', 'address']
def form_valid(self, form):
form.instance.customer = self.request.user
messages.success(self.request, f'Your repair request has been updated!')
return super().form_valid(form)
def test_func(self):
repair = self.get_object()
return self.request.user == repair.customer
class ComplaintUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Complaint
template_name = 'center/product_complaint.html'
fields = ['product_type', 'brand', 'choice_field' ,'complaint_description', 'purchase_date', 'phone_no', 'suggestions']
def form_valid(self, form):
form.instance.customer = self.request.user
messages.success(self.request, f'Your complaint details have been updated! Thanks for your suggestions')
return super().form_valid(form)
def test_func(self):
product = self.get_object()
return self.request.user == product.customer
class ProductDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Product
success_url = '/center/report_check/'
def test_func(self):
product = self.get_object()
return self.request.user == product.customer
class RepairDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Repair
success_url = '/center/report_check/'
def test_func(self):
repair = self.get_object()
return self.request.user == repair.customer
class ComplaintDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Complaint
success_url = '/center/report_check/'
def test_func(self):
product = self.get_object()
return self.request.user == product.customer
class BaseContextMixin(ContextMixin):
def get_context_data(self, **kwargs):
context_data = super(BaseContextMixin, self).get_context_data(**kwargs)
data1 = Product.objects.all()
context_data["key1"] = data1
data2 = Repair.objects.all()
context_data["key2"] = data2
data3 = Complaint.objects.all()
context_data["key3"] = data3
current_customer = 'default'
for j in data1:
if j.customer == self.request.user:
current_customer = j.customer
context_data['current_customer'] = current_customer
current_customer2 = 'default'
for j in data2:
if j.customer == self.request.user:
current_customer2 = j.customer
context_data['current_customer2'] = current_customer2
current_customer3 = 'default'
for j in data3:
if j.customer == self.request.user:
current_customer3 = j.customer
context_data['current_customer3'] = current_customer3
return context_data
class ReportListView(BaseContextMixin, TemplateView, LoginRequiredMixin):
template_name = 'center/report_check.html'
def get_context_data(self, **kwargs):
context_data = super(ReportListView, self).get_context_data(**kwargs)
return context_data
|
from __future__ import absolute_import, unicode_literals
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.db.models import signals
from django.utils.translation import ugettext_lazy as _
from django_celery_beat.models import PeriodicTask, PeriodicTasks
from . import schedules
class TaskLog(models.Model):
task_name = models.CharField(max_length=255)
created = models.DateTimeField(auto_now_add=True, editable=False)
modified = models.DateTimeField(auto_now=True)
class CustomPeriodicTask(PeriodicTask):
PERIOD_CHOICES = (
('ONCE', _('Once')),
('DAILY', _('Daily')),
('WEEKLY', _('Weekly')),
('MONTHLY', _('Monthly')),
)
MONTHLY_CHOICES = (
('DAY', _('Day')),
('FIRSTWEEK', _('First Week')),
('SECONDWEEK', _('Second Week')),
('THIRDWEEK', _('Third Week')),
('FOURTHWEEK', _('Fourth Week')),
('LASTWEEK', _('Last Week')),
('LASTDAY', _('Last Day')),
)
end_time = models.DateTimeField(
_('End Datetime'), blank=True, null=True,
help_text=_(
'Datetime when the scheduled task should end')
)
every = models.PositiveSmallIntegerField(
_('every'), null=False, default=1,
help_text=_('For Weekly and Monthly Repeat')
)
scheduler_type = models.CharField(
_('scheduler_type'), max_length=24, choices=PERIOD_CHOICES,
null=True, blank=True
)
monthly_type = models.CharField(
_('monthly_type'), max_length=24, choices=MONTHLY_CHOICES,
null=True, blank=True
)
max_run_count = models.PositiveIntegerField(
null=True, blank=True,
help_text=_('To end scheduled task after few occurrence')
)
last_executed_at = models.DateTimeField(null=True, blank=True)
last_executed_days = JSONField(null=True, blank=True)
@property
def schedule(self):
if self.interval:
return self.interval.schedule
if self.crontab:
crontab = schedules.my_crontab(
minute=self.crontab.minute,
hour=self.crontab.hour,
day_of_week=self.crontab.day_of_week,
day_of_month=self.crontab.day_of_month,
month_of_year=self.crontab.month_of_year,
)
return crontab
if self.solar:
return self.solar.schedule
if self.clocked:
return self.clocked.schedule
signals.pre_delete.connect(PeriodicTasks.changed, sender=CustomPeriodicTask)
signals.pre_save.connect(PeriodicTasks.changed, sender=CustomPeriodicTask)
|
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 11 17:10:25 2017
@author: david
"""
from parsing_funs import set_type_dict, make_table, load_file, file_path
import json
|
import pickle
from collections import defaultdict
from input import get_tagged_corpus
from output import get_gold_from_dir
from typing import List
from nltk.tokenize import word_tokenize
from pathlib import Path
from flair.data import Sentence, Token, Corpus
from flair.data_fetcher import NLPTaskDataFetcher, NLPTask
from flair.embeddings import TokenEmbeddings, CharacterEmbeddings, WordEmbeddings, BertEmbeddings, FlairEmbeddings, StackedEmbeddings
from flair.models import SequenceTagger
from flair.trainers import ModelTrainer
# corpus, id_dict = get_tagged_corpus(data_folder, tokenizer, mask_propaganda=False)
# checkpoint_path = 'resources/model/best-model.pt'
# trainer: ModelTrainer = ModelTrainer.load_from_checkpoint(Path(checkpoint_path), 'SequenceTagger', corpus)
# test_data = InputParser(data_dir + 'test/', tokenizer, challenge='PTR', data_file_ending='.txt',
# mask_propaganda=mask_propaganda)
# test_sentences, test_id_list = read_column_data(test_data.data, {0: 'text', 1: 's_span', 2: 'e_span', 3: 'label'})
# ModelTrainer._evaluate_sequence_tagger_to_file(trainer.model, test_sentences, id_dict=test_id_list)
checkpoint_path = 'resources/model/best-model.pt'
model = SequenceTagger.load(checkpoint_path)
# test = open('test.tsv').readlines()
test = open('test.tsv').readlines()
test = [line.split('\t')[0] for line in test]
predictions : List[Sentence] = []
for i,sent in enumerate(test):
sentence = Sentence(sent, use_tokenizer=True)
model.predict(sentence)
predictions.append(sentence)
if i % 100 == 0:
print('tagged {} examples'.format(i))
# pickle.dump(predictions,open('test.pkl','wb'))
# predictions = pickle.load(open('test.pkl','rb'))
submission_file = open('/datasets/test/test_submission_file.txt').readlines()
char_before = 0
doc_tags = defaultdict(list)
for line1, line2, sent in zip(submission_file, predictions, test):
doc_id, sent_id, _ = line1.split('\t')
if sent_id == '1':
char_before = 0
spans = line2.get_spans('label')
if len(spans) > 0:
doc_tags[doc_id].append((char_before, sent_id, line2.to_original_text(), spans))
char_before += len(sent)
with open('flc-submission.txt','w') as writer:
for key in sorted(doc_tags.keys()):
for item in doc_tags[key]:
char_before, sent_id, sentence, spans = item
first_span, last_span = spans[0], spans[-1]
label = spans[0].tag
start_char = char_before + spans[0].start_pos
end_char = char_before + spans[-1].end_pos
writer.write('{}\t{}\t{}\t{}\n'.format(key, label, start_char, end_char))
|
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass, field
from typing import Dict, Generic, Iterable, List, TypeVar
from datahub.ingestion.api.closeable import Closeable
from datahub.ingestion.api.common import PipelineContext, RecordEnvelope, WorkUnit
from datahub.ingestion.api.report import Report
@dataclass
class SourceReport(Report):
workunits_produced: int = 0
workunit_ids: List[str] = field(default_factory=list)
warnings: Dict[str, List[str]] = field(default_factory=dict)
failures: Dict[str, List[str]] = field(default_factory=dict)
def report_workunit(self, wu: WorkUnit) -> None:
self.workunits_produced += 1
self.workunit_ids.append(wu.id)
def report_warning(self, key: str, reason: str) -> None:
if key not in self.warnings:
self.warnings[key] = []
self.warnings[key].append(reason)
def report_failure(self, key: str, reason: str) -> None:
if key not in self.failures:
self.failures[key] = []
self.failures[key].append(reason)
WorkUnitType = TypeVar("WorkUnitType", bound=WorkUnit)
class Extractor(Generic[WorkUnitType], Closeable, metaclass=ABCMeta):
@abstractmethod
def configure(self, config_dict: dict, ctx: PipelineContext) -> None:
pass
@abstractmethod
def get_records(self, workunit: WorkUnitType) -> Iterable[RecordEnvelope]:
pass
# See https://github.com/python/mypy/issues/5374 for why we suppress this mypy error.
@dataclass # type: ignore[misc]
class Source(Closeable, metaclass=ABCMeta):
ctx: PipelineContext
@classmethod
@abstractmethod
def create(cls, config_dict: dict, ctx: PipelineContext) -> "Source":
pass
@abstractmethod
def get_workunits(self) -> Iterable[WorkUnit]:
pass
@abstractmethod
def get_report(self) -> SourceReport:
pass
|
from __future__ import division
from math import floor
from collections import Counter, defaultdict
from itertools import combinations, islice
from magichour.api.local.util.log import get_logger, log_time
logger = get_logger(__name__)
def xor(s1, s2, skip_in_s2=0):
"""
XOR at the core of the the PARIS distance function
Take in two sets and compute their symmetric difference. Allow up to skip_in_s2 items to be missing.
"""
num_in_s1_not_in_s2 = len(s1.difference(s2))
num_in_s2_not_in_s1 = len(s2.difference(s1))
num_in_s2_not_in_s1 -= skip_in_s2
num_in_s2_not_in_s1 = max(num_in_s2_not_in_s1, 0)
return num_in_s1_not_in_s2 + num_in_s2_not_in_s1
def paris_distance(di, A, R, r_count):
'''
Compute paris distance function
'''
if len(di) == 0:
return 0
total_rep = set()
for ind in R:
total_rep.update(A[ind])
return xor(di, total_rep, r_count) / len(di)
def PCF(D, A, R, tau=50, r_slack=0, verbose=False):
'''
Calculate the full PARIS cost function given a set of Documents, Atoms, and a representation
'''
if verbose:
print 'PCF:'
print ' A: ', len(A) # [sorted(a) for a in A]
print ' R: ', len([1 for item in R if len(item) > 0])
print ' D/R:', len(D), len(R)
print ' r_count:', r_slack
pcfa = 0
pcfb = 0
for ind in range(len(D)):
# PCFA
pcfa += paris_distance(D[ind], A, R[ind], r_slack)
# PCFB
if len(D[ind]) != 0:
pcfb += float(len(R[ind])) / len(D[ind])
#pcfb += float(len([w for i in R[ind] for w in A[i]]))/len(D[ind])
if verbose:
print 'PCFA:', pcfa
print 'PCFB:', pcfb
# PCFC
pcfc = tau * len(A)
total_cost = pcfa + pcfb + pcfc
if verbose:
print 'PCFC:', tau * len(A)
print 'TOTAL: ', total_cost
return total_cost
def get_best_representation(di, A, verbose=False, r_slack=None):
'''
Get best possible representation for di given a set of atoms A
'''
# Start with empty set for this representation
curr_r = set()
# degenerate case
if len(di) == 0:
return curr_r
min_atom_ind = -1
min_distance = paris_distance(
di, A, curr_r, r_slack) + 1.0 / len(di) * len(curr_r)
potential_atoms = []
for i in range(len(A)):
if len(di.intersection(A[i])) > 0:
potential_atoms.append(i)
# Keep adding atoms to the representation until we are unable to improve
# the result
while min_atom_ind is not None:
# Find atom to add to the representation that minimizes total distance
min_atom_ind = None
for i in potential_atoms:
# Only check distance for items where there is some intersection
# between the line and the atom
if i not in curr_r: # and len(di.intersection(A[i])) > 0:
attempted_r = curr_r
attempted_r.add(i)
dist = paris_distance(
di, A, attempted_r, r_slack) + 1.0 / len(di) * len(attempted_r)
if verbose:
print 'Dist, min_dist', dist, min_distance
if min_distance is None or dist < min_distance:
min_distance = dist
min_atom_ind = i
attempted_r.remove(i)
if min_atom_ind is not None:
curr_r.add(min_atom_ind)
return curr_r
def design_atom(E, r_slack=0, tau=1):
'''
Implementation of the atom design function described in the PARIS paper
'''
# Get most common pair of elements in E
c = Counter()
for ind in range(len(E)):
c.update(combinations(E[ind], 2))
if len(c) == 0:
# There are no item pairs so we can't use our design atom function here
return None
Aj = None
# Initial atom is the most common pair of atoms in E
Aj_next = set(c.most_common(1)[0][0])
# Baseline error as the error in the current error set
prev_el = PCF(E, [Aj], [set() for ind in range(len(E))],
r_slack=r_slack, tau=tau) # Empty representation set
# Compute the error with the atom based on the most common pair of items
# in E
R_next = [
get_best_representation(
E[ind],
[Aj_next],
verbose=False,
r_slack=r_slack) for ind in range(
len(E))]
el = PCF(E, [Aj_next], R_next, r_slack=r_slack, tau=tau)
# Iterate until the atom updates stop improving the overall cost
while el < prev_el:
# Previous iteration was good so that becomes the new baseline
prev_el = el
Aj = Aj_next
# Add most common element in remaining unrepresented component of E
# Only count Documents that are currently using the atom in their
# representation
d = Counter()
for i, ri in enumerate(R_next):
if len(ri) > 0:
d.update(E[i].difference(Aj_next))
if len(d) > 0:
Aj_next.add(d.most_common(1)[0][0])
# Update best representation and compute cost
R_next = [
get_best_representation(
E[ind],
[Aj_next],
verbose=False,
r_slack=r_slack) for ind in range(
len(E))]
el = PCF(E, [Aj_next], R_next, r_slack=r_slack, tau=tau)
if len(d) > 0:
Aj_next.remove(d.most_common(1)[0][0])
if Aj is None:
print 'No atom created'
return Aj
def get_error(D, A, R, a_index_to_ignore):
'''
Compute the elements for each item in di not represented in by the current Atom/Representation (ignoring atoms we
are supposed to ignore
'''
E = []
for ind in range(len(D)): # For each Di
representation_for_item_i = set()
for atom_index in R[
ind]: # Add the elements of this atom to our total set
if atom_index not in a_index_to_ignore: # If this isn't the atom we are ignoring
representation_for_item_i.update(A[atom_index])
error_for_item_i = D[ind].difference(representation_for_item_i)
E.append(error_for_item_i)
return E
def get_error2(D, A, R, a_index_to_ignore):
'''
Compute the elements for each item in di not represented in by the current Atom/Representation (ignoring atoms we
are supposed to ignore
'''
E = []
for ind in range(len(D)): # For each Di
if len(R[ind].intersection(a_index_to_ignore)) > 0:
representation_for_item_i = set()
for atom_index in R[
ind]: # Add the elements of this atom to our total set
if atom_index not in a_index_to_ignore: # If this isn't the atom we are ignoring
representation_for_item_i.update(A[atom_index])
error_for_item_i = D[ind].difference(representation_for_item_i)
E.append(error_for_item_i)
else:
E.append(set())
return E
def PARIS(D, r_slack, num_iterations=3, tau=1.0):
A = []
for iteration in range(num_iterations):
logger.debug('==STARTING WITH %d ATOMS===' % len(A))
# Representation Stage
R = [
get_best_representation(
D[ind],
A,
r_slack=r_slack) for ind in range(
len(D))]
# Update Stage: Iterate through atoms replacing if possible
for a_index_to_update in range(
len(A) - 1, -1, -1): # iterate backwards
a_index_to_ignore = set([a_index_to_update])
E = get_error2(D, A, R, a_index_to_ignore)
new_a = design_atom(E, r_slack=r_slack, tau=tau)
if new_a is not None and new_a != A[a_index_to_update]:
logger.debug(
'Replacing Atom: Index [%d], Items in Common [%d], Items Different [%d]' %
(a_index_to_update, len(
A[a_index_to_update].symmetric_difference(new_a)), len(
new_a.intersection(
A[a_index_to_update]))))
del A[a_index_to_update]
A.append(new_a)
# Reduction Phase
R = [
get_best_representation(
D[ind],
A,
verbose=False,
r_slack=r_slack) for ind in range(
len(D))]
prev_error = PCF(D, A, R, r_slack=r_slack, tau=tau)
next_error = prev_error
should_stop = False
while len(A) > 0 and next_error <= prev_error and not should_stop:
logger.debug('Starting Reduction Phase with %d Atoms' % len(A))
prev_error = next_error
atom_counts = Counter()
atom_combo_counts = Counter()
total_count = 0
for ri in R:
atom_counts.update(ri)
atom_combo_counts.update(combinations(list(ri), 2))
total_count += len(ri)
# print atom_combo_counts.most_common()
should_stop = True
# Check to see if there are any
for i in range(
len(A) - 1, -1, -1): # Increment backwards so indexes don't change
if atom_counts[i] == 0:
logger.debug("Removing Atom: %s %s" % (i, A[i]))
del A[i]
should_stop = False
# check to see for every pair if it occurs more than twice it's
# likelihood
atoms_to_join = []
edited_atoms = set()
for ((a1, a2), count) in atom_combo_counts.items():
if a1 not in edited_atoms and a2 not in edited_atoms:
joint_likelihood_if_indepenent = atom_counts[
a1] * atom_counts[a2] / total_count / total_count
actual_prob = count / total_count
if actual_prob > 2.0 * joint_likelihood_if_indepenent:
atoms_to_join.append((a1, a2))
edited_atoms.add(a1)
edited_atoms.add(a2)
# edited_atoms.update(range(len(A))) # Only allow
# edit/iteration
if len(atoms_to_join) > 0:
logger.debug('Atoms that should be joined: %s' % atoms_to_join)
# Check for atoms that have a mostly overlapping set of items
if len(atoms_to_join) == 0:
for (a1, a2) in combinations(range(len(A)), 2):
if a1 not in edited_atoms and a2 not in edited_atoms and len(
A[a1].intersection(A[a2])) > .9 * max(len(A[a1]), len(A[a2])):
atoms_to_join.append((a1, a2))
edited_atoms.add(a1)
edited_atoms.add(a2)
# edited_atoms.update(range(len(A))) # Only allow
# edit/iteration
if len(atoms_to_join) > 0:
logger.debug(
'Overlapping atoms that should be joined: %s' %
atoms_to_join)
if len(atoms_to_join) > 0:
deleted_atoms = set()
def get_new_count(a1, deleted_atoms):
'''
Small helper function to account for deleted atoms
'''
num_less_than_a1 = len(
[a for a in deleted_atoms if a < a1])
return a1 - num_less_than_a1
for (a1, a2) in atoms_to_join:
# Delete a1
a1_updated = get_new_count(a1, deleted_atoms)
a_new = A[a1_updated]
del A[a1_updated]
deleted_atoms.add(a1)
# Delete a2
a2_updated = get_new_count(a2, deleted_atoms)
a_new.update(A[a2_updated])
del A[a2_updated]
deleted_atoms.add(a2)
A.append(a_new)
should_stop = False
R = [
get_best_representation(
D[ind],
A,
verbose=False,
r_slack=r_slack) for ind in range(
len(D))]
next_error = PCF(D, A, R, r_slack=r_slack, tau=tau)
logger.debug(
'ERRORS: next(%s) original(%s) Should Stop: %s' %
(next_error, prev_error, should_stop))
# Create new atoms
new_atom = -1
prev_error = PCF(D, A, R, r_slack=r_slack, tau=tau)
new_error = None
R_next = R
while (new_error is None or new_error <
prev_error) and new_atom is not None:
E = get_error(D, A, R_next, set())
new_atom = design_atom(
E, r_slack=r_slack, tau=tau) # Don't skip any atoms
if new_atom is not None:
A_next = A
A_next.append(new_atom)
R_next = [
get_best_representation(
D[ind],
A_next,
verbose=False,
r_slack=r_slack) for ind in range(
len(D))]
new_error = PCF(D, A_next, R_next, r_slack=r_slack, tau=tau)
if new_error < prev_error:
A = A_next
R = R_next
logger.debug(
'Adding Atom: %s\t%s\t%s' %
(new_error, prev_error, new_atom))
prev_error = new_error
new_error = None
else:
A = A[:-1]
logger.debug(
'Not Adding atom: %s\t%s\t%s' %
(new_error, prev_error, new_atom))
logger.debug(
'End of iteration cost: %s, %s, %s' %
(new_error, prev_error, new_atom))
logger.debug('Num ATOMS: %s ' % len(A))
return A, R
def run_paris_on_document(log_file,
window_size=20.0,
line_count_limit=None,
groups_to_skip=set([-1])):
import gzip
transactions = defaultdict(set)
lookup_table = {}
line_count = 0
if log_file.endswith('.gz'):
fIn = gzip.open(log_file)
else:
fIn = open(log_file)
# Iterate through lines building up a lookup table to map Group to
# template and to build up transactions
for line in islice(fIn, line_count_limit):
line = line.strip().split(',')
# Extract fields
time = float(line[0])
group = int(line[1])
if group not in lookup_table:
# Add to lookup table if we haven't seen this group before for
# displaying the results
template = ','.join(line[2:])
lookup_table[group] = template
# Based on window add to transactions
if group not in groups_to_skip:
window = int(time / window_size)
transactions[window].add(group)
# TODO: Allow for overlap here
line_count += 1
# PARIS expects a list of sets and not a dictionary, pull values
D = transactions.values()
# Run the PARIS algorithm
A, R = PARIS(D, r_slack)
# Display the results
for a in A:
for group in a:
print group, lookup_table[group]
print '--------------------------------------'
for a in A:
print ' '.join(map(str, a))
def test_with_syntheticdata():
import random
#alphabet_size = 200
alphabet_size = 194
#num_elements_per_atom = 8
num_elements_per_atom = 40
num_K = 50 # Number of atoms
L = 3 # number of atoms in dataset
N = 300 # 3000 # Number of sets
r = 1 # .51
r_count = int(floor(r * num_elements_per_atom))
r_slack = num_elements_per_atom - r_count
# Generate synthetic data
# Define our atoms
random.seed(1024)
K = [] # True Atoms
for i in range(num_K):
K.append(set(random.sample(range(alphabet_size), num_elements_per_atom)))
# Generate Input Sets
D = []
D_truth = []
for i in range(N):
di = set()
di_truth = set()
for j in random.sample(
range(num_K), L): # Randomly pick L atoms from all atoms
di_truth.add(j)
# add r_count items from each atom to our set
di.update(random.sample(K[j], r_count))
D.append(di)
D_truth.append(di_truth)
A, R = PARIS(D, r_slack)
def get_closest_set(a, K):
smallest_sym_diff = None
smallest_k = None
for k in K:
sym_diff = a.symmetric_difference(k)
if smallest_sym_diff is None or sym_diff < smallest_sym_diff:
smallest_sym_diff = sym_diff
smallest_k = k
return smallest_k
print 'Comparing clusters'
for a in A:
print sorted(a), sorted(get_closest_set(a, K))
def main():
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename", type=str,
help="Input log file", metavar="FILE")
parser.add_option(
"-w",
"--window",
dest="window_size",
default=20.0,
type=float,
help="Default window size")
parser.add_option(
"-n",
"--num_lines",
dest="num_lines",
default=None,
type=int)
(options, args) = parser.parse_args()
run_paris_on_document(
options.filename,
options.window_size,
line_count_limit=options.num_lines)
if __name__ == "__main__":
main()
|
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
link = "http://nda.local"
browser = webdriver.Chrome()
#Инструкция wait нужна для того, когда элемент не сразу прогружается не падала ошибка
browser.implicitly_wait(30)
try:
browser.get(link)
#CRUD в Справочники
button_Directories_Open = browser.find_element_by_css_selector("[data-qtip = Справочники]").click()
button_Pet_Types = browser.find_element_by_css_selector("[data-qtip = 'Pet Types']").click()
button_Create_Pet_Types = browser.find_element_by_css_selector("[data-qtip = Создать]").click()
input_Pet_Types = browser.find_element_by_name("Name")
input_Pet_Types.send_keys("test")
button_Save_Pet_Types = browser.find_element_by_link_text("Создать").click()
time.sleep(1)
tr_Pet_Types_Record = browser.find_element_by_partial_link_text("test").click()
button_Edit_Pet_Types = browser.find_element_by_css_selector("[data-qtip = Изменить]").click()
input_Pet_Types = browser.find_element_by_name("Name")
input_Pet_Types.send_keys("test000")
button_Save_Pet_Types = browser.find_element_by_link_text("Применить").click()
time.sleep(1)
tr_Pet_Types_Record = browser.find_element_by_partial_link_text("test000").click()
button_Delete_Pet_Types = WebDriverWait(browser, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[data-qtip = Удалить]"))).click()
button_RecordDelete_Pet_Types = browser.find_element_by_link_text("Удалить").click()
finally:
time.sleep(10)
browser.quit()
|
from tools.tools import cartesian_mask
if __name__ == "__main__":
mask_dir = 'mask'
shape = (18, 192, 192)
mask_8x = cartesian_mask(shape, 8, sample_n=4, centred=True)
mask_8x = np.transpose(mask_8x, (1,2,0))
mask_10x = cartesian_mask(shape, 10, sample_n=4, centred=True)
mask_10x = np.transpose(mask_10x, (1,2,0))
mask_12x = cartesian_mask(shape, 12, sample_n=4, centred=True)
mask_12x = np.transpose(mask_12x, (1,2,0))
mask_8x_file = os.path.join(mask_dir, 'mask_8x_0.mat')
mask_10x_file = os.path.join(mask_dir, 'mask_12x_4.mat')
mask_12x_file = os.path.join(mask_dir, 'mask_12x_4.mat')
datadict = {
'mask': np.squeeze(mask_8x)
}
scio.savemat(mask_8x_file, datadict)
datadict = {
'mask': np.squeeze(mask_10x)
}
scio.savemat(mask_10x_file, datadict)
datadict = {
'mask': np.squeeze(mask_12x)
}
scio.savemat(mask_12x_file, datadict) |
"""
Chương trình clone source https://600tuvungtoeic.com/
"""
import os
import bs4
import requests
import shutil
import json
import codecs
import cv2
SOURCE_URL = 'https://600tuvungtoeic.com/'
idWord = 1
def main():
r = requests.get(SOURCE_URL)
if r.ok:
s = bs4.BeautifulSoup(r.content, 'lxml')
items = s.select('.gallery-item')
listTopic = []
listWord = []
listWordError = []
count = 1
for item in items:
count += 1
data = {}
print(
'----------------------------------------------------------------------------------------------------------------------------------------')
# print(item)
page = item.select_one('a')
page = page.attrs['href'] if page else ''
topic_en = item.select_one('h3')
topic_en = topic_en.text.strip() if topic_en else ''
data['topic_en'] = topic_en.split(' - ')[1] if topic_en else ''
data['id'] = int(topic_en.split(' - ')[0]) if topic_en else '0'
# print(page)
# print(str(data))
image_url = item.select_one('img')
image_url = image_url.attrs['src'] if image_url else ''
data['image'] = downloadFile('topic_image', image_url, True)
image_topic = 'topic_image/' + data['image']
if not os.path.isdir('topic_image/image_unpass'):
os.mkdir('topic_image/image_unpass')
img = cv2.imread(image_topic, 0)
data['image_unpass'] = data['image'].split('.')[0] + '_unpass.jpg'
cv2.imwrite('topic_image/image_unpass/' + data['image_unpass'], img)
topicDetail(page, data, listWord, listWordError)
listTopic.append(data)
print(
'---------------------------------------------------------------------------------------------------------------------------------------')
# if count == 5:
# break
print(listTopic)
print(listWord)
dir = '600WordToiec'
if not os.path.isdir(dir):
os.mkdir(dir)
topic = codecs.open(os.path.join(dir, 'Topic.json'), encoding='utf-8', mode='w')
word = codecs.open(os.path.join(dir, 'Word.json'), encoding='utf-8', mode='w')
wordError = codecs.open(os.path.join(dir, 'WordError.json'), encoding='utf-8', mode='w')
json.dump(listTopic, topic, ensure_ascii=False, indent=2)
json.dump(listWord, word, ensure_ascii=False, indent=2)
json.dump(listWordError, wordError, ensure_ascii=False, indent=2)
def topicDetail(url, topic, listWord, listError):
global idWord
isError = False
r = requests.get(os.path.join(SOURCE_URL, url))
print(r.url)
if r.ok:
s = bs4.BeautifulSoup(r.content, 'lxml')
topic_vi = s.select_one('h2.page-title')
topic_vi = topic_vi.text.strip() if topic_vi else ''
topic_vi = topic_vi.split(' - ')[-1]
# print(topic_vi)
topic['topic_vi'] = topic_vi
items = s.select('.tuvung')
for item in items:
word = {'id': idWord, 'id_topic': topic['id']}
contents = item.select('.noidung > span')
if contents.__len__() == 0:
continue
vocabulary = contents[0].text.strip()
vocabulary = vocabulary if vocabulary else ''
word['vocabulary'] = vocabulary
spelling = contents[1].text.strip()
spelling = spelling if spelling else ''
word['spelling'] = spelling
contain_explain_vi = contents[3].next_sibling.strip()
contain_explain_vi = contain_explain_vi if contain_explain_vi else ''
from_type = contain_explain_vi.split(')')[0]
from_type = from_type if from_type else ''
word['from_type'] = from_type.strip() + ')'
explain_vi = contain_explain_vi.split('):')[1]
explain_vi = explain_vi if explain_vi else ''
word['explain_vi'] = explain_vi.strip()
try:
explain_en = contents[2].next_sibling
explain_en = explain_en if explain_en else ''
if '<br/>' in str(explain_en):
if 'catalog' in word['vocabulary']:
explain_en = 'A complete list of items, typically one in alphabetical or other systematic order'
elif 'open to' in word['vocabulary']:
explain_en = 'To be receptive to or welcoming of something that comes from outside of oneself.'
elif 'broaden' in word['vocabulary']:
explain_en = 'Become larger in distance from side to side; widen.'
elif 'be ready for' in word['vocabulary']:
explain_en = 'feeling that you must have or must do something'
else:
example_en = ''
isError = True
word['explain_en'] = explain_en
except TypeError:
continue
try:
example_en = contents[4].next_sibling.strip()
example_en = example_en if example_en else ''
word['example_en'] = example_en
example_vi = item.select_one('.noidung > b')
example_vi = example_vi.text.strip() if example_vi else ''
word['example_vi'] = example_vi
image_word = item.select_one('.hinhanh > img')
image_word = image_word.attrs['src'] if image_word else ''
if image_word:
if ' ' in image_word:
image_word = image_word.replace(' ', '_')
word['image'] = downloadFile('word_image', image_word, True)
else:
isError = True
audio = item.select_one('.noidung > audio > source')
audio = audio.attrs['src'] if audio else ''
if audio:
if ' ' in audio:
audio = audio.replace(' ', '_')
word['audio'] = downloadFile('audio', os.path.join(SOURCE_URL, audio))
else:
isError = True
contentAudio = item.select_one('.noidung').contents[-1]
contentAudio = str(contentAudio) if contentAudio else ''
if contentAudio:
contentAudio = contentAudio.split('<audio')[1]
if contentAudio:
contentAudio = contentAudio.split('<source src="')[1]
if contentAudio:
contentAudio = contentAudio.split('" type')[0]
if ' ' in contentAudio:
contentAudio = contentAudio.replace(' ', '_')
word['audio'] = downloadFile('audio', os.path.join(SOURCE_URL, contentAudio))
isError = False
idWord += 1
print(word)
if isError:
isError = False
listError.append(word)
else:
listWord.append(word)
except Exception:
pass
def downloadFile(dir, url, is_image=False):
# tạo thư mục
if not os.path.isdir(dir):
os.mkdir(dir)
file_name = url.split('/')[-1]
if is_image:
file_name = file_name.split('.')[0] + ".jpg"
file_name = file_name.lower()
if '-' in file_name:
file_name = file_name.replace('-', "_")
if os.path.exists(file_name):
return file_name
response = requests.get(url, stream=True)
if response.status_code == 404:
print('Error Not Found')
print(url)
with open(dir + '/' + file_name, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
return file_name
if __name__ == '__main__':
main()
|
# Given a string containing just the characters '(' and ')', find the length of
# the longest valid (well-formed) parentheses substring.
#
# Example 1:
#
#
# Input: "(()"
# Output: 2
# Explanation: The longest valid parentheses substring is "()"
#
#
# Example 2:
#
#
# Input: ")()())"
# Output: 4
# Explanation: The longest valid parentheses substring is "()()"
#
# Related Topics String Dynamic Programming
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def longestValidParentheses(self, s: str) -> int:
# 动态规划
n = len(s)
if not s or n < 2:
return 0
res = 0
dp = [0 for _ in range(n)]
for i in range(1, n):
if s[i] == ')':
if s[i - 1] == '(':
if i >= 2:
dp[i] = dp[i - 2] + 2
else:
dp[i] = 2
elif i - dp[i - 1] > 0 and s[i - dp[i - 1] - 1] == '(':
if i - dp[i - 1] >= 2:
dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
else:
dp[i] = dp[i - 1] + 2
res = max(res, dp[i])
return res
# leetcode submit region end(Prohibit modification and deletion)
|
import os
def check_ping(host_name,count,waitinsec):
response= os.system("ping "+host_name)
# print(f" response is {response}")
check_ping('www.google.com',5,2) |
# 何故かわかっていないが,辞書でソートだとWAでリストでソートだとACになる
def main():
n, m = map(int, input().split())
ab = []
for _ in range(n):
x, y = map(int, input().split())
ab.append((x, y))
# dic_sorted = sorted(dic.items(), key=lambda x:x[0])
ab.sort()
ans = 0
cnt = 0
for i in range(n):
if m == cnt: break
if m < cnt + ab[i][1]:
ans += ab[i][0] * (m - cnt)
break
else:
ans += ab[i][0] * ab[i][1]
cnt += ab[i][1]
# for i in range(n):
# if m == cnt: break
# if m < cnt + dic_sorted[i][1]:
# ans += dic_sorted[i][0] * (m - cnt)
# break
# else:
# ans += dic_sorted[i][0] * dic_sorted[i][1]
# cnt += dic_sorted[i][1]
print(ans)
if __name__ == '__main__':
main() |
# 122. Best Time to Buy and Sell Stock II
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices: return 0
profit = 0
for i in range(len(prices[:-1])):
if prices[i] < prices[i+1]:
profit += prices[i+1] - prices[i]
return profit
def maxProfitOld(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
have_bought = False
buy_in_price = prices[0]
profit = 0
for price in prices[1:]:
tmp = price - buy_in_price
if tmp > 0:
profit += tmp
buy_in_price = price
return profit |
"""Example for manually working with the quantum objects classes.
While manually manipulating quantum states is definitely not the focus of this
simulation package (there are better tools for that), it is nonetheless a good
starting point. Knowing how the quantum objects work is also essential for
creating custom events.
"""
import numpy as np
from requsim.world import World
from requsim.quantum_objects import Qubit, Pair
import requsim.libs.matrix as mat
from requsim.tools.noise_channels import z_noise_channel
world = World()
# without specifying any specific setup, make a Pair object with a specific
# density matrix
qubit1 = Qubit(world=world)
qubit2 = Qubit(world=world)
initial_state = mat.phiplus @ mat.H(mat.phiplus) # Bell state
pair = Pair(world=world, qubits=[qubit1, qubit2], initial_state=initial_state)
# Tip: you can use world.print_status() to show the state of world in a
# human-readable format
# now apply some map to the state. In quantum repeater context, this is most
# often a noise channel
# a) manually change the state with matrix operations
epsilon = 0.01
noise_operator = mat.tensor(mat.Z, mat.I(2)) # z_noise on qubit1
pair.state = (1 - epsilon) * pair.state + epsilon * noise_operator @ pair.state @ mat.H(
noise_operator
)
# b) use appropriate NoiseChannel object and Qubit methods
qubit3 = Qubit(world=world)
qubit4 = Qubit(world=world)
initial_state = mat.phiplus @ mat.H(mat.phiplus) # Bell state
pair2 = Pair(world=world, qubits=[qubit3, qubit4], initial_state=initial_state)
# z_noise_channel imported from requsim.tools.noise_channels
qubit3.apply_noise(z_noise_channel, epsilon=0.01)
assert np.allclose(pair.state, pair2.state)
# removing objects from the world works via the destroy methods
pair.destroy()
qubit1.destroy()
qubit2.destroy()
pair2.destroy()
qubit3.destroy()
qubit4.destroy()
|
T = int(input())
for tc in range(1, T+1):
str1 = input()
str2 = input()
max = 0
for str in str1:
if str2.count(str) > max:
max = str2.count(str)
print("#{} {}".format(tc, max)) |
for tc in range(1, 11):
N = int(input())
data = input()
stack = []
num_lst = []
push_prio = {'*': 2, '+': 1, '(': 3}
pop_prio = {'*': 2, '+': 1, '(': 0}
# Change to postfix
for i in range(N):
if data[i].isdigit():
num_lst.append(data[i])
else:
if not stack:
stack.append(data[i])
continue
else:
if data[i] == ')':
while stack[-1] != '(':
num_lst.append(stack.pop())
stack.pop()
elif push_prio[data[i]] > pop_prio[stack[-1]]:
stack.append(data[i])
else:
while push_prio[data[i]] <= pop_prio[stack[-1]]:
num_lst.append(stack.pop())
stack.append(data[i])
for i in range(len(num_lst)):
if num_lst[i].isdigit():
stack.append(num_lst[i])
else:
num2 = int(stack.pop())
num1 = int(stack.pop())
if num_lst[i] == "+":
tmp = num1 + num2
elif num_lst[i] == "*":
tmp = num1 * num2
stack.append(str(tmp))
print(f'#{tc} {stack[0]}')
|
from tkinter import *
from tkinter import ttk
import pymysql
from tkinter import messagebox
from PIL import ImageTk,Image
class Student:
def __init__(self,root):
self.root=root
self.root.title("Scholar Stewardship Application")
self.root.geometry("1350x700+0+0")
self.root.configure(bg="AntiqueWhite1")
title=Label(self.root,text="Scholar Stewardship Application",bd=10,relief=GROOVE,font=("times new roman",40,"bold"),bg="navy",fg="White")
title.pack(side=TOP,fill=X)
#---------------------------------------------------------
Manage_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="crimson")
Manage_Frame.place(x=20,y=100,width=450,height=580)
m_title=Label(Manage_Frame,text="Administrate Student Details",bg="crimson",fg="white",font=("times new roman",25,"bold"))
m_title.grid(row=0,columnspan=2,pady=10)
self.Roll_No_var=StringVar()
self.name_var = StringVar()
self.email_var = StringVar()
self.gender_var = StringVar()
self.contact_var = StringVar()
self.dob_var = StringVar()
self.address_var = StringVar()
self.search_by=StringVar()
self.search_txt=StringVar()
lbl_roll = Label(Manage_Frame,text="Roll number",bg="crimson",fg="white",font=("times new roman",20,"bold"))
lbl_roll.grid(row=1,column=0,pady=10,padx=20,sticky="w")
txt_roll=Entry(Manage_Frame,textvariable=self.Roll_No_var,font=("times new roman",15, "bold"),bd=5,relief=GROOVE)
txt_roll.grid(row=1,column=1,pady=10,padx=20,sticky="w")
lbl_name = Label(Manage_Frame, text="Name", bg="crimson", fg="white", font=("times new roman", 20, "bold"))
lbl_name.grid(row=2, column=0, pady=10, padx=20, sticky="w")
txt_name = Entry(Manage_Frame,textvariable=self.name_var, font=("times new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_name.grid(row=2, column=1, pady=10, padx=20, sticky="w")
lbl_email = Label(Manage_Frame, text="Email", bg="crimson",fg="white",font=("times new roman", 20, "bold"))
lbl_email.grid(row=3, column=0, pady=10, padx=20, sticky="w")
txt_email = Entry(Manage_Frame,textvariable=self.email_var, font=("times new roman", 15, "bold"),bd=5, relief=GROOVE)
txt_email.grid(row=3, column=1, pady=10, padx=20, sticky="w")
lbl_gender = Label(Manage_Frame, text="Gender", bg="crimson",fg="white",font=("times new roman", 20, "bold"))
lbl_gender.grid(row=4, column=0, pady=10, padx=20, sticky="w")
combo_gender=ttk.Combobox(Manage_Frame,textvariable=self.gender_var,font=("times new roman",14))
combo_gender['values']=("Male","Female","Other")
combo_gender.grid(row=4,column=1,padx=20,pady=10)
lbl_contact = Label(Manage_Frame, text="Contact", bg="crimson", fg="white", font=("times new roman", 20, "bold"))
lbl_contact.grid(row=5, column=0, pady=10, padx=20, sticky="w")
txt_contact = Entry(Manage_Frame,textvariable=self.contact_var, font=("times new roman",15, "bold"), bd=5, relief=GROOVE)
txt_contact.grid(row=5, column=1, pady=10, padx=20, sticky="w")
lbl_dob = Label(Manage_Frame, text="DOB", bg="crimson", fg="white", font=("times new roman", 20, "bold"))
lbl_dob.grid(row=6, column=0, pady=10, padx=20, sticky="w")
txt_dob = Entry(Manage_Frame,textvariable=self.dob_var, font=("times new roman", 15, "bold"), bd=5, relief=GROOVE)
txt_dob.grid(row=6, column=1, pady=10, padx=20, sticky="w")
lbl_address = Label(Manage_Frame, text="Address", bg="crimson", fg="white", font=("times new roman", 20, "bold"))
lbl_address.grid(row=7, column=0, pady=10, padx=20, sticky="w")
self.txt_address=Text(Manage_Frame,width=30,height=4,font=("",10))
self.txt_address.grid(row=7,column=1,pady=10,padx=20,sticky="w")
#________________________________________________
btn_Frame = Frame(Manage_Frame, bd=4, relief=RIDGE, bg="crimson")
btn_Frame.place(x=15,y=500, width=420)
Addbtn = Button(btn_Frame, text="Add", width=10,command=self.add_students).grid(row=0, column=0, padx=10, pady=10)
updatebtn = Button(btn_Frame, text="Update", width=10,command=self.update_data).grid(row=0, column=1, padx=10, pady=10)
deletebtn = Button(btn_Frame, text="Delete", width=10,command=self.delete_data).grid(row=0, column=2, padx=10, pady=10)
Clearbtn = Button(btn_Frame, text="Clear", width=10,command=self.clear).grid(row=0, column=3, padx=10, pady=10)
#----------------------------------------------
Detail_Frame=Frame(self.root,bd=4,relief=RIDGE,bg="green3")
Detail_Frame.place(x=500,y=100,width=800,height=560)
lbl_Search=Label(Detail_Frame, text="Search", bg="green3", fg="white", font=("times new roman", 20, "bold"))
lbl_Search.grid(row=0, column=0, pady=10, padx=20, sticky="w")
combo_search = ttk.Combobox(Detail_Frame,width=10,textvariable=self.search_by, font=("times new roman", 13,"bold"),state='readonly')
combo_search['values'] = ("Roll_No", "Name", "Contact")
combo_search.grid(row=0, column=1, padx=20, pady=10)
txt_search = Entry(Detail_Frame,width=20,textvariable=self.search_txt, font=("times new roman", 10, "bold"), bd=5, relief=GROOVE)
txt_search.grid(row=0, column=2, pady=10, padx=20, sticky="w")
searchbtn = Button(Detail_Frame, text="Search", width=10,pady=5,command=self.search_data).grid(row=0, column=3, padx=10, pady=10)
showallbtn = Button(Detail_Frame, text="Showall", width=10,pady=5,command=self.fetch_data).grid(row=0, column=4, padx=10, pady=10)
#______________________________________________________
Table_Frame=Frame(Detail_Frame,bd=4,relief=RIDGE,bg="grey1")
Table_Frame.place(x=10,y=70,width=760,height=480)
scroll_x=Scrollbar(Table_Frame,orient=HORIZONTAL)
scroll_y = Scrollbar(Table_Frame, orient=VERTICAL)
self.Student_table=ttk.Treeview(Table_Frame,columns=("roll","name","email","gender","contact","dob","address"),xscrollcommand=scroll_x.set,yscrollcommand=scroll_y.set)
scroll_x.pack(side=BOTTOM,fill=X)
scroll_y.pack(side=RIGHT,fill=Y)
scroll_x.config(command=self.Student_table.xview)
scroll_y.config(command=self.Student_table.yview)
self.Student_table.heading("roll",text="Roll No.")
self.Student_table.heading("name",text="Name")
self.Student_table.heading("email", text="Email")
self.Student_table.heading("gender", text="Gender")
self.Student_table.heading("contact", text="Conatct")
self.Student_table.heading("dob", text="DOB")
self.Student_table.heading("address", text="Address")
self.Student_table['show']='headings'
self.Student_table.column("roll",width=100)
self.Student_table.column("name", width=100)
self.Student_table.column("email", width=100)
self.Student_table.column("gender", width=100)
self.Student_table.column("contact", width=100)
self.Student_table.column("dob", width=100)
self.Student_table.column("address", width=150)
self.Student_table.pack(fill=BOTH,expand=1)
self.Student_table.bind("<ButtonRelease-1>",self.get_cursor)
self.fetch_data()
def add_students(self):
if self.Roll_No_var.get()=="" or self.name_var.get()=="":
messagebox.showerror("Eroor","All fields are required!!!")
else:
con = pymysql.connect(host="localhost", user="root", password="", database="stm")
cur = con.cursor()
cur.execute("insert into students values(%s,%s,%s,%s,%s,%s,%s)", (self.Roll_No_var.get(),
self.name_var.get(),
self.email_var.get(),
self.gender_var.get(),
self.contact_var.get(),
self.dob_var.get(),
self.txt_address.get('1.0', END)
))
con.commit()
self.fetch_data()
self.clear()
con.close()
messagebox.showinfo("Sucess","Record has been inserted")
def fetch_data(self):
con = pymysql.connect(host="localhost", user="root", password="", database="stm")
cur = con.cursor()
cur.execute("select * from students")
rows=cur.fetchall()
if len(rows)!=0:
self.Student_table.delete(*self.Student_table.get_children())
for row in rows:
self.Student_table.insert("",END,values=row)
con.commit()
con.close()
def clear(self):
self.Roll_No_var.set("")
self.name_var.set("")
self.email_var.set("")
self.gender_var.set("")
self.contact_var.set("")
self.dob_var.set("")
self.txt_address.delete("1.0",END)
def get_cursor(self,ev):
cursor_row=self.Student_table.focus()
contents=self.Student_table.item(cursor_row)
row=contents['values']
self.Roll_No_var.set(row[0])
self.name_var.set(row[1])
self.email_var.set(row[2])
self.gender_var.set(row[3])
self.contact_var.set(row[4])
self.dob_var.set(row[5])
self.txt_address.delete("1.0", END)
self.txt_address.insert(END,row[6])
def update_data(self):
con = pymysql.connect(host="localhost", user="root", password="", database="stm")
cur = con.cursor()
cur.execute("update students set name=%s,email=%s,gender=%s,contact=%s,dob=%s,address=%s where roll_no=%s",(
self.name_var.get(),
self.email_var.get(),
self.gender_var.get(),
self.contact_var.get(),
self.dob_var.get(),
self.txt_address.get('1.0', END),
self.Roll_No_var.get()
))
con.commit()
self.fetch_data()
self.clear()
con.close()
def delete_data(self):
con = pymysql.connect(host="localhost", user="root", password="", database="stm")
cur = con.cursor()
cur.execute("delete from students where roll_no=%s",self.Roll_No_var.get())
con.commit()
con.close()
self.fetch_data()
self.clear()
def search_data(self):
con = pymysql.connect(host="localhost", user="root", password="", database="stm")
cur = con.cursor()
cur.execute("select * from students where " +str(self.search_by.get())+" LIKE '%"+str(self.search_txt.get())+"%'")
rows=cur.fetchall()
if len(rows)!=0:
self.Student_table.delete(*self.Student_table.get_children())
for row in rows:
self.Student_table.insert("",END,values=row)
con.commit()
con.close()
root=Tk()
ob=Student(root)
root.mainloop()
|
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import unittest
from copy import deepcopy
from quiz.quiz1 import closest_multiple_10
test_case = [
[22, 20],
[35, 30],
[37, 40]
]
class MyTestCase(unittest.TestCase):
def test_something(self):
copy = deepcopy(test_case)
for case, answer in copy:
self.assertEqual(closest_multiple_10(case), answer)
if __name__ == '__main__':
unittest.main()
|
from django.contrib import admin
from .models import Cards, CardDetail
# Register your models here.
admin.site.register(Cards)
admin.site.register(CardDetail) |
from django import forms
from django.forms import ModelForm
from models import UserProfile
from django.contrib.auth.models import User
import logging
from django.contrib.auth import authenticate, login
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Email Address'}),max_length = 50)
password = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Password'}), max_length=50)
recaptcha = forms.CharField(max_length = 50, required=False,widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Enter Above Number'}))
class ForgetPwdForm(forms.Form):
email = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Email Address'}))
class ContactForm(forms.Form):
subject = forms.CharField()
email = forms.EmailField(required=False)
message = forms.CharField()
class UploadForm(forms.Form):
file = forms.FileField()
description = forms.CharField ( widget=forms.widgets.Textarea() )
class AddressForm(forms.Form):
STATES = (('', 'Select State'), ('AL', 'Alabama'),('AK', 'Alaska'),('AZ', 'Arizona'),('AR', 'Arkansas'),
('CA', 'California'),('CO', 'Colorado'),('CT', 'Connecticut'),('DE', 'Delaware'),
('FL', 'Florida'),('GA', 'Georgia'),('HI', 'Hawaii'),('ID', 'Idaho'),('IL', 'Illinois'),
('IN', 'Indiana'),('IA', 'Iowa'),('KS', 'Kansas'),('KY', 'Kentucky'),('LA', 'Louisiana'),
('ME', 'Maine'),('MD', 'Maryland'),('MA', 'Massachusetts'),('MI', 'Michigan'),
('MN', 'Minnesota'),('MS', 'Mississippi'),('MO', 'Missouri'),('MT', 'Montana'),
('NE', 'Nebraska'),('NV', 'Nevada'),('NH', 'New Hampshire'), ('NJ', 'New Jersey'),
('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'),
('ND', 'North Dakota'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'),
('PA', 'Pennsylvania'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'),
('TN', 'Tennessee'),('TX', 'Texas'),('UT', 'Utah'),('VT', 'Vermont'),('VA', 'Virginia'),
('WA', 'Washington'),('WV', 'West Virginia'),('WI', 'Wisconsin'),('WY', 'Wyoming'))
contact_id = forms.CharField(widget=forms.HiddenInput, required=False)
first_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'First Name'}),max_length = 200)
last_name = forms.CharField(max_length = 50L, required=True)
company = forms.CharField(max_length = 255L, required=False)
phone = forms.CharField(max_length = 50L, required=True)
address1 = forms.CharField(max_length = 255L, required=True)
address2 = forms.CharField(max_length = 255L, required=False)
city = forms.CharField(max_length = 50L, required=True)
country = forms.CharField(max_length = 100L, required=True)
state = forms.ChoiceField(choices=STATES, initial='FL')
zip = forms.CharField(max_length = 20L, required=True)
address_type = forms.CharField(widget=forms.HiddenInput, required=False)
class BillingShippingAddressForm(forms.Form):
COUNTRIES = (('USA','United States'), ('UK', 'United Kingdom'))
STATES = (('', 'Select State'), ('AL', 'Alabama'),('AK', 'Alaska'),('AZ', 'Arizona'),('AR', 'Arkansas'),
('CA', 'California'),('CO', 'Colorado'),('CT', 'Connecticut'),('DE', 'Delaware'),
('FL', 'Florida'),('GA', 'Georgia'),('HI', 'Hawaii'),('ID', 'Idaho'),('IL', 'Illinois'),
('IN', 'Indiana'),('IA', 'Iowa'),('KS', 'Kansas'),('KY', 'Kentucky'),('LA', 'Louisiana'),
('ME', 'Maine'),('MD', 'Maryland'),('MA', 'Massachusetts'),('MI', 'Michigan'),
('MN', 'Minnesota'),('MS', 'Mississippi'),('MO', 'Missouri'),('MT', 'Montana'),
('NE', 'Nebraska'),('NV', 'Nevada'),('NH', 'New Hampshire'), ('NJ', 'New Jersey'),
('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'),
('ND', 'North Dakota'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'),
('PA', 'Pennsylvania'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'),
('TN', 'Tennessee'),('TX', 'Texas'),('UT', 'Utah'),('VT', 'Vermont'),('VA', 'Virginia'),
('WA', 'Washington'),('WV', 'West Virginia'),('WI', 'Wisconsin'),('WY', 'Wyoming'))
contact_id = forms.CharField(widget=forms.HiddenInput, required=False)
billing_first_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control','autocomplete':'ON', 'size':130}),max_length = 50, required=True)
billing_last_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control','autocomplete':'ON', 'size':130}),max_length = 50, required=True)
billing_company = forms.CharField(max_length = 255L, required=False)
billing_phone_part1 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':1, 'maxlength':3, 'style':'width:25px' }),max_length = 3, required=False)
billing_phone_part2 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':1, 'maxlength':3, 'style':'width:25px'}),max_length = 3, required=False)
billing_phone_part3 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':2, 'maxlength':4, 'style':'width:30px'}),max_length = 4, required=False)
billing_phone_ext = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':3}),max_length = 50, required=False)
billing_address1 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':40}),max_length = 50, required=False)
billing_address2 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':40}),max_length = 50, required=False)
billing_city = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':10}),max_length = 50, required=False)
billing_state = forms.ChoiceField(choices=STATES, required = False)
billing_country = forms.ChoiceField(choices=COUNTRIES, initial='USA')
billing_zip = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':5, 'maxlength':5, 'style':'width:40px'}), max_length = 5, required=False)
shipping_first_name = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':30}),max_length = 50, required=False)
shipping_last_name = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':30}),max_length = 50, required=False)
shipping_company = forms.CharField(max_length = 255L, required=False)
shipping_phone_part1 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':3, 'maxlength':3, 'style':'width:25px'}), max_length = 3, required=False)
shipping_phone_part2 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':3, 'maxlength':3, 'style':'width:25px'}), max_length = 3, required=False)
shipping_phone_part3 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':3, 'maxlength':4, 'style':'width:30px'}), max_length = 4, required=False)
shipping_phone_ext = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':3}),max_length = 50, required=False)
shipping_address1 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':40}),max_length = 50, required=False)
shipping_address2 = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':40}),max_length = 50, required=False)
shipping_city = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':10}),max_length = 50, required=False)
shipping_state = forms.ChoiceField(choices=STATES)
shipping_zip = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'ON', 'size':5, 'maxlength':5, 'style':'width:40px'}), max_length = 5, required=False)
class RegistrationForm(forms.Form):
email = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Email Address'}),max_length = 200)
first_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'First Name'}),max_length = 50L)
last_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Last Name'}),max_length = 50L)
password = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Password'}), max_length=50)
cpassword = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Confirm Password'}), max_length=50)
phone = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Phone'}),max_length = 50, required=False)
#country = forms.ChoiceField(choices=[ (o.id, o.name) for o in ShippingCountries.objects.all().filter(enabled=1)], initial='USA',widget=forms.Select(attrs={'class' : 'form-control', 'autocomplete':'OFF'}))
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
def clean_email(self):
if User.objects.filter(email=self.cleaned_data['email']).count() > 0:
raise forms.ValidationError('Email Address already registered')
return self.cleaned_data['email']
def save(self, request):
user = User()
user.username = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if self.cleaned_data['password'] != '':
user.set_password(self.cleaned_data['password'])
user.email = self.cleaned_data['email']
user.save()
if self.cleaned_data['password'] != '':
user = authenticate(username=self.cleaned_data['email'], password=self.cleaned_data['password'])
userprofile = UserProfile()
userprofile.user = user
userprofile.phone = self.cleaned_data['phone']
userprofile.save()
#mail.send_mail(sender="support <accounts@example.com>",
# to="gjelstabet.com Support <accounts@gjelstabet.com>",
# subject=user.first_name+" "+user.last_name+"<"+user.email+"> Account Registration",
# body="""
# Greetings:
# We would like to thank you for registering with gjelstabet. We hope you enjoy
# our service and please do let us know any suggestion you might have either via
# sales@gjelstabet.com or our website.
# Thank you and have a nice day !
# Your PR Media Store Team
# """)
return userprofile
class ProfileDetailsForm(forms.Form):
USERTYP = (('1','Image Owner'), ('2', 'PR Officer'))
email = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Email Address'}),max_length = 200)
username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Username'}),max_length = 50, required=False)
password = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Password'}), max_length=50, required=True)
first_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'First Name'}),max_length = 50L)
last_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Last Name'}),max_length = 50L)
u_type = forms.ChoiceField(widget=forms.RadioSelect, choices=USERTYP)
phone = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Phone'}),max_length = 50, required=False)
def __init__(self, *args, **kwargs):
super(ProfileDetailsForm, self).__init__(*args, **kwargs)
def clean_email(self):
if User.objects.filter(email=self.cleaned_data['email']).count() > 0:
raise forms.ValidationError('Email Address already registered')
return self.cleaned_data['email']
def save(self, request):
logging.info('User Type:: %s',self.cleaned_data['u_type'])
user = User()
user.username = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if self.cleaned_data['password'] != '':
user.set_password(self.cleaned_data['password'])
if self.cleaned_data['u_type'] == "2":
user.is_staff=1
user.email = self.cleaned_data['email']
user.save()
if self.cleaned_data['password'] != '':
user = authenticate(username=user.username, password=self.cleaned_data['password'])
userprofile = UserProfile()
userprofile.user = user
if self.cleaned_data['u_type'] == "1":
userprofile.is_imageowner = self.cleaned_data['u_type']
userprofile.phone = self.cleaned_data['phone']
current_user = request.user
userprofile.created_by = current_user.id
userprofile.save()
return userprofile
class UserForm(forms.Form):
STATUSES = (('1','Super Admin'), ('1', 'PR Officer'), ('1', 'Image Owner'))
email = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Email Address'}),max_length = 200)
username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Username'}),max_length = 50)
user_type = forms.ChoiceField(choices=STATUSES, required = False, widget=forms.Select(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Username'}))
password = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Password'}), max_length=50)
confirmpass = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Confirm Password'}), max_length=50)
first_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'First Name'}),max_length = 50L)
last_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Last Name'}),max_length = 50L)
class ChangePwdForm(forms.Form):
#username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'txt-box1', 'autocomplete':'OFF', 'placeholder':'Email Address', 'disabled':"disabled"}),max_length = 50)
#old_password = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'txt-box1', 'autocomplete':'OFF', 'placeholder':'Password'}), max_length=50)
#new_password = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'txt-box1', 'autocomplete':'OFF', 'placeholder':'Password'}), max_length=50)
#username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'txt-box1', 'autocomplete':'OFF', 'placeholder':'Email Address', 'disabled':"disabled"}),max_length = 50, required=False)
old_password = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'Old Password'}), max_length = 25L)
new_password = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control', 'autocomplete':'OFF', 'placeholder':'New Password'}), max_length = 25L)
#--- Murthy Added Forms from 2013-16-17 --
class CreditCardForm(forms.Form):
previous_cards = forms.ChoiceField(choices=[], widget=forms.RadioSelect(), required=False)
card_holder_name = forms.CharField(max_length = 50L)
card_type = forms.ChoiceField(choices=[('V', 'Visa'), ('M', 'Master')])
card_number = forms.CharField(max_length = 50L)
card_expdate = forms.CharField(max_length = 5L)
card_cvn = forms.CharField(max_length = 5L)
is_save_card = forms.BooleanField(required=False, label="Check this")
def __init__(self, *args, **kwargs):
card_list = kwargs.pop('card_list')
super(CreditCardForm, self).__init__(*args,**kwargs)
self.fields['previous_cards'].choices = card_list
class NewAccountForm(forms.Form):
username1 = forms.CharField(widget=forms.TextInput(attrs={'class' : 'txt-box1', 'autocomplete':'OFF', 'placeholder':'Email Address'}),max_length = 50)
password1 = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'txt-box1', 'autocomplete':'OFF', 'placeholder':'Password'}), max_length=25)
confirm_password1 = forms.CharField(widget=forms.PasswordInput(render_value=False,attrs={'class' : 'txt-box1', 'autocomplete':'OFF', 'placeholder':'Confirm Password'}), max_length=25)
class PaypalOrderFormNoLogin(BillingShippingAddressForm, NewAccountForm):
comment = forms.CharField(widget=forms.Textarea, max_length = 255L, required=False)
class PaypalOrderFormLoggedIn(BillingShippingAddressForm):
comment = forms.CharField(widget=forms.Textarea, max_length = 255L, required=False)
class AuthorizeNetFormNoLogin(BillingShippingAddressForm, CreditCardForm, NewAccountForm):
comment = forms.CharField(widget=forms.Textarea, max_length = 255L, required=False)
class AuthorizeNetFormLoggedIn(BillingShippingAddressForm, CreditCardForm):
comment = forms.CharField(widget=forms.Textarea, max_length = 255L, required=False)
class NoGateWay(BillingShippingAddressForm):
comment = forms.CharField(widget=forms.Textarea, max_length = 255L, required=False)
class RadioForm(forms.Form):
STATES = (('AL', 'Alabama'),('AK', 'Alaska'),('AZ', 'Arizona'),('AR', 'Arkansas'),
('CA', 'California'),('CO', 'Colorado'),('CT', 'Connecticut'),('DE', 'Delaware'),
('FL', 'Florida'),('GA', 'Georgia'),('HI', 'Hawaii'),('ID', 'Idaho'),('IL', 'Illinois'),
('IN', 'Indiana'),('IA', 'Iowa'),('KS', 'Kansas'),('KY', 'Kentucky'),('LA', 'Louisiana'),
('ME', 'Maine'),('MD', 'Maryland'),('MA', 'Massachusetts'),('MI', 'Michigan'),
('MN', 'Minnesota'),('MS', 'Mississippi'),('MO', 'Missouri'),('MT', 'Montana'),
('NE', 'Nebraska'),('NV', 'Nevada'),('NH', 'New Hampshire'), ('NJ', 'New Jersey'),
('NM', 'New Mexico'), ('NY', 'New York'), ('NC', 'North Carolina'),
('ND', 'North Dakota'), ('OH', 'Ohio'), ('OK', 'Oklahoma'), ('OR', 'Oregon'),
('PA', 'Pennsylvania'), ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'),
('TN', 'Tennessee'),('TX', 'Texas'),('UT', 'Utah'),('VT', 'Vermont'),('VA', 'Virginia'),
('WA', 'Washington'),('WV', 'West Virginia'),('WI', 'Wisconsin'),('WY', 'Wyoming'))
shipping_state = forms.ChoiceField(choices=STATES, initial='CA')
|
# -*- coding: utf-8 -*-
###########################################################################################
#
# module name for OpenERP
# Copyright (C) 2015 qdodoo Technology CO.,LTD. (<http://www.qdodoo.com/>).
#
###########################################################################################
import qdodoo_car_archives #引入模型
import qdodoo_car_contract #引入模型
import qdodoo_entrusted_agency #引入模型
import qdodoo_car_operations #引入模型
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#Python Objects Exercise
#1 Basics
class Person:
def __init__(self, name, email, phone, friends):
self.name = name
self.email = email
self.phone = phone
self.friends = []
# def greet(self, other_person):
# print('Hello {}, I am {}!'.format(other_person.name, self.name))
# def print_contact_info(self):
# print("Sonny's email: {}, Sonny's phone number {}".format(self.email , self.phone))
# # def add_friend(self, friend):
# # self.add_friend()
sonny = Person("Sonny", "sonny@hotmail.com", "483-485-4948", [])
jordan = Person("Jordan", "jordan@aol.com", "495-586-3456", [])
# sonny.greet(jordan)
# jordan.greet(sonny)
# print(sonny.email)
# print(sonny.phone)
# print(jordan.email)
# print(jordan.phone)
# sonny.print_contact_info()
# jordan.friends.append("sonny")
# jordan.friends.append("Sonic the Hedgehog") #Just testing....
# sonny.friends.append("jordan")
print(jordan.friends)
print(len(jordan.friends))
#2 Make Your Own Class
# class Vehicle:
# def __init__(self, make, model, year):
# self.make = make
# self.model = model
# self.year = year
# def print_info(self):
# print(self.year, self.make, self.model)
# car = Vehicle("Nissan", "Leaf", "2015")
# car.print_info()
# truck = Vehicle("Toyota", "Tundra", "2011") #Just testing with another object
# truck.print_info()
|
#!/usr/bin/env python
import os.path
from flask import Flask
from werkzeug.contrib.fixers import ProxyFix
from flask.ext.sqlalchemy import SQLAlchemy
from .routes import register_routes
from .database import db
from .animal_inventory.models import Mouse
app = Flask(__name__)
app.config.from_object('CloudColony.settings.common.DevelopmentConfig')
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://flask_cloud_colony:balrog@localhost/cloud_colony'
db.init_app(app)
register_routes(app)
app.wsgi_app = ProxyFix(app.wsgi_app)
if __name__ == "__main__":
with app.app_context():
db.create_all()
|
import MySQLdb as sql
from config import Config
import sys
cfg = Config()
def get_connection():
""" Establish connection to database """
return sql.connect(host=cfg.dbhost, port=cfg.dbport, user=cfg.user,\
passwd=cfg.password, db=cfg.database,\
charset=cfg.charset)
def create_db ():
""" Initialize database """
conn = get_connection()
create_api_keys()
create_profiles(conn)
create_friends(conn)
#create_lounges(conn)
create_playlists(conn)
create_music(conn)
#create_chatlines(conn)
def drop_table(cur, table):
print "Dropping",table,"...",
cur.execute("DROP TABLE IF EXISTS "+table+";")
print "Done"
def clean_db():
""" Remove tables from database """
conn = get_connection()
with conn as cur:
drop_table(cur, "api_keys")
drop_table(cur, "friends")
#drop_table(cur, "chatlines")
drop_table(cur, "music")
#drop_table(cur, "lounges")
drop_table(cur, "playlists")
drop_table(cur, "profiles")
conn.commit()
def create_api_keys ():
""" Create table for registered API keys. """
conn = get_connection()
""" FIELDS
key -- the 32-char string used to identify the service
"""
print "Setting up api keys...",
with conn as cur:
cur.execute("CREATE TABLE IF NOT EXISTS api_keys (apikey VARCHAR(32) NOT NULL, PRIMARY KEY(apikey));")
conn.commit()
print "Done"
def create_tests():
""" Add testdata to the db """
conn = get_connection()
print "Creating test data...",
with conn as cur:
cur.execute('INSERT INTO api_keys VALUES ("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");')
conn.commit()
print "Done"
def create_profiles(conn):
""" Create profile table"""
""" FIELDS
id profile id
username the shown username
email contact infor for the profile
active the activation status.
secret bcrypt hash
session session token
steam_id steam_id number
playlist current lounge playlist
track current lounge track
"""
print "Creating profiles...",
with conn as cur:
qry = "CREATE TABLE IF NOT EXISTS profiles\
(id INT NOT NULL AUTO_INCREMENT,\
username VARCHAR(32) UNIQUE NOT NULL,\
email VARCHAR(255) UNIQUE NOT NULL,\
active BOOLEAN, secret VARCHAR(60) NOT NULL,\
steam_id VARCHAR(24), session VARCHAR(60),\
playlist INT, track INT,\
PRIMARY KEY(id));"
cur.execute(qry)
print "Done"
conn.commit()
def create_friends(conn):
""" Create friends table """
""" FIELDS
target the user who consider friend its friend
friend the friend in question
"""
print "Creating friends...",
with conn as cur:
qry = "CREATE TABLE IF NOT EXISTS friends\
(target INT NOT NULL, friend INT NOT NULL,\
PRIMARY KEY(target, friend),\
FOREIGN KEY(target) REFERENCES profiles(id),\
FOREIGN KEY(friend) REFERENCES profiles(id));"
cur.execute(qry)
print "Done"
conn.commit()
def create_music(conn):
""" Create music->file mapping table """
""" FIELDS
id track id
user_id owner user id
title track title
path filesystem path
playlist_id id of the playlist
"""
print "Creating music...",
with conn as cur:
qry = "CREATE TABLE IF NOT EXISTS music (id int NOT NULL AUTO_INCREMENT,\
user_id INT NOT NULL, title VARCHAR(255), path varchar(1024),\
playlist_id INT NOT NULL, PRIMARY KEY(id), FOREIGN KEY (user_id)\
REFERENCES profiles(id), FOREIGN KEY(playlist_id) REFERENCES playlists(id));"
cur.execute(qry)
print "Done"
conn.commit()
def create_lounges(conn):
""" Create user lounges consisting of
1 lounge -> 1 playlist
1 lounge -> many chat messages """
""" FIELDS
id lounge id
owner_id profile that owns lounge
playlist_id current playlist
song_id current song
"""
print "Creating lounges...",
with conn as cur:
qry = "CREATE TABLE IF NOT EXISTS lounges\
(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id));"#,\
#owner_id INT NOT NULL,\
#playlist_id INT NOT NULL,\
#song_id INT NOT NULL, PRIMARY KEY(id),\
#FOREIGN KEY(owner_id) REFERENCES profiles(id),\
#FOREIGN KEY(playlist_id) REFERENCES playlists(id),\
#FOREIGN KEY(song_id) REFERENCES music(id));"
cur.execute(qry);
conn.commit()
print "Done"
def create_playlists(conn):
""" Create lounge->music mapping """
""" FIELDS
id playlist id
title name of playlist
user_id owner user id
"""
print "Creating playlists...",
with conn as cur:
qry = "CREATE TABLE IF NOT EXISTS playlists\
(id INT NOT NULL AUTO_INCREMENT, title VARCHAR(255),\
user_id INT NOT NULL, PRIMARY KEY(id),\
FOREIGN KEY(user_id) REFERENCES profiles(id));"
cur.execute(qry)
conn.commit()
print "Done"
def create_playlistlines (conn):
""" Creates linked-list structure for each playlist """
""" FIELDS
id line id, unique
next_id next track
playlist_id belonging to playlist
music_id target track
"""
print "Creating playlistlines...",
with conn as cur:
qry = "CREATE TABLE IF NOT EXISTS playlistlines\
(id INT NOT NULL AUTO_INCREMENT, next_id INT NULL,\
playlist_id INT NOT NULL, music_id INT NOT NULL,\
PRIMARY KEY(id),\
FOREIGN KEY(next_id) REFERENCES playlistlines(id),\
FOREIGN KEY(music_id) REFERENCES music(id));"
cur.execute(qry)
conn.commit()
print "Done"
def create_chatlines(conn):
""" Chats for every lounge. """
""" FIELDS
user_id user who posted the message
lounge_id the lounge it was posted to
message the message
timestamp the time when the message was posted
"""
print "Creating chatlines...",
with conn as cur:
qry = "CREATE TABLE IF NOT EXISTS chatlines\
(user_id INT NOT NULL,\
lounge_id INT NOT NULL,\
message VARCHAR(256),\
time DATETIME,\
PRIMARY KEY(user_id, lounge_id, time),\
FOREIGN KEY(user_id) REFERENCES profiles(id),\
FOREIGN KEY(lounge_id) REFERENCES lounges(id));"
cur.execute(qry)
conn.commit()
print "Done"
def add_api_key(key):
""" Adds a key to the api_key list. """
conn = get_connection()
print 'Adding key "'+key+'" to the list.'
with conn as cur:
cur.execute('INSERT INTO api_keys VALUES (%s);', (key,))
conn.commit()
print "Done"
if __name__ == "__main__":
if len(sys.argv) == 1 or len(sys.argv)>3:
print "Usage: create_db.py [create] [clean] [addkey key_to_add]"
elif sys.argv[1] == 'addkey' and len(sys.argv)==3:
add_api_key(sys.argv[2])
elif len(sys.argv) == 2:
if sys.argv[1] == 'create':
create_db()
elif sys.argv[1] == 'clean':
clean_db()
elif sys.argv[1] == 'recreate':
clean_db()
create_db()
elif sys.argv[1] == 'tests':
create_tests()
else:
print "Unknown command!"
else:
print "Unknown command!"
|
import abc
from typing import Dict, Iterable, Optional
from oaas_registry.service_definition import ServiceDefinition
class Registry(metaclass=abc.ABCMeta):
"""
This registry represents a simple decorator for the actual
implementations.
"""
@abc.abstractmethod
def register_service(
self,
*,
namespace: str = "default",
name: str,
version: str = "1",
tags: Dict[str, str],
locations: Iterable[str],
) -> ServiceDefinition:
...
@abc.abstractmethod
def resolve_service(
self,
*,
id: Optional[str] = None,
namespace: str = "default",
name: str,
version: str = "1",
tags: Dict[str, str],
) -> Iterable[ServiceDefinition]:
...
@abc.abstractmethod
def unregister_service(self, *, id: str) -> bool:
...
|
""" A test script to shut down Zookeeper. """
import logging
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
import monit_interface
def run():
""" Shuts down Zookeeper. """
logging.warning("Stopping Zookeeper.")
monit_interface.stop('zookeeper-9999', is_group=False)
logging.warning("Done!")
return True
if __name__ == "__main__":
run()
|
import datetime
from django.db import models
from django.conf import settings
from .utils import window, next_full_hour, full_hours_between
ONE_HOUR = datetime.timedelta(hours=1)
class Category(models.Model):
title = models.CharField(max_length=1023)
style = models.CharField(max_length=15)
notes = models.TextField(blank=True)
public = models.BooleanField(default=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['title']
verbose_name_plural = "categories"
class Room(models.Model):
name = models.CharField(max_length=1023)
order = models.IntegerField(unique=True)
public = models.BooleanField(default=True)
notes = models.TextField(blank=True)
def __unicode__(self):
return self.name
def programme_continues_at(self, the_time, **conditions):
latest_programme = self.programme_set.filter(
start_time__lt=the_time,
**conditions
).order_by('-start_time')[:1]
if latest_programme:
return the_time < latest_programme[0].end_time
else:
return False
class Meta:
ordering = ['order']
class Person(models.Model):
first_name = models.CharField(max_length=1023)
surname = models.CharField(max_length=1023)
nick = models.CharField(blank=True, max_length=1023)
email = models.EmailField(blank=True, max_length=254)
phone = models.CharField(blank=True, max_length=255)
anonymous = models.BooleanField()
notes = models.TextField(blank=True)
@property
def full_name(self):
if self.nick:
return u'{0} "{1}" {2}'.format(
self.first_name,
self.nick,
self.surname
)
else:
return u'{0} {1}'.format(
self.first_name,
self.surname
)
@property
def display_name(self):
if self.anonymous:
return self.nick
else:
return self.full_name
def clean(self):
if self.anonymous and not self.nick:
from django.core.exceptions import ValidationError
raise ValidationError('If real name is hidden a nick must be provided')
def __unicode__(self):
return self.full_name
class Meta:
ordering = ['surname']
class Role(models.Model):
title = models.CharField(max_length=1023)
require_contact_info = models.BooleanField(default=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ['title']
class Tag(models.Model):
title = models.CharField(max_length=15)
order = models.IntegerField(default=0)
style = models.CharField(max_length=15, default='label-default')
def __unicode__(self):
return self.title
class Meta:
ordering = ['order']
class Programme(models.Model):
title = models.CharField(max_length=1023)
description = models.TextField()
start_time = models.DateTimeField()
length = models.IntegerField()
notes = models.TextField(blank=True)
category = models.ForeignKey(Category)
room = models.ForeignKey(Room)
organizers = models.ManyToManyField(Person, through='ProgrammeRole')
tags = models.ManyToManyField(Tag, blank=True)
@property
def end_time(self):
return (self.start_time + datetime.timedelta(minutes=self.length))
@property
def formatted_hosts(self):
return u', '.join(p.display_name for p in self.organizers.all())
@property
def is_blank(self):
return False
def __unicode__(self):
return self.title
@property
def css_classes(self):
return self.category.style if self.category.style else ''
@property
def public(self):
return self.category.public
class Meta:
ordering = ['start_time', 'room']
class ProgrammeRole(models.Model):
person = models.ForeignKey(Person)
programme = models.ForeignKey(Programme)
role = models.ForeignKey(Role)
def clean(self):
if self.role.require_contact_info and not (self.person.email or self.person.phone):
from django.core.exceptions import ValidationError
raise ValidationError('Contacts of this type require some contact info')
def __unicode__(self):
return self.role.title
class ViewMethodsMixin(object):
@property
def programmes_by_start_time(self):
results = []
prev_start_time = None
for start_time in self.start_times():
cur_row = []
incontinuity = prev_start_time and (start_time - prev_start_time > ONE_HOUR)
incontinuity = 'incontinuity' if incontinuity else ''
prev_start_time = start_time
results.append((start_time, incontinuity, cur_row))
for room in self.public_rooms:
try:
programme = room.programme_set.get(
start_time=start_time,
room__public=True
)
rowspan = self.rowspan(programme)
cur_row.append((programme, rowspan))
except Programme.DoesNotExist:
if room.programme_continues_at(start_time):
# programme still continues, handled by rowspan
pass
else:
# there is no (visible) programme in the room at start_time, insert a blank
cur_row.append((None, None))
except Programme.MultipleObjectsReturned:
raise ValueError('Room {room} has multiple programs starting at {start_time}'.format(**locals()))
return results
def start_times(self, programme=None):
result = settings.TIMETABLE_SPECIAL_TIMES[::]
for (start_time, end_time) in settings.TIMETABLE_TIME_BLOCKS:
cur = start_time
while cur <= end_time:
result.append(cur)
cur += ONE_HOUR
if programme:
result = [
i for i in result if
programme.start_time <= i < programme.end_time
]
return sorted(set(result))
@property
def public_rooms(self):
return self.rooms.filter(public=True)
def rowspan(self, programme):
return len(self.start_times(programme=programme))
class View(models.Model, ViewMethodsMixin):
name = models.CharField(max_length=32)
public = models.BooleanField(default=True)
order = models.IntegerField(default=0)
rooms = models.ManyToManyField(Room)
def __unicode__(self):
return self.name
class Meta:
ordering = ['order']
class AllRoomsPseudoView(ViewMethodsMixin):
def __init__(self):
self.name = 'All rooms'
self.public = True
self.order = 0
self.rooms = Room.objects.all() |
"""Routines for grabbing a page, with caching."""
import hashlib
import os
import time
from six.moves.urllib.error import HTTPError
from six.moves.urllib.request import urlopen
from sr.tools.environment import get_cache_dir
# Number of seconds for the cache to last for
CACHE_LIFE = 36000
def grab_url_cached(url):
"""
Download a possibly cached URL.
:returns: The contents of the page.
"""
cache_dir = get_cache_dir('urls')
h = hashlib.sha1()
h.update(url.encode('UTF-8'))
F = os.path.join(cache_dir, h.hexdigest())
if os.path.exists(F) and (time.time() - os.path.getmtime(F)) < CACHE_LIFE:
with open(F) as file:
page = file.read()
else:
# try the remote supplier page cache
try:
base_url = "https://www.studentrobotics.org/~rspanton/supcache/{}"
cached_url = base_url.format(h.hexdigest())
sc = urlopen(cached_url)
page = sc.read()
except HTTPError:
page = urlopen(url).read()
with open(F, 'wb') as file:
file.write(page)
return page
|
import requests
import random
business_id = 'kApVYIWwlriVK1pqPVrOPg'
API_KEY = '_5qOZHWTK4tjf0PzbSumf7l0oOgq6ZNl0cP04_zXtijrwRs-hQqs3VHUW69ok4JC2YoIPhyUOyq7tE-8TldNdfyhT8HltpV9KqCeG8jArab9rZdDxGthP--PAvY3X3Yx'
ENDPOINT = 'https://api.yelp.com/v3/businesses/search'
HEADERS = {'Authorization': 'bearer %s' % API_KEY}
#Define parameters
PARAMETERS = {'term': 'restaurant',
'limit': 50,
'radius': 5000,
#'offset': 50,
'location': 'augusta'}
#Make a request to the yelp API
response = requests.get(url = ENDPOINT, params = PARAMETERS, headers = HEADERS)
#convert the JSON string to a Dictionary
business_data = response.json()
def business_search_results():
biz_list = []
for biz in business_data['businesses']:
biz_list.append(biz['name'])
return random.choice(biz_list)
#print(business_search_results()) |
from rest_framework import serializers
from users.models import LeaderProfile, Teacher, Student, StudentGroup
from django.contrib.auth.models import User
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class LeaderSerializer(serializers.ModelSerializer):
class Meta:
model = LeaderProfile
fields = ("image", "sex", "age", "phone", "email")
class TeacherListSerializer(serializers.ModelSerializer):
class Meta:
model = Teacher
fields = ("id", "image", "bio", "experience", "sex", "birthday", "phone")
class StudentListSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ("id", "image", "sex", "birthday", "phone")
class TeacherCreateSerializer(serializers.ModelSerializer):
username = serializers.CharField(source="user.username")
password = serializers.CharField(write_only=True, source="user.password")
first_name = serializers.CharField(source="user.first_name")
last_name = serializers.CharField(source="user.last_name")
email = serializers.CharField(source="user.email")
class Meta:
model = Teacher
fields = ("username", 'password', "first_name", "last_name", "email", "image", "bio", "experience", "sex", "birthday", "phone")
def create(self, validated_data):
user = validated_data.pop('user')
user = User.objects.create(username=user['username'], first_name=user['first_name'], last_name=user['last_name'], email=user['email'])
user.set_password('password')
teacher = Teacher(**validated_data)
teacher.user = user
teacher.save()
return teacher
def update(self, instance, validated_data):
user = validated_data.pop('user')
if user.get('password'):
password = user.pop('password')
instance.user.set_password(password)
instance.user.save()
if user.get('username'):
username = user.pop('username')
instance.user.username = username
instance.user.save()
if user.get('last_name'):
last_name = user.pop('last_name')
instance.user.last_name = last_name
instance.user.save()
if user.get('first_name'):
first_name = user.pop('first_name')
instance.user.first_name = first_name
instance.user.save()
if user.get('email'):
email = user.pop('email')
instance.user.email = email
instance.user.save()
if validated_data.get('bio'):
bio = validated_data.pop('bio')
instance.bio = bio
instance.save()
if validated_data.get('experience'):
experience = validated_data.pop('experience')
instance.experience = experience
instance.save()
if validated_data.get('sex'):
sex = validated_data.pop('sex')
instance.sex = sex
instance.save()
if validated_data.get('sex'):
sex = validated_data.pop('sex')
instance.sex = sex
instance.save()
if validated_data.get('birthday'):
birthday = validated_data.pop('birthday')
instance.birthday = birthday
instance.save()
if validated_data.get('phone'):
phone = validated_data.pop('phone')
instance.phone = phone
instance.save()
return instance
class StudentCreateSerializer(serializers.ModelSerializer):
username = serializers.CharField(source="user.username")
password = serializers.CharField(write_only=True, source="user.password")
first_name = serializers.CharField(source="user.first_name")
last_name = serializers.CharField(source="user.last_name")
email = serializers.CharField(source="user.email")
class Meta:
model = Teacher
fields = ("username", 'password', "first_name", "last_name", "email", "image", "sex", "birthday", "phone")
def create(self, validated_data):
user = validated_data.pop('user')
user = User.objects.create(username=user['username'], first_name=user['first_name'], last_name=user['last_name'], email=user['email'])
user.set_password('password')
student = Student(**validated_data)
student.user = user
student.save()
return student
def update(self, instance, validated_data):
user = validated_data.pop('user')
if user.get('password'):
password = user.pop('password')
instance.user.set_password(password)
instance.user.save()
if user.get('username'):
username = user.pop('username')
instance.user.username = username
instance.user.save()
if user.get('last_name'):
last_name = user.pop('last_name')
instance.user.last_name = last_name
instance.user.save()
if user.get('first_name'):
first_name = user.pop('first_name')
instance.user.first_name = first_name
instance.user.save()
if user.get('email'):
email = user.pop('email')
instance.user.email = email
instance.user.save()
if validated_data.get('sex'):
sex = validated_data.pop('sex')
instance.sex = sex
instance.save()
if validated_data.get('birthday'):
birthday = validated_data.pop('birthday')
instance.birthday = birthday
instance.save()
if validated_data.get('phone'):
phone = validated_data.pop('phone')
instance.phone = phone
instance.save()
return instance
class StudentGroupListSerializer(serializers.ModelSerializer):
students_in_the_group = StudentCreateSerializer(many=True, read_only=True)
class Meta:
model = StudentGroup
fields = ('id', 'name_of_group', 'teacher_of_group', 'students_in_the_group')
class StudentGroupCreateSerializer(serializers.ModelSerializer):
class Meta:
model = StudentGroup
fields = ('name_of_group', 'teacher_of_group', 'students_in_the_group')
def to_representation(self, value):
response = super().to_representation(value)
response['Student'] = StudentListSerializer(value.students_in_the_group, many=True).data
return response
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attr):
data = super().validate(attr)
token = self.get_token(self.user)
data['user'] = str(self.user)
return data
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
teachers = Teacher.objects.filter(user__id=user.id)
token = super().get_token(user)
if not teachers:
token['access level'] = "0"
else:
token['access level'] = "teacher"
token['username'] = user.username
return token
|
def quickSort(alist,blist):
quickSortHelper(alist,0,len(alist)-1,blist)
def quickSortHelper(alist,first,last,blist):
if first<last:
splitpoint = partition(alist,first,last,blist)
quickSortHelper(alist,first,splitpoint-1,blist)
quickSortHelper(alist,splitpoint+1,last,blist)
def partition(alist,first,last,blist):
pivotvalue = alist[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp2 = blist[leftmark]
blist[leftmark] = blist[rightmark]
blist[rightmark] = temp2
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
temp2 = blist[first]
blist[first] = blist[rightmark]
blist[rightmark] = temp2
return rightmark
def max(a,b):
if a>b:
return a
else:
return b
def unionOfIntervals(alist,blist):
for i in range(0,len(alist)-1):
if alist[i+1] <= blist[i] :
alist[i+1] = alist[i]
blist[i+1] = max(blist[i],blist[i+1])
else:
print "("
print alist[i]
print ","
print blist[i]
print ")"
print alist[len(alist)-1]
print blist[len(alist)-1]
alist = [54,26,63,17,77,31,44,55,20]
blist = [58,34,100,47,78,34,45,78,37]
quickSort(alist,blist)
print(alist)
print blist
unionOfIntervals(alist,blist)
|
from flask import Flask, request, abort, jsonify
import json
import sys
import subprocess
sys.path.insert(1, '../PP-01')
from bill import *
app = Flask(__name__)
def getStatus():
subprocess.call('echo {} | sudo -S {}'.format(pwd, 'echo root'), shell=True)
cpuPercentage = subprocess.getoutput("mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12\"%\" }'")
cpuTemp = subprocess.getoutput('echo {} | sudo -S {}'.format(pwd, 'tlp-stat -t | grep temp | awk \'{print $4}\''))
gpuTemp = subprocess.getoutput('nvidia-smi | grep N/A | awk \'$3 ~ /[1-9.]+/ {print $3}\'')
storagePercent = subprocess.getoutput('df --output=pcent / | awk -F "%" "NR==2{print $1}"')
batteryStatus = subprocess.getoutput('echo {} | sudo -S {}'.format(pwd, 'tlp-stat -b | grep status | awk \'{print $3 $4}\''))
return cpuPercentage, cpuTemp, gpuTemp, storagePercent, batteryStatus
def formatStatus(status):
fstatus = {
'cpu': '{}'.format(status[0].split('%')[0]),
'cpuTemp': '{}'.format(status[1]),
'gpuTemp': '{}'.format(status[2]),
'storage': '{}'.format(status[3].split('%')[0]),
'batStatus': '{}'.format(status[4])
}
return fstatus
# server password SECRET
pwd = '1910'
webhook = 'https://nyxserverbot.herokuapp.com'
datawebhook = webhook + '/data'
def sendData(data, webhook=datawebhook):
subprocess.call("curl -X POST -H 'Content-type: application/text' --data '\"{}\"' {}".format(data, webhook), shell=True)
@app.route("/data", methods=['POST'])
def data():
data = json.loads(request.data, strict=False)
print("data received '{}'".format(str(data)))
if data == 'Status':
subprocess.call('echo {} | sudo -S {}'.format(pwd, 'echo root'), shell=True)
# sent data with curl to heroku app
cpuPercentage = subprocess.getoutput("mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12\"%\" }'")
cpuTemp = subprocess.getoutput('echo {} | sudo -S {}'.format(pwd, 'tlp-stat -t | grep temp | awk \'{print $4}\''))
gpuTemp = subprocess.getoutput('nvidia-smi | grep N/A | awk \'$3 ~ /[1-9.]+/ {print $3}\'')
storagePercent = subprocess.getoutput('df --output=pcent / | awk -F "%" "NR==2{print $1}"')
batteryStatus = subprocess.getoutput('echo {} | sudo -S {}'.format(pwd, 'tlp-stat -b | grep status | awk \'{print $3}\''))
status = 'CPU percentage : {}\nCPU temperature : {} C\nGPU Temperature : {}\nStorage Percentage : used{}\nBattery Status : {}\n'.format(cpuPercentage, cpuTemp, gpuTemp, storagePercent, batteryStatus)
sendData(status)
elif data == 'reboot':
print(data)
subprocess.call('reboot', shell=True)
elif data == 'tunnelrestart':
print(data)
subprocess.call('python3 ngrokserverstart.py', shell=True)
elif data == 'killSSH':
print(data)
subprocess.call("pkill -f 'ssh'", shell=True)
elif data == 'killTCP':
print(data)
subprocess.call("pkill -f 'tcp'", shell=True)
elif data == 'killall':
subprocess.call("killall ngrok", shell=True)
print(data)
elif data == 'shutdown':
subprocess.call('echo {} | sudo -S {}'.format(pwd, 'shutdown -h now'), shell=True)
return data
@app.route("/status", methods=['GET'])
def status():
return jsonify(formatStatus(getStatus()))
import os
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
|
import os
import mimetypes
def file_inspector(filename):
'Reports posix filesystem attributes for a file'
_, ext = os.path.splitext(filename)
s = os.stat(filename)
content_type, encoding = mimetypes.guess_type(filename)
# ignoreing ctime as rarely relevant
return {
#'created': [time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(s.st_ctime))],
'extension': [ext[1:].lower()],
'mimetype': content_type.split('/'),
'size': ["{0:d}kB".format(int(s.st_size/1000))]
}
file_inspector.extensions = [".*"]
file_inspector.version = '1.0.0'
|
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
class turtlebot_move():
def __init__(self):
rospy.init_node('turtlebot_move', anonymous=False)
rospy.loginfo("Press CTRL + C to terminate")
rospy.on_shutdown(self.shutdown)
self.set_velocity = rospy.Publisher('cmd_vel_mux/input/navi', Twist, queue_size=10)
vel = Twist()
vel.linear.x = 0.5
vel.angular.z = 0
vel_t = Twist()
vel_t.linear.x = 0
vel_t.angular.z = 1.57079632 #robot will rotate at 1.57rad /s for 2 sec
#set update at 10 Hz
rate = rospy.Rate(10);
#allows the robot to move forward for 0.5m/s for 10 seconds
#robot then turns 90 degrees
#sampling rate of 10hZ (0.5m/s *10 seconds* 10 ticks per second = 50)
#(0.5m/s *2 seconds* 10 ticks per second = 10)
while (True):
for i in range(50):
self.set_velocity.publish(vel)
rate.sleep()
for i in range(10):
self.set_velocity.publish(vel_t)
rate.sleep()
while not rospy.is_shutdown():
self.set_velocity.publish(vel)
rate.sleep()
def shutdown(self):
rospy.loginfo("Stop Action")
stop_vel = Twist()
stop_vel.linear.x = 0
stop_vel.angular.z = 0
self.set_velocity.publish(stop_vel)
rospy.sleep(1)
if __name__ == '__main__':
try:
turtlebot_move()
except rospy.ROSInterruptException:
rospy.loginfo("Action terminated.")
|
"""2D convolutional model for Allen data."""
layer_structure = [
{
'layers': ['_pass'],
'names': ['contextual'],
'hardcoded_erfs': {
'SRF': 1,
'CRF_excitation': 1,
'CRF_inhibition': 1,
'SSN': 9,
'SSF': 29
},
'normalization': ['contextual'],
'normalization_target': ['pre'],
'normalization_aux': {
'timesteps': 10,
'regularization_targets': { # Modulate sparsity
'q_t': {
'regularization_type': 'l1',
'regularization_strength': 0.01
},
't_t': {
'regularization_type': 'l1',
'regularization_strength': 0.1
},
'p_t': {
'regularization_type': 'l1',
'regularization_strength': 0.1
},
}
},
}
]
output_structure = [
{
'layers': ['gather'],
'aux': {
'h': 25,
'w': 25
}, # Output size
'names': ['gather'],
},
{
'layers': ['fc'],
'weights': [1],
'names': ['fc1'],
}
]
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 01:44:32 2019
@author: Owner
"""
import json
from sklearn.metrics import davies_bouldin_score
import numpy as np
import utm
from sklearn import metrics
path = "\\Users\\Owner\\Desktop\\PythonCodes\\ML_Project\\FINAL_DBSCAN_200M_250p_c.geojson"
with open(path) as f:
features_list = json.load(f)["features"]
points = []
labels = []
for feature in features_list:
input_lat,input_lon = [feature['geometry']['coordinates'][0],
feature['geometry']['coordinates'][1]]
utmTup = utm.from_latlon(input_lat, input_lon)
point = [utmTup[0],utmTup[1]]
clusterID = feature['properties']['CLUSTER_ID']
points.append(point)
labels.append(clusterID)
X = np.array(points)
labels = np.array(labels)
#print(X)
#print(labels)
print("FINAL_HDBSCAN_125p_c")
print("Davies-Bouldin Index: ",davies_bouldin_score(X, labels))
print("Calinski-Harabasz: ",metrics.calinski_harabasz_score(X, labels))
print("Silhouette Score: ",metrics.silhouette_score(X, labels, metric='euclidean')) |
from django.conf.urls import url
from market import views
urlpatterns = [
url(r'^goods/',views.GoodsView.as_view()),
url(r'^foodtype/',views.FoodTypesView.as_view())
]
|
import click
from rq_mantis.app import app
@click.command()
@click.option('--redis-url', default='redis://localhost:6379', help='Redis url eg. redis://localhost:6379')
@click.option('--debug', default=False, help='Debug mode')
@click.option('--host', default='127.0.0.1', help='Host')
@click.option('--port', default=5000, help='Port')
def run(redis_url, debug, host, port):
app.config['REDIS_URL'] = redis_url
app.run(host, port, debug)
if __name__ == '__main__':
run()
|
import cv2
img=cv2.imread('back.png')
gray=cv2.imread('back.png',cv2.IMREAD_GRAYSCALE)
cv2.imshow('dog image',img)
cv2.imshow('gra dog image',gray)
cv2.waitKey(0)
cv2.destroyAllWindows() |
# Generated by Django 3.0 on 2020-01-22 09:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('restaurants', '0004_remove_restaurant_created'),
]
operations = [
migrations.RemoveField(
model_name='restaurant',
name='restaurant_category',
),
migrations.AddField(
model_name='restaurant',
name='category',
field=models.CharField(choices=[('Asian', 'Asian'), ('Italian', 'Italian'), ('Mexican', 'Mexican'), ('Swiss', 'Swiss')], default='Asian', max_length=100, verbose_name='category'),
),
]
|
import sqlite3
import Tkinter
window=Tkinter.Tk()
con=sqlite3.connect('login.db')
cur=con.cursor()
# cur.execute('CREATE TABLE LoginDetails (Name TEXT , Username TEXT , Password TEXT, Account FLOAT)')
# cur.execute("INSERT INTO LoginDetails VALUES('Andikan Bassey ' , 'Lambo' , 'andikan', 20000)")
def search(username, password):
query= "SELECT name, password FROM LoginDetails WHERE UserName = '"+username+ "' AND Password = '"+password+ "'"
cur.execute(query)
ans = cur.fetchall()
print(ans)
def login():
window = Tkinter.Tk()
labe1=Tkinter.Label(window, text='Welcome')
labe1.pack()
window.mainloop()
#models
username = Tkinter.StringVar()
password = Tkinter.StringVar()
label1=Tkinter.Label(window, text='Username')
label1.pack()
entry1=Tkinter.Entry(window, textvariable = username)
entry1.pack()
label2=Tkinter.Label(window, text='Password')
label2.pack()
entry2=Tkinter.Entry(window, textvariable = password)
entry2.pack()
button=Tkinter.Button(window,text='Login' , command =login)
button.pack()
window.mainloop()
|
#!/usr/bin/env python
#
# This file is part of the Fun SDK (fsdk) project. The complete source code is
# available at https://github.com/luigivieira/fsdk.
#
# Copyright (c) 2016-2017, Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import csv
import cv2
from collections import OrderedDict
import numpy as np
#=============================================
class FaceData:
"""
Represents the data of a face detected on an image.
"""
_chinLine = [i for i in range(5, 12)]
"""
Indexes of the landmarks at the chin line.
"""
_jawLine = [i for i in range(17)]
"""
Indexes of the landmarks at the jaw line.
"""
_rightEyebrow = [i for i in range(17,22)]
"""
Indexes of the landmarks at the right eyebrow.
"""
_leftEyebrow = [i for i in range(22,27)]
"""
Indexes of the landmarks at the left eyebrow.
"""
_noseBridge = [i for i in range(27,31)]
"""
Indexes of the landmarks at the nose bridge.
"""
_lowerNose = [i for i in range(30,36)]
"""
Indexes of the landmarks at the lower nose.
"""
_rightEye = [i for i in range(36,42)]
"""
Indexes of the landmarks at the right eye.
"""
_leftEye = [i for i in range(42,48)]
"""
Indexes of the landmarks at the left eye.
"""
_rightUpperEyelid = [37, 38]
"""
Indexes of the landmarks at the upper eyelid of the right eye.
"""
_rightLowerEyelid = [41, 40]
"""
Indexes of the landmarks at the lower eyelid of the right eye.
"""
_leftUpperEyelid = [43, 44]
"""
Indexes of the landmarks at the upper eyelid of the left eye.
"""
_leftLowerEyelid = [47, 46]
"""
Indexes of the landmarks at the lower eyelid of the left eye.
"""
_outerLip = [i for i in range(48,60)]
"""
Indexes of the landmarks at the outer lip.
"""
_innerLip = [i for i in range(60,68)]
"""
Indexes of the landmarks at the inner lip.
"""
header = lambda: ['face.left', 'face.top',
'face.right', 'face.bottom'] + \
list(np.array([['face.landmark.{:d}.x'.format(i),
'face.landmark.{:d}.y'.format(i)]
for i in range(68)]).reshape(-1)) + \
['face.distance', 'face.gradient']
"""
Helper static function to create the header useful for saving FaceData
instances to a CSV file.
"""
_poseModel = np.array([
(0.0, 0.0, 0.0), # Nose tip
(0.0, -330.0, -65.0), # Chin bottom
(-225.0, 170.0, -135.0), # Left eye left corner
(225.0, 170.0, -135.0), # Right eye right corner
(-150.0, -150.0, -125.0), # Left mouth corner
(150.0, -150.0, -125.0) # Right mouth corner
])
"""
Arbitrary facial model for pose estimation considering only 6 facial
landmarks (nose tip, chin bottom, left eye left corner, right eye right
corner, left mouth corner and right mouth corner).
"""
_cameraMatrix = np.array([
[1470.178963530401, 0, 654.91904910619],
[0, 1476.4198888732042, 364.0557064295808],
[0, 0, 1]
], dtype = 'float')
"""
Matrix of the camera intrinsic parameters. These values were obtained with
the calibration of the camera with 24 images of a 9x7 checked-board pattern.
"""
_distCoeffs = np.array([
[0.004101556323186707], [0.22084309786735434],
[0.0009548613012245966], [0.0022172138428918665]
])
"""
Vector of distortion coefficients of the camera. These values were obtained
with the calibration of the camera with 11 images of a 9x7 checked-board
pattern.
"""
def __init__(self, region = (0, 0, 0, 0),
landmarks = [0 for i in range(136)],
distance = 0.0, gradient = 0.0):
"""
Class constructor.
Parameters
----------
region: tuple
Left, top, right and bottom coordinates of the region where the face
is located in the image used for detection. The default is all 0's.
landmarks: list
List of x, y coordinates of the 68 facial landmarks in the image
used for detection. The default is all 0's.
distance: float
Estimated distance in centimeters of the face to the camera. The
default is 0.0.
gradient: float
Gradient of the distance based on neighbor frames. The default is
0.0.
"""
self.region = region
"""
Region where the face is found in the image used for detection. This is
a tuple of int values describing the region in terms of the top-left and
bottom-right coordinates where the face is located.
"""
self.landmarks = landmarks
"""
Coordinates of the landmarks on the image. This is a numpy array of
pair of values describing the x and y positions of each of the 68 facial
landmarks.
"""
self.distance = distance
"""
Estimated distance in centimeters of the face to the camera.
"""
self.gradient = gradient
"""
Gradient of the distance based on neighbor frames. This value is not
updated by the face detector class. It is just used during the
extraction of features for the assessment of fun.
"""
#---------------------------------------------
def copy(self):
"""
Deep copies the data of the face.
Deep copying means that no mutable attribute (like tuples or lists) in
the new copy will be shared with this instance. In that way, the two
copies can be changed independently.
Returns
-------
ret: FaceData
New instance of the FaceDate class deep copied from this instance.
"""
return FaceData(self.region, self.landmarks.copy(),
self.distance, self.gradient)
#---------------------------------------------
def isEmpty(self):
"""
Check if the FaceData object is empty.
An empty FaceData object have region and landmarks with all 0's.
Returns
------
response: bool
Indication on whether this object is empty.
"""
return all(v == 0 for v in self.region) or \
all(vx == 0 and vy == 0 for vx, vy in self.landmarks)
#---------------------------------------------
def crop(self, image):
"""
Crops the given image according to this instance's region and landmarks.
This function creates a subregion of the original image according to the
face region coordinates, and also a new instance of FaceDate object with
the region and landmarks adjusted to the cropped image.
Parameters
----------
image: numpy.array
Image that contains the face.
Returns
-------
croppedImage: numpy.array
Subregion in the original image that contains only the face. This
image is shared with the original image (i.e. its data is not
copied, and changes to either the original image or this subimage
will affect both instances).
croppedFace: FaceData
New instance of FaceData with the face region and landmarks adjusted
to the croppedImage.
"""
left = self.region[0]
top = self.region[1]
right = self.region[2]
bottom = self.region[3]
croppedImage = image[top:bottom+1, left:right+1]
croppedFace = self.copy()
croppedFace.region = (0, 0, right - left, bottom - top)
croppedFace.landmarks = [[p[0]-left, p[1]-top] for p in self.landmarks]
return croppedImage, croppedFace
#---------------------------------------------
def draw(self, image, drawRegion = None, drawFaceModel = None):
"""
Draws the face data over the given image.
This method draws the facial landmarks (in red) to the image. It can
also draw the region where the face was detected (in blue) and the face
model used by dlib to do the prediction (i.e., the connections between
the landmarks, in magenta). This drawing is useful for visual inspection
of the data - and it is fun! :)
Parameters
------
image: numpy.array
Image data where to draw the face data.
drawRegion: bool
Optional value indicating if the region area should also be drawn.
The default is True.
drawFaceModel: bool
Optional value indicating if the face model should also be drawn.
The default is True.
Returns
------
drawnImage: numpy.array
Image data with the original image received plus the face data
drawn. If this instance of Face is empty (i.e. it has no region
and no landmarks), the original image is simply returned with
nothing drawn on it.
"""
if self.isEmpty():
raise RuntimeError('Can not draw the contents of an empty '
'FaceData object')
# Check default arguments
if drawRegion is None:
drawRegion = True
if drawFaceModel is None:
drawFaceModel = True
# Draw the region if requested
if drawRegion:
cv2.rectangle(image, (self.region[0], self.region[1]),
(self.region[2], self.region[3]),
(0, 0, 255), 2)
# Draw the positions of landmarks
color = (0, 255, 255)
for i in range(68):
cv2.circle(image, tuple(self.landmarks[i]), 1, color, 2)
# Draw the face model if requested
if drawFaceModel:
c = (0, 255, 255)
p = np.array(self.landmarks)
cv2.polylines(image, [p[FaceData._jawLine]], False, c, 2)
cv2.polylines(image, [p[FaceData._leftEyebrow]], False, c, 2)
cv2.polylines(image, [p[FaceData._rightEyebrow]], False, c, 2)
cv2.polylines(image, [p[FaceData._noseBridge]], False, c, 2)
cv2.polylines(image, [p[FaceData._lowerNose]], True, c, 2)
cv2.polylines(image, [p[FaceData._leftEye]], True, c, 2)
cv2.polylines(image, [p[FaceData._rightEye]], True, c, 2)
cv2.polylines(image, [p[FaceData._outerLip]], True, c, 2)
cv2.polylines(image, [p[FaceData._innerLip]], True, c, 2)
return image
#---------------------------------------------
def toList(self):
"""
Gets the contents of the FaceData as a list of values (useful to
write the data to a CSV file), in the order defined by header().
Returns
-------
ret: list
A list with all values of the this FaceData.
"""
ret = [self.region[0], self.region[1],
self.region[2], self.region[3]] + \
list(np.array(self.landmarks).reshape(-1)) + \
[self.distance, self.gradient]
return ret
#---------------------------------------------
def fromList(self, values):
"""
Sets the contents of the Face Data from a list of values (useful to
read the data from a CSV file, for instance), in the order defined by
the method header().
Parameters
----------
values: list
A list with all values of of this data. The values are expected
as strings (since they are probably read from a CSV file), so they
will be converted accordingly to the target types.
Exceptions
-------
exception: RuntimeError
Raised if the list has unexpected number of values.
exception: ValueError
Raised if any position in the list has an unexpected value/type.
"""
if len(values) != len(FaceData.header()):
raise RuntimeError
self.region = (int(values[0]), int(values[1]),
int(values[2]), int(values[3]))
self.landmarks = list(np.array(values[4:140], dtype=int).reshape(68, 2))
self.distance = float(values[140])
self.gradient = float(values[141])
#---------------------------------------------
def calculateDistance(self):
"""
Estimate the distance of the face from the camera using pose estimation.
"""
self.distance = 0.0
if self.isEmpty():
return
# Get the 2D positions of the pose model points detected in the image
p = self.landmarks
points = np.array([
tuple(p[30]), # Nose tip
tuple(p[8]), # Chin
tuple(p[36]), # Left eye left corner
tuple(p[45]), # Right eye right corner
tuple(p[48]), # Left Mouth corner
tuple(p[54]) # Right mouth corner
], dtype = 'float')
# Estimate the pose of the face in the 3D world
ret, rot, trans = cv2.solvePnP(FaceData._poseModel,
points, FaceData._cameraMatrix,
FaceData._distCoeffs,
flags=cv2.SOLVEPNP_ITERATIVE)
# The estimated distance is the absolute value on the Z axis. That value
# is divided by 100 to approximate to the real value in centimeters (due
# to the face model being scaled by ~ 10x in millimeters).
d = abs(trans[2][0] / 100)
# Error verification. I don't know exactly why, but for a few frames in
# *one or two* of the test videos the value returned by solvePnP is
# totally bizarre (too big or too low). Perhaps this has to do with the
# calibration of the camera. But at this time, it is easier to not have
# a distance calculated in those very rare scenarios. The value used in
# this cases is 0; the distance update code that relies on this calculus
# ignores 0s by using the same value from a previous frame.
#
# The expected range of distance is between 20 and 60 cm, so "extreme"
# values (bellow 10 and above 100) are considered errors.
if d < 10 or d > 100:
self.distance = 0.0
else:
self.distance = d
#=============================================
class GaborData:
"""
Represents the responses of the Gabor bank to the facial landmarks.
"""
header = lambda: ['kernel.{:d}.landmark.{:d}'.format(k, i)
for k in range(32)
for i in range(68)]
"""
Helper static function to create the header useful for saving GaborData
instances to a CSV file.
"""
def __init__(self, features = [0.0 for i in range(2176)]):
"""
Class constructor.
Parameters
----------
features: list
Responses of the filtering with the bank of Gabor kernels at each of
the facial landmarks. The default is all 0's.
"""
self.features = features
"""
Responses of the filtering with the bank of Gabor kernels at each of the
facial landmarks. The Gabor bank used has 32 kernels and there are 68
landmarks, hence this is a vector of 2176 values (32 x 68).
"""
#---------------------------------------------
def copy(self):
"""
Deep copies the data of this object.
Deep copying means that no mutable attribute (like tuples or lists) in
the new copy will be shared with this instance. In that way, the two
copies can be changed independently.
Returns
-------
ret: GaborData
New instance of the GaborData class deep copied from this instance.
"""
return GaborData(self.features.copy())
#---------------------------------------------
def isEmpty(self):
"""
Check if the object is empty.
Returns
------
response: bool
Indication on whether this object is empty.
"""
return all(v == 0 for v in self.features)
#---------------------------------------------
def toList(self):
"""
Gets the contents of this object as a list of values (useful to
write the data to a CSV file), in the order defined by header().
Returns
-------
ret: list
A list with all values of the this GaborData.
"""
ret = self.features.copy()
return ret
#---------------------------------------------
def fromList(self, values):
"""
Sets the contents of the Gabor Data from a list of values (useful to
read the data from a CSV file, for instance), in the order defined by
the method header().
Parameters
----------
values: list
A list with all values of of this data. The values are expected
as strings (since they are probably read from a CSV file), so they
will be converted accordingly to the target types.
Exceptions
-------
exception: RuntimeError
Raised if the list has unexpected number of values.
exception: ValueError
Raised if any position in the list has an unexpected value/type.
"""
if len(values) != len(GaborData.header()):
raise RuntimeError
self.features = [float(f) for f in values]
#=============================================
class EmotionData:
"""
Represents the probabilities of the prototypic emotions detected on a frame.
"""
header = lambda: ['emotion.neutral', 'emotion.happiness', 'emotion.sadness',
'emotion.anger', 'emotion.fear', 'emotion.surprise',
'emotion.disgust']
"""
Helper static function to create the header useful for saving EmotionData
instances to a CSV file.
"""
def __init__(self, emotions = OrderedDict([
('neutral', 0.0), ('happiness', 0.0), ('sadness', 0.0),
('anger', 0.0), ('fear', 0.0), ('surprise', 0.0),
('disgust', 0.0)
])):
"""
Class constructor.
Parameters
----------
emotions: dict
Dictionary with the probabilities of each prototypical emotion plus
the neutral face. The default is a dictionary with all probabilities
equal to 0.0.
"""
self.neutral = emotions['neutral']
"""
Probabilities of a neutral face.
"""
self.happiness = emotions['happiness']
"""
Probabilities of a happiness face.
"""
self.sadness = emotions['sadness']
"""
Probabilities of a sadness face.
"""
self.anger = emotions['anger']
"""
Probabilities of an anger face.
"""
self.fear = emotions['fear']
"""
Probabilities of a fear face.
"""
self.surprise = emotions['surprise']
"""
Probabilities of a surprise face.
"""
self.disgust = emotions['disgust']
"""
Probabilities of a disgust face.
"""
#---------------------------------------------
def copy(self):
"""
Deep copies the data of this object.
Deep copying means that no mutable attribute (like tuples or lists) in
the new copy will be shared with this instance. In that way, the two
copies can be changed independently.
Returns
-------
ret: EmotionData
New instance of the EmotionData class deep copied from this object.
"""
ret = EmotionData()
ret.neutral = self.neutral
ret.happiness = self.happines
ret.sadness = self.sadness
ret.anger = self.anger
ret.fear = self.fear
ret.surprise = self.surprise
ret.disgust = self.disgust
return ret
#---------------------------------------------
def isEmpty(self):
"""
Check if the object is empty.
Returns
------
response: bool
Indication on whether this object is empty.
"""
return all(v == 0.0 for v in [self.neutral, self.happiness,
self.sadness, self.anger, self.fear,
self.surprise, self.disgust])
#---------------------------------------------
def toList(self):
"""
Gets the contents of this object as a list of values (useful to
write the data to a CSV file), in the order defined by header().
Returns
-------
ret: list
A list with all values of the this EmotionData.
"""
ret = [self.neutral, self.happiness, self.sadness,
self.anger, self.fear, self.surprise, self.disgust]
return ret
#---------------------------------------------
def fromList(self, values):
"""
Sets the contents of the Emotion Data from a list of values (useful to
read the data from a CSV file, for instance), in the order defined by
the method header().
Parameters
----------
values: list
A list with all values of of this data. The values are expected
as strings (since they are probably read from a CSV file), so they
will be converted accordingly to the target types.
Exceptions
-------
exception: RuntimeError
Raised if the list has unexpected number of values.
exception: ValueError
Raised if any position in the list has an unexpected value/type.
"""
if len(values) != len(EmotionData.header()):
raise RuntimeError
self.neutral = float(values[0])
self.happiness = float(values[1])
self.sadness = float(values[2])
self.anger = float(values[3])
self.fear = float(values[4])
self.surprise = float(values[5])
self.disgust = float(values[6])
#=============================================
class BlinkData:
"""
Represents the blinking information related to a frame of video.
"""
header = lambda: ['blink.count', 'blink.rate']
"""
Helper static function to create the header useful for saving BlinkData
instances to a CSV file.
"""
def __init__(self, count = 0, rate = 0):
"""
Class constructor.
Parameters
----------
count: int
Total number of blinks detected until this frame of the video. The
default is 0.
rate: int
Blinking rate (in blinks per minute) accounted until this frame of
the video. The default is 0.
"""
self.count = count
"""
Total number of blinks detected until this frame of the video.
"""
self.rate = rate
"""
Blinking rate (in blinks per minute) accounted until this frame of the
video.
"""
#---------------------------------------------
def copy(self):
"""
Deep copies the data of this object.
Deep copying means that no mutable attribute (like tuples or lists) in
the new copy will be shared with this instance. In that way, the two
copies can be changed independently.
Returns
-------
ret: BlinkData
New instance of the BlinkData class deep copied from this instance.
"""
return BlinkData(self.count, self.rate)
#---------------------------------------------
def isEmpty(self):
"""
Check if the object is empty.
Returns
------
response: bool
Indication on whether this object is empty.
"""
return self.count == 0 or self.rate == 0
#---------------------------------------------
def toList(self):
"""
Gets the contents of this object as a list of values (useful to
write the data to a CSV file), in the order defined by header().
Returns
-------
ret: list
A list with all values of the this GaborData.
"""
return [self.count, self.rate]
#---------------------------------------------
def fromList(self, values):
"""
Sets the contents of the Blink Data from a list of values (useful to
read the data from a CSV file, for instance), in the order defined by
the method header().
Parameters
----------
values: list
A list with all values of of this data. The values are expected
as strings (since they are probably read from a CSV file), so they
will be converted accordingly to the target types.
Exceptions
-------
exception: RuntimeError
Raised if the list has unexpected number of values.
exception: ValueError
Raised if any position in the list has an unexpected value/type.
"""
if len(values) != len(BlinkData.header()):
raise RuntimeError
self.count = int(values[0])
self.rate = int(values[1])
#=============================================
class FrameData:
"""
Represents the data of features extracted from a frame of a video and used
for the assessment of fun.
"""
header = lambda: ['frame'] + FaceData.header() + \
EmotionData.header() + BlinkData.header()
"""
Helper static function to create the header for storing frames of data.
"""
#---------------------------------------------
def __init__(self, frameNum):
"""
Class constructor.
Parameters
----------
frameNum: int
Number of the frame to which the data belongs to.
"""
self.frameNum = frameNum
"""
Number of the frame to which the data belongs to.
"""
self.face = FaceData()
"""
Face detected in this frame.
"""
self.emotions = EmotionData()
"""
Probabilities of the prototypical emotions detected in this frame.
"""
self.blinks = BlinkData()
"""
Blinking information accounted until this frame.
"""
#---------------------------------------------
def toList(self):
"""
Gets the contents of the Frame Data as a list of values (useful to
write the data to a CSV file, for instance), in the order defined by
the method header().
Returns
-------
ret: list
A list with all values of the frame data.
"""
ret = [self.frameNum] + self.face.toList() + \
self.emotions.toList() + self.blinks.toList()
return ret
#---------------------------------------------
def fromList(self, values):
"""
Sets the contents of the Frame Data from a list of values (useful to
read the data from a CSV file, for instance), in the order defined by
the method header().
Parameters
----------
values: list
A list with all values of of this data. The values are expected
as strings (since they are probably read from a CSV file), so they
will be converted accordingly to the target types.
Exceptions
-------
exception: RuntimeError
Raised if the list has unexpected number of values.
exception: ValueError
Raised if any position in the list has an unexpected value/type.
"""
if len(values) != len(FrameData.header()):
raise RuntimeError
self.frameNum = int(values[0])
start = 1
end = start + len(FaceData.header())
self.face.fromList(values[start:end])
start = end
end = start + len(EmotionData.header())
self.emotions.fromList(values[start:end])
start = end
end = start + len(BlinkData.header())
self.blinks.fromList(values[start:end])
|
from datetime import date
from rest_framework.response import Response
from django.http import JsonResponse, HttpResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework import pagination
import jwt
from restapi import settings
from .models import Emp
from .serializers import HR_Serial, Emp_Serial
from rest_framework import generics, mixins, status
def decode(encoded):
try:
decrypt = jwt.decode(encoded, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.InvalidTokenError:
return dict({
'username': '',
'emp_id': 0
})
return decrypt
# Create your views here.
class Fire(generics.GenericAPIView, mixins.UpdateModelMixin):
queryset = Emp.objects.all()
serializer_class = HR_Serial
lookup_field = 'id'
def post(self, request, id):
querysets = Emp.objects.all()
entries = decode(request.headers.get('Authorisation'))
for data in querysets:
if entries['username'] == data.username and entries['id'] == data.emp_id and entries['role']:
print(request.data)
return self.update(request, id)
else:
return JsonResponse([{'message': 'Unauthorised'}], safe=False, status=status.HTTP_401_UNAUTHORIZED)
class HrView(generics.GenericAPIView, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin,
mixins.CreateModelMixin, mixins.DestroyModelMixin):
queryset = Emp.objects.all()
serializer_class = HR_Serial
lookup_field = 'id'
def get(self, request, id=None):
querysets = Emp.objects.all().filter(is_active=True)
entries = decode(request.headers.get('Authorisation'))
for data in querysets:
if entries['username'] == data.username and entries['id'] == data.emp_id:
if id:
return self.retrieve(request)
else:
return self.list(request)
else:
return JsonResponse([{'message': 'Unauthorised'}], safe=False, status=status.HTTP_401_UNAUTHORIZED)
def put(self, request, id):
querysets = Emp.objects.all()
entries = decode(request.headers.get('Authorisation'))
for data in querysets:
if entries['username'] == data.username and entries['id'] == data.emp_id:
return self.update(request, id)
else:
return JsonResponse([{'message': 'Unauthorised'}], safe=False, status=status.HTTP_401_UNAUTHORIZED)
def post(self, request):
querysets = Emp.objects.all()
counts = querysets.count()
serializer_class = Emp_Serial
entries = decode(request.headers.get('Authorisation'))
for data in querysets:
if entries['username'] == data.username and entries['id'] == data.emp_id:
request.data['emp_id'] = counts + 1
return self.create(request)
else:
return JsonResponse([{'message': 'Unauthorised'}], safe=False, status=status.HTTP_401_UNAUTHORIZED)
def delete(self, request, id):
querysets = Emp.objects.all()
entries = decode(request.headers.get('Authorisation'))
for data in querysets:
if entries['username'] == data.username and entries['id'] == data.emp_id and entries['role']:
return self.destroy(request, id)
else:
return JsonResponse([{'message': 'Unauthorised'}], safe=False, status=status.HTTP_401_UNAUTHORIZED)
class Bulk(generics.GenericAPIView, mixins.CreateModelMixin):
queryset = Emp.objects.all()
def post(self, request):
querysets = Emp.objects.all()
counts = querysets.count()
entries = decode(request.headers.get('Authorisation'))
for data in querysets:
if entries['username'] == data.username and entries['id'] == data.emp_id and entries['role']:
i = 1
for datas in request.data:
datas['emp_id'] = counts + i
serializer_class = Emp_Serial(data=datas)
if serializer_class.is_valid():
serializer_class.save()
i = i + 1
return Response(status=status.HTTP_201_CREATED)
else:
return JsonResponse([{'message': 'Unauthorised'}], safe=False, status=status.HTTP_401_UNAUTHORIZED)
class Search(generics.GenericAPIView):
def get(self, request):
try:
data = request.session['Authorization']
print(data)
except:
pass
if data:
return request.session['Authorisation']
else:
print('False')
return JsonResponse({
'message': 'False'
})
def post(self, request):
queryset = Emp.objects.all().filter(is_active=True)
isAdmin = False
for data in queryset:
if request.data['username'] == data.username and request.data['password'] == data.password:
if data.role == 'Admin':
isAdmin = True
payloads = jwt.encode({
'username': data.username,
'message': 'Found',
'role': isAdmin,
'id': data.id
}, settings.SECRET_KEY, algorithm='HS256')
payload = [{
'username': data.username,
'message': 'Found',
'role': isAdmin,
'id': data.id,
'secret': "".join(chr(x) for x in payloads)
}]
return JsonResponse(payload, safe=False)
return Response(status=status.HTTP_404_NOT_FOUND)
def put(self, request):
try:
print(request.session['Authorization'])
del request.session['Authorization']
except KeyError:
pass
return HttpResponse("You're logged out.")
class Empty(generics.GenericAPIView):
def get(self, id=None):
return JsonResponse([{'message': 'connected'}], safe=False)
class ExamplePagination(pagination.PageNumberPagination):
page_size = 2
page_size_query_param = 'pagesize'
class Sort(generics.ListAPIView):
serializer_class = HR_Serial
queryset = Emp.objects.all().filter(is_active=True)
filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter)
filter_fields = ('emp_id', 'name', 'username', 'email', 'created_date', 'role', 'is_active', 'end_date')
ordering_fields = ('emp_id', 'name', 'username', 'email', 'created_date', 'role', 'is_active', 'end_date')
search_fields = ('emp_id', 'name', 'username', 'email', 'created_date', 'role', 'is_active', 'end_date')
pagination_class = ExamplePagination
class Searching(generics.GenericAPIView, mixins.ListModelMixin):
serializer_class = HR_Serial
queryset = Emp.objects.all().filter(is_active=True)
filter_backends = (DjangoFilterBackend, OrderingFilter, SearchFilter)
filter_fields = ('emp_id', 'name', 'username', 'email', 'created_date', 'role')
ordering_fields = ('emp_id', 'name', 'username', 'email', 'created_date', 'role')
search_fields = ('emp_id', 'name', 'username', 'email', 'created_date', 'role')
pagination_class = ExamplePagination
def get(self, request):
querysets = Emp.objects.all().filter(is_active=True)
entries = decode(request.headers.get('Authorisation'))
authentication = request.session.get('sessionid')
for data in querysets:
if entries['username'] == data.username and entries['id'] == data.emp_id:
return self.list(request)
else:
return JsonResponse([{'message': 'Unauthorised'}], safe=False, status=status.HTTP_401_UNAUTHORIZED)
|
# Copyright 2016 Canonical Limited.
#
# This file is part of charm-helpers.
#
# charm-helpers is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3 as
# published by the Free Software Foundation.
#
# charm-helpers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with charm-helpers. If not, see <http://www.gnu.org/licenses/>.
from unittest import TestCase
from mock import patch
from charms_hardening.host.checks import pam
class PAMTestCase(TestCase):
@patch.object(pam.utils, 'get_settings', lambda x: {
'auth': {'pam_passwdqc_enable': True,
'retries': False}
})
def test_enable_passwdqc(self):
audits = pam.get_audits()
self.assertEqual(2, len(audits))
audit = audits[0]
self.assertTrue(isinstance(audit, pam.PasswdqcPAM))
audit = audits[1]
self.assertTrue(isinstance(audit, pam.DeletedFile))
self.assertEqual('/usr/share/pam-configs/tally2', audit.paths[0])
@patch.object(pam.utils, 'get_settings', lambda x: {
'auth': {'pam_passwdqc_enable': False,
'retries': True}
})
def test_disable_passwdqc(self):
audits = pam.get_audits()
self.assertEqual(1, len(audits))
self.assertFalse(isinstance(audits[0], pam.PasswdqcPAM))
@patch.object(pam.utils, 'get_settings', lambda x: {
'auth': {'pam_passwdqc_enable': False,
'retries': True}
})
def test_auth_retries(self):
audits = pam.get_audits()
self.assertEqual(1, len(audits))
self.assertTrue(isinstance(audits[0], pam.Tally2PAM))
|
# -*- coding: utf-8 -*-
"""Global pyprof2html's environment.
"""
from jinja2 import Environment, PackageLoader
__all__ = ['ENVIRON']
CODEC = 'utf-8'
ENVIRON = Environment(loader=PackageLoader('pyprof2html',
'./templates', encoding=CODEC))
|
from tkinter import *
from tkinter import ttk
from datetime import datetime, date
import locale
locale.setlocale(locale.LC_ALL, ("es_ES", "UTF-8"))
HEIGHTBTN = 50
WIDTHBTN = 68
class Header(ttk.Frame):
cadena = ''
def __init__(self, parent):
ttk.Frame.__init__(self, parent, width=7*WIDTHBTN, height=0.7*HEIGHTBTN)
self.pack_propagate(0)
self.__lbl = ttk.Label(self, text=self.cadena, anchor='center', font=('Helvetica', '21', 'bold'), background='white', foreground='black', borderwidth='1', relief='ridge')
self.__lbl.pack(side=TOP, fill=BOTH, expand=True)
def valor(self, texto):
self.cadena = texto
self.__lbl.config(text=self.cadena)
class CalendButton(ttk.Frame):
def __init__(self, parent, text, command, wbtn=0.5, hbtn=0.5):
ttk.Frame.__init__(self, parent, width=wbtn*WIDTHBTN, height=hbtn*HEIGHTBTN)
self.pack_propagate(0)
s = ttk.Style()
s.theme_use('alt')
s.configure('my.TButton', font=('Helvetica', '11', 'bold'))
self.__b = ttk.Button(self, style='my.TButton', text=text, command=command)
self.__b.pack(side=TOP, fill=BOTH, expand=True)
class WeekDay(ttk.Frame):
def __init__(self, parent, text):
ttk.Frame.__init__(self,parent, width=WIDTHBTN, height=0.3*HEIGHTBTN)
self.pack_propagate(0)
self.__weekDay = ttk.Label(self, text=text, font='Helvetica 7', anchor='center', background='white', foreground='black', borderwidth='1', relief='ridge')
self.__weekDay.pack(side=TOP, fill=X, expand=False)
class MonthDay(ttk.Frame):
cadenaDia = ''
def __init__(self, parent, onClic):
ttk.Frame.__init__(self, parent, width=WIDTHBTN, height=HEIGHTBTN)
self.pack_propagate(0)
self.onClic = onClic
m = ttk.Style()
m.theme_use('alt')
m.configure('my.TLabel', font=('Helvetica', '21', 'bold'), anchor='se', background='white', borderwidth='1', relief='ridge')
self.monthDay = ttk.Label(self, text=self.cadenaDia, style='my.TLabel', padding=4)
self.monthDay.pack(side=TOP, fill=BOTH, expand=True)
def valor(self, texto, color):
self.cadenaDia = texto
if color in ('red', 'black'):
labelDia = self.cadenaDia.day
self.monthDay.config(text=labelDia, foreground=color)
self.monthDay.bind("<Button-1>", self.changeColor)
if color in ('grey'):
self.monthDay.config(text=self.cadenaDia, foreground=color)
def changeColor(self, event):
try:
if isinstance(self.cadenaDia, date):
self.monthDay.config(foreground='blue')
fechaElegida = str(self.cadenaDia.day) + ' de ' + (self.cadenaDia.strftime("%B")).title() + ' de ' + str(self.cadenaDia.year)
self.onClic(fechaElegida)
except:
return None
class Display(ttk.Frame):
def __init__(self, parent):
ttk.Frame.__init__(self, parent, width=7*WIDTHBTN, height=HEIGHTBTN)
self.pack_propagate(0)
fechaElegida = str(date.today().day) + ' de ' + (date.today().strftime("%B")).title() + ' de ' + str(date.today().year)
self.date = ttk.Label(self, text=fechaElegida, font='Helvetica 12', anchor='center', background='white', foreground='black', borderwidth='1', relief='ridge')
self.date.pack(side=TOP, fill=BOTH, expand=True)
class Calendar(ttk.Frame):
listDays = []
hoy = date.today()
hoy = hoy.replace(day=1)
def __createCalendar(self):
layoutCalendar = ttk.Frame(self, name='layoutCalendar')
for rowMonth in range(2, 8):
for columnMonth in range(0, 7):
self.day = MonthDay(self, self.informaDia)
self.day.grid(row=rowMonth, column=columnMonth)
self.listDays.append(self.day)
return layoutCalendar
def informaDia(self, valor):
self.fxBox.date.config(text=valor)
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
cadena = self.rellenaCab(self.hoy)
self.cabecera = Header(self)
self.cabecera.grid(column=0, row=0, columnspan=7)
self.cabecera.valor(cadena)
self.forwYear = CalendButton(self, text='>>', command=lambda: self.operar('>>', self.hoy)).grid(column=6, row=0, sticky=W, ipadx=3)
self.forwMonth = CalendButton(self, text='>', command=lambda: self.operar('>', self.hoy)).grid(column=5, row=0, sticky=E, ipadx=3, padx=5)
self.backYear = CalendButton(self, text='<<', command=lambda: self.operar('<<', self.hoy)).grid(column=0, row=0, sticky=E, ipadx=3)
self.backMonth = CalendButton(self, text='<', command=lambda: self.operar('<', self.hoy)).grid(column=1, row=0, sticky=W, ipadx=3, padx=5)
self.Monday = WeekDay(self, text='Lunes').grid(column=0, row=1)
self.Tuesday = WeekDay(self, text='Martes').grid(column=1, row=1)
self.Wednesday = WeekDay(self, text='Miércoles').grid(column=2, row=1)
self.Thursday = WeekDay(self, text='Jueves').grid(column=3, row=1)
self.Friday = WeekDay(self, text='Viernes').grid(column=4, row=1)
self.Saturday = WeekDay(self, text='Sábado').grid(column=5, row=1)
self.Sunday = WeekDay(self, text='Domingo').grid(column=6, row=1)
self.layoutCalendar = self.__createCalendar()
self.generaCalendar(self.hoy)
self.fxBox = Display(self)
self.fxBox.grid(column=0, row=8, columnspan=7)
def generaCalendar(self, hoy):
mes = self.hoy.month
if mes == 1:
mesAnt = 12
else:
mesAnt = self.hoy.month - 1
diasMesAct = self.calcDiasMes(mes)
diasMesAnt = self.calcDiasMes(mesAnt)
firstDay = self.hoy.replace(day=1)
indMesAct = firstDay.weekday()
indMesAnt = indMesAct - 1
for diaMesAnt in range(diasMesAnt, diasMesAnt-indMesAnt-1, -1):
self.listDays[indMesAnt].valor(diaMesAnt, 'grey')
indMesAnt -= 1
for diaMesAct in range(1, diasMesAct+1):
self.diaCalendar = self.hoy.replace(day=diaMesAct)
if indMesAct in (5,6,12,13,19,20,26,27,33,34,40,41):
self.listDays[indMesAct].valor(self.diaCalendar, 'red')
else:
self.listDays[indMesAct].valor(self.diaCalendar, 'black')
indMesAct += 1
diaMesNew = 1
while indMesAct < 42:
self.listDays[indMesAct].valor(diaMesNew, 'grey')
diaMesNew += 1
indMesAct += 1
def rellenaCab(self, hoy):
return (hoy.strftime("%B")).title() + ' ' + str(hoy.year)
def calcDiasMes(self, month):
if month in (1,3,5,7,8,10,12):
diasMes = 31
elif month in (4,6,9,11):
diasMes = 30
elif month == 2:
anno = self.hoy.year
if self.esBisiesto(anno):
diasMes = 29
else:
diasMes = 28
return diasMes
def esBisiesto(self, year):
return (year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))
def operar(self, operacion, hoy):
self.layoutCalendar.destroy()
if operacion == '>>':
newDate = self.hoy.replace(year=self.hoy.year+1)
self.hoy = newDate
newCab = self.rellenaCab(self.hoy)
self.cabecera.valor(newCab)
self.generaCalendar(self.hoy)
elif operacion == '>':
if self.hoy.month == 12:
newDate = self.hoy.replace(year=self.hoy.year+1, month=1)
else:
newDate = self.hoy.replace(month=self.hoy.month+1)
self.hoy = newDate
newCab = self.rellenaCab(self.hoy)
self.cabecera.valor(newCab)
self.generaCalendar(self.hoy)
elif operacion == '<<':
newDate = self.hoy.replace(year=self.hoy.year-1)
self.hoy = newDate
newCab = self.rellenaCab(self.hoy)
self.cabecera.valor(newCab)
self.generaCalendar(self.hoy)
elif operacion == '<':
if self.hoy.month == 1:
newDate = self.hoy.replace(year=self.hoy.year-1, month=12)
else:
newDate = self.hoy.replace(month=self.hoy.month-1)
self.hoy = newDate
newCab = self.rellenaCab(self.hoy)
self.cabecera.valor(newCab)
self.generaCalendar(self.hoy)
|
__description__ = \
"""
Control a clock that displays an RGB value to represent time.
"""
__author__ = "Michael J. Harms"
__date__ = "2018-04-30"
import time, datetime, json, sys, copy, multiprocessing, math
class Clock:
"""
Control leds to display time as a color.
"""
def __init__(self,
update_interval=0.1,
brightness=1.0,
min_brightness=0.05):
"""
update_interval: how often to update the clock in seconds.
brightness: overall brightness of the clock (between 0 and 1). If an
ambient light sensor is used, the brightness scalar will
be applied on top of brightness changes indicated by the
sensor.
min_brightness: minimum brightness of clock
"""
self._update_interval = update_interval
if self._update_interval <= 0:
err = "update interval must be greater than zero.\n"
raise ValueError(err)
self._brightness = brightness
if self._brightness < 0 or self._brightness > 1:
err = "brightness must be between 0 and 1.\n"
raise ValueError(err)
self._min_brightness = min_brightness
if self._min_brightness < 0 or self._min_brightness > 1:
err = "minimum brightness must be between 0 and 1.\n"
raise ValueError(err)
# Currently no colorwheel
self._colorwheel = None
# Currently no led
self._led = None
# Currently no light sensor
self._light_sensor = None
# Currently stopped
self._running = False
self._rgb = [0.,0.,0.]
def _update(self):
"""
Update the clock.
"""
# Get the current time.
now = datetime.datetime.now()
# Convert into seconds since midnight
time_in_seconds = (now.hour*60 + now.minute)*60 + now.second
# Update the RGB values with this new time
if self._colorwheel is not None:
self._rgb = self._colorwheel.rgb(time_in_seconds)[:]
# Set the brightness, imposing limit that forces value to be between
# 1 and the minimum brightness.
bright_scalar = self.brightness*self.ambient_brightness
if bright_scalar > 1:
bright_scalar = 1.0
if bright_scalar < self._min_brightness:
bright_scalar = self._min_brightness
# Normalize channels so intensity is always sum(rgb)*bright_scalar.
# This keeps the intensity the same, whether light is coming from
# one, two, or three output channels
total = sum(self.rgb)
values = []
for i in range(3):
values.append(int(round(255*bright_scalar*self.rgb[i]/total,0)))
# Set the LEDs to have desired RGB valuse
values = tuple(values)
if self._led is not None:
self._led.set(values)
def _run(self):
"""
Loop that updates clock every update_interval seconds.
"""
while True:
self._update()
time.sleep(self._update_interval)
def start(self):
"""
Start the clock on its own thread.
"""
# If already running, do not start
if self._running:
return
self._process = multiprocessing.Process(target=self._run)
self._process.start()
self._running = True
def stop(self):
"""
Stop the clock.
"""
# Do not running, do not stop
if not self._running:
return
self._process.terminate()
self._running = False
def add_colorwheel(self,colorwheel):
self._colorwheel = colorwheel
try:
self._colorwheel.rgb
except AttributeError:
err = "colorwheel must have 'rgb' attribute.\n"
raise ValueError(err)
def add_led(self,led):
"""
"""
self._led = led
try:
self._led.set
except AttributeError:
err = "LEDs not available. Must have 'set' attribute.\n"
raise ValueError(err)
def add_ambient_light_sensor(self,light_sensor):
"""
Add an ambient light sensor.
"""
self._light_sensor = light_sensor
try:
self._light_sensor.brightness
except AttributeError:
err = "Light sensor not readable. Must have 'brightness' attribute.\n"
raise ValueError(err)
@property
def brightness(self):
"""
Brightness (controlled by user). Read, but NOT set by thread. This
means the brightness can be adjusted while the clock is running.
"""
return self._brightness
@brightness.setter
def brightness(self,brightness):
"""
Set the brightness.
"""
if brightness < 0 or brightness > 1:
err = "Brightness must be between zero and 1.\n"
raise ValueError(err)
self._brightness = float(brightness)
# Make the thread come up for air and grab the new brightness value
if self._running:
self.stop()
self.start()
@property
def rgb(self):
return self._rgb
@property
def ambient_brightness(self):
"""
Ambient brightness. If no sensor has been added, return 1.0.
"""
if self._light_sensor is None:
return 1.0
else:
return self._light_sensor.brightness
|
#%%
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from scipy.misc import derivative
from scipy.integrate import solve_ivp
from scipy.interpolate import InterpolatedUnivariateSpline as IUS, interp1d
from scipy.optimize import fsolve
rc('text', usetex = True)
#%%
#Evolution of the scalar field
kp = 0.05
def V(phi):
a = 1
b = 1.4349
V0 = 4*10**-10
v = np.sqrt(0.108)
x = phi/v
return V0*(6*x**2 - 4*a*x**3 + 3*x**4)/(1 + b*x**2)**2
def V_phi(phi):
return derivative(V, phi, dx = 10**-6)
N_eval = np.linspace(0, 63.2, 10**6)
phi_i = 3.614
ei = 10**-4
phi_Ni = -np.sqrt(2*ei)
def solver(N, X):
phi, g = X
return [g, (g**2/2 - 3)*(V_phi(phi)/V(phi) + g)]
def HSR_1_check(N, X):
phi, g = X
return g**2/2 - 1
HSR_1_check.terminal = False
X0 = [phi_i, phi_Ni]
sol = solve_ivp(solver, (0,66), X0, method = 'BDF', t_eval = np.linspace(0, 62.8, 10**6))
phi = sol.y[0]
phi_N = sol.y[1]
N = sol.t
plt.plot(phi, phi_N)
plt.xlabel("$\phi$")
plt.ylabel("$\phi'$")
plt.title("Phase plot")
plt.show()
# %%
#Evolution of Hubble scale
H = (2*V(phi)/(6 - phi_N**2))**0.5
plt.plot(N, H, label = "$H(N)$")
plt.legend()
plt.show()
phi_N_2_check = interp1d(phi_N**2, N)
phi_N = IUS(N, phi_N)
N_end = phi_N_2_check(1)
print(N_end)
H = IUS(N, H)
H_N = H.derivative()
ai = kp/np.exp(N_end - 50)*H(N_end - 50)
a = IUS(N, ai*np.exp(N))
phi_NN = phi_N.derivative()
z = IUS(N, ai*np.exp(N)*(phi_NN(N)))
z_N = z.derivative()
z_NN = z.derivative(2)
mus2 = IUS(N, (a(N)*H(N))**2*(z_NN(N)/z(N) + z_N(N)/z(N) + z_N(N)*H_N(N)/(z(N)*H(N))))
mut2 = IUS(N, (2 + H_N(N)/H(N))*(a(N)*H(N))**2)
# %%
#Evaluating the scalar power spectrum
plt.plot(N, np.sqrt(np.abs(mus2(N))))
plt.yscale('log')
plt.show()
Ni_check = IUS(10**2*np.sqrt(np.abs(mut2(N))) - 10**-3, N)
print(Ni_check(0))
# N_sol = fsolve(lambda N: 10**2*np.sqrt(np.abs(mut2(N))) - 10**-3, 1)
# plt.plot(N, 10**2*np.sqrt(np.abs(mus2(N))) - 10**-3)
# plt.yscale('log')
# plt.show()
# print(N_sol)
# %%
|
import random
import math
iter = 100
avg_result = 0.0
for i in range(iter):
limit = 100
first_octant = 0
for i in range(limit):
x = random.uniform(-1, 1)
y = random.uniform(-1 * math.sqrt(1 - pow(x, 2)), math.sqrt(1 - pow(x, 2)))
z = random.uniform(-1 * math.sqrt(1 - pow(x, 2) - pow(y, 2)), math.sqrt(1 - pow(x, 2) - pow(y,2)))
if x > 0 and y > 0 and z > 0:
first_octant += 1
avg_result += (first_octant / limit)
print(avg_result / iter)
|
import time
import pygame
class PetImage:
initial = time.time()
def __init__(self, screen, file, number):
"""初始化宠物图像并设置其初始位置"""
self.screen = screen
self.delay = 0
# 加载宠物图像并获取其外接矩形
self.number = number
self.index = 0
self.images = pygame.image.load(file).convert_alpha()
self.images = [self.images.subsurface(pygame.Rect(i * self.images.get_width() // self.number, 0,
self.images.get_width() // self.number,
self.images.get_height())) for i in range(number)]
self.rect = self.images[0].get_rect()
self.screen_rect = self.screen.get_rect()
# 将每个新宠物图像放在屏幕底部以下(隐藏)
self.rect.centerx = self.screen_rect.centerx
self.rect.top = self.screen_rect.bottom
def update(self, pos):
# 更新宠物图像位置
self.delay = time.time() - self.initial
self.index = int(self.delay * 8) % self.number
self.rect.left = pos[0]
self.rect.top = pos[1]
def draw(self):
# 绘制宠物图像到屏幕指定位置
self.screen.blit(self.images[self.index], self.rect)
class ButtonImage:
def __init__(self, screen, width, height, button_file, text, font_name, font_size):
"""初始化按钮的属性"""
self.screen = screen
self.screen_rect = self.screen.get_rect()
# 设置按钮图像的尺寸和其他属性并获取其外接矩形
self.width = width
self.height = height
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.button_file = button_file
self.button_image = pygame.image.load(self.button_file).convert()
self.button_image.set_colorkey((255, 255, 255))
self.button_rect = self.button_image.get_rect()
self.button_rect.center = self.rect.center
self.text = text
self.font = pygame.font.Font(font_name, font_size)
self.text_image = self.font.render(self.text, True, (255, 255, 255))
self.text_rect = self.text_image.get_rect()
self.text_rect.center = self.rect.center
# 将每个新按钮图像放在屏幕底部以下(隐藏)
self.rect.centerx = self.screen_rect.centerx
self.rect.top = self.screen_rect.bottom
def click(self):
self.button_image.set_alpha(200)
def release(self):
self.button_image.set_alpha(255)
def update(self, pos):
# 更新按钮图像位置
self.rect.left = pos[0]
self.rect.top = pos[1]
self.button_rect.center = self.rect.center
self.text_rect.center = self.rect.center
def draw(self):
# 在按钮图像上绘制文字
self.button_rect.center = self.rect.center
self.screen.blit(self.button_image, self.button_rect)
self.text_rect.center = self.rect.center
self.screen.blit(self.text_image, self.text_rect)
class BarImage:
def __init__(self, screen, width, height, bar_color, text_color, text, font_size, total, left):
self.screen = screen
self.width = width
self.height = height
self.screen_rect = self.screen.get_rect()
self.total = total
self.left = left
self.bar_color = bar_color
self.text_color = text_color
self.text = text
self.font = pygame.font.Font("resources\\fonts\\title.otf", font_size)
self.rect = pygame.Rect((self.screen_rect.left, self.screen_rect.bottom), (self.width, self.height))
self.text_image = self.font.render(self.text + " " + str(self.left) + "/" + str(self.total),
True, self.text_color)
self.text_image_rect = self.text_image.get_rect()
self.text_image_rect.left = self.rect.left
self.text_image_rect.centery = self.rect.centery
self.bar_width = self.width - self.text_image_rect.width - 15
self.bar_height = self.height / 2
def update(self, left, pos):
self.left = left if left < self.total else self.total
self.rect.left = pos[0]
self.rect.top = pos[1]
self.text_image = self.font.render(self.text + " " + str(self.left) + "/" + str(self.total),
True, self.text_color)
self.text_image_rect = self.text_image.get_rect()
self.text_image_rect.left = self.rect.left
self.text_image_rect.centery = self.rect.centery
self.bar_width = self.width - self.text_image_rect.width - 15
self.text_image_rect.left = self.rect.left
self.text_image_rect.centery = self.rect.centery
def draw(self):
self.screen.blit(self.text_image, self.text_image_rect)
pygame.draw.rect(self.screen, (255, 255, 255), (self.text_image_rect.right + 5,
self.rect.centery - self.bar_height / 2, self.bar_width,
self.bar_height))
pygame.draw.rect(self.screen, self.bar_color, (self.text_image_rect.right + 5,
self.rect.centery - self.bar_height / 2,
self.bar_width * self.left / self.total, self.bar_height))
|
import gdal
import subprocess
import CAMS_utils
gdal.UseExceptions()
def reproject(var, infname, outfname, xmin, xmax, ymin, ymax):
args = ['./reprojectCAMS.sh', '-i', infname,
'-o', outfname,
'-p', var,
'--xmin', str(xmin),
'--ymin', str(ymin),
'--xmax', str(xmax),
'--ymax', str(ymax)]
print args
subprocess.call(args)
def reproject_cams(MOD09band, year, month, tile, directory):
# Get extent and resolution of modis file
xmin, xmax, xres, ymin, ymax, yres = CAMS_utils.get_tile_extent(MOD09band)
# Loop through variables
variables = CAMS_utils.parameters()
for var in variables:
# Get input file
infname = CAMS_utils.nc_filename(tile, year, month,
directory=directory, checkpath=False)
# Create output filename
print directory
outfname = CAMS_utils.vrt_filename(tile, year, month, var,
directory=directory)
# Reproject image
reproject(var, infname, outfname, xmin, xmax, ymin, ymax)
def main():
modisband = 'HDF4_EOS:EOS_GRID:"/media/Data/modis/h17v05/MOD09GA.A2016009.h17v05.006.2016012053256.hdf":MODIS_Grid_500m_2D:sur_refl_b02_1'
year = 2016
month = 1
tile = '/home/nicola/python/eoldas/cams_handler/data/h17v05'
directory = "data"
reproject_cams(modisband, year, month, tile, directory)
if __name__ == "__main__":
main()
|
"""create app_users table
Revision ID: 363dec53760
Revises: 2634028c6b8
Create Date: 2015-10-25 14:22:41.435025
"""
# revision identifiers, used by Alembic.
revision = '363dec53760'
down_revision = '2634028c6b8'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
import datetime
def _get_date():
return datetime.datetime.now()
def upgrade():
op.create_table('app_users',
sa.Column('id', sa.Integer, primary_key=True, nullable=False),
sa.Column('username', sa.String(128), nullable=False, unique=True),
sa.Column('firstname', sa.String(128)),
sa.Column('lastname', sa.String(128)),
sa.Column('email', sa.String(128), nullable=False),
sa.Column('phone', sa.VARCHAR(12)),
sa.Column('company', sa.String(32)),
sa.Column('password_hash', sa.String(128), nullable=False),
sa.Column('time_zone_id', sa.Integer, sa.ForeignKey('time_zones.id')),
sa.Column('created_at', sa.TIMESTAMP(timezone=False), default=_get_date),
sa.Column('updated_at', sa.TIMESTAMP(timezone=False), onupdate=_get_date))
def downgrade():
op.drop_table('app_users')
|
import threading
import socket
import sys
import _thread
import RPi.GPIO as GPIO
import time
import os
import sqlite3
import grovepi
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(10, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
c = GPIO.PWM(10, 50)
l = GPIO.PWM(16, 50)
r = GPIO.PWM(18, 50)
ultrasonic_ranger = 4
ultrasonic_rangers = 3
target_host = '192.168.0.109'
target_port = 8888
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))
def setio(p7, p11, p13, p15):
GPIO.output(7, p7)
GPIO.output(11, p11)
GPIO.output(13, p13)
GPIO.output(15, p15)
def ultrasonic():
while True:
try:
a=str(grovepi.ultrasonicRead(ultrasonic_ranger))
a2 = str(grovepi.ultrasonicRead(ultrasonic_rangers))
if a2 > a :
bytes(a, encoding = "utf8")
client.sendall(str.encode(a))
elif a > a2 :
bytes(a2, encoding = "utf8")
client.sendall(str.encode(a))
except TypeError:
print ("tError")
except IOError:
print ("ioError")
def socket_reader():
var = 1
while var == 1:
response = client.recv(4096)
a = str(response)
if a.find('go') != -1 :
print("go")
setio(False, True, False, True)
elif a.find('stop') != -1 :
print("stop")
setio(False, False, False, False)
time.sleep(1)
print("open")
c.start(8.5)
time.sleep(1)
print("down")
l.start(7.5)
r.start(6.5)
time.sleep(1)
print("close")
c.start(5.0)
time.sleep(1)
print("up")
l.start(12.5)
r.start(2.0)
time.sleep(1)
elif a.find('doput') != -1:
print("stop")
setio(True, False, True, False)
print("down")
l.start(7.5)
r.start(6.5)
time.sleep(1)
print("open")
c.start(8.5)
time.sleep(1)
print("up")
l.start(12.5)
r.start(2.0)
time.sleep(1)
print("close")
c.start(5.0)
time.sleep(1)
elif a.find('right') != -1:
print("r")
setio(False, True, False, False)
elif a.find('left') != -1:
print("l")
setio(False, False, False, True)
elif a.find('end') != -1:
print("e")
setio(True, False, True, False)
def main():
tha = threading.Thread(target=ultrasonic)
tha.start()
thb = threading.Thread(target=socket_reader)
thb.start()
if __name__ == '__main__':
main()
|
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = Node()
def insert(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
return data
def includes(self, data):
if not self.head:
return False
cur = self.head
while cur:
if cur.data == data:
return True
cur = cur.next
return False
def to_string(self):
value = " "
cur = self.head
while cur.next != None:
value += " " + str(cur.data)
cur = cur.next
print(value)
return value |
def DistinctList(arr):
total = 0
numDict = {}
for x in arr:
if x not in numDict:
numDict[x] = 1
else:
numDict[x] +=1
#print(numDict)
for val in numDict.values():
if val > 1:
total += val -1
#print(total)
return total
print(DistinctList([100,2,101,4])) |
from unittest import TestCase
class TestLineItem(TestCase):
def test_variant_id(self):
self.fail()
def test_title(self):
self.fail()
def test_quantity(self):
self.fail()
def test_price(self):
self.fail()
def test_grams(self):
self.fail()
def test_sku(self):
self.fail()
def test_variant_title(self):
self.fail()
def test_vendor(self):
self.fail()
def test_fulfillment_service(self):
self.fail()
def test_product_id(self):
self.fail()
def test_requires_shipping(self):
self.fail()
def test_taxable(self):
self.fail()
def test_gift_card(self):
self.fail()
def test_name(self):
self.fail()
def test_variant_inventory_management(self):
self.fail()
def test_properties(self):
self.fail()
def test_product_exists(self):
self.fail()
def test_fulfillable_quantity(self):
self.fail()
def test_total_discount(self):
self.fail()
def test_fulfillment_status(self):
self.fail()
def test_tax_lines(self):
self.fail()
def test_origin_location(self):
self.fail()
def test_destination_location(self):
self.fail()
|
dict = {'test1': 93, 'test2': 95}
dict['test3'] = 99
print( dict.get('test4', 100) )
print( dict.pop('test1') )
print( dict ) |
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.core import serializers
from django.contrib.auth.decorators import login_required
from .models import Post, Comment
from .forms import PostForm, CommentForm
# Create your views here.
def home(request):
return HttpResponse("Good Bye Rocket Ship! Hello new Home PandaQQ TWPRIDE <body><h1>Ni de Ming Zi</h1><div><strong>Hello</strong></div></body>")
################################# Posts ##############################################
def api_posts(request):
all_posts = Post.objects.all()
data = []
for post in all_posts:
data.append({"Author": post.author, "Title": post.title})
return JsonResponse({"data": data, "status": 200})
def post_list(request):
posts = Post.objects.all()
context = {"posts": posts}
return render(request, 'post_list.html', context)
def post_detail(request,pk):
post = Post.objects.get(id=pk)
context = {"post": post}
return render(request, 'post_detail.html', context)
@login_required
def post_create(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = post.user
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
context = {'form': form, 'header': "Add New Post"}
return render(request, 'post_form.html', context)
@login_required
def post_edit(request, pk):
post = Post.objects.get(id=pk)
if request.method == 'POST':
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
context = {'form': form, 'header': f"Edit {post.author}"}
return render(request, 'post_form.html', context)
@login_required
def post_delete(request, pk):
Post.objects.get(id=pk).delete()
return redirect('post_list')
################################# Comments ##############################################
def comment_list(request):
comments = Comment.objects.all()
context = {"comments": comments}
return render(request, 'comment_list.html', context)
@login_required
def comment_create(request, pk):
post = Post.objects.get(id=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('post_detail', pk=comment.post.pk)
else:
form = CommentForm()
context = {'form': form, 'header': f"Add Comment for {post.author}"}
return render(request, 'comment_form.html', context)
@login_required
def comment_edit(request, pk, comment_pk):
comment = Comment.objects.get(id=comment_pk)
if request.method == 'POST':
form = CommentForm(request.POST, instance=comment)
if form.is_valid():
comment = form.save()
return redirect('post_detail', pk=comment.post.pk)
else:
form = CommentForm(instance=comment)
context = {'form': form, 'header': f"Edit {comment.author}"}
return render(request, 'comment_form.html', context)
@login_required
def comment_delete(request, pk, comment_pk):
Comment.objects.get(id=comment_pk).delete()
return redirect('post_detail', pk=pk)
|
# -*- coding=utf-8 -*-
import os
from django.db.models import FileField
from django.forms import forms, MultiValueField, CharField, MultipleChoiceField, SelectMultiple
from django.template.defaultfilters import filesizeformat
from famille.utils.python import generate_timestamp
from famille.utils.widgets import RangeWidget, CommaSeparatedMultipleChoiceWidget
class ContentTypeRestrictedFileField(FileField):
"""
Same as FileField, but you can specify:
- content_types - list containing allowed content_types. Example: ['application/pdf', 'image/jpeg']
- max_upload_size - a number indicating the maximum file size allowed for upload.
2.5MB - 2621440
5MB - 5242880
10MB - 10485760
20MB - 20971520
50MB - 5242880
100MB - 104857600
250MB - 214958080
500MB - 429916160
"""
def __init__(self, *args, **kwargs):
self.content_types = kwargs.pop("content_types", None)
self.max_upload_size = kwargs.pop("max_upload_size", None)
self.extensions = kwargs.pop("extensions", None)
super(ContentTypeRestrictedFileField, self).__init__(*args, **kwargs)
# FIXME: use validators instead !!!!!!!
def clean(self, *args, **kwargs):
data = super(ContentTypeRestrictedFileField, self).clean(*args, **kwargs)
if not hasattr(data.file, "content_type"):
return data
file = data.file
content_type = file.content_type
_, ext = os.path.splitext(file.name)
if self.content_types and content_type.lower() not in self.content_types:
raise forms.ValidationError(u'Format non supporté. Les formats valides sont: %s' % ", ".join(self.extensions))
if self.extensions and ext.lower() not in self.extensions:
raise forms.ValidationError(u'Format non supporté. Les formats valides sont: %s' % ", ".join(self.extensions))
if self.max_upload_size and file._size > self.max_upload_size:
raise forms.ValidationError('Fichier trop volumineux (max %s)' % filesizeformat(self.max_upload_size))
return data
def upload_to_timestamp(basedir):
"""
Generate a filename method. Useful for FileField's upload_to parameter.
:param basedir: the basedir in which to save the file
"""
def wrapped(instance, filename):
_, ext = os.path.splitext(filename)
time_filename = "%s%s" % (generate_timestamp(), ext)
return os.path.join(basedir, time_filename)
return wrapped
content_type_restricted_file_field_rules = [
([ContentTypeRestrictedFileField, ], [],{})
]
class RangeField(MultiValueField):
def __init__(self, field_class=CharField, min_value=None, max_value=None, widget=None, *args, **kwargs):
self.fields = (field_class(), field_class())
if widget:
min_value, max_value = widget.min_value, widget.max_value
if not 'initial' in kwargs:
kwargs['initial'] = [min_value, max_value]
widget = widget or RangeWidget(min_value, max_value)
super(RangeField, self).__init__(
fields=self.fields, widget=widget, *args, **kwargs
)
def compress(self, data_list):
if data_list: # TODO
return [
self.fields[0].clean(data_list[0]),
self.fields[1].clean(data_list[1])
]
return None
def clean(self, value):
value = value or ""
return value[1:-1] if value.startswith("[") else value
class LazyMultipleChoiceField(MultipleChoiceField):
def _get_choices(self):
"""
Override choices getter to cast choices to list.
"""
return list(self._choices)
def _set_choices(self, value):
"""
Override choices setter to not cast directly choices to list.
:param value: the value to set
"""
self._choices = self.widget.choices = value
choices = property(_get_choices, _set_choices)
class CommaSeparatedMultipleChoiceField(MultipleChoiceField):
widget = CommaSeparatedMultipleChoiceWidget
def clean(self, data):
"""
Clean the data taken from the select. Transform
the list of values in a coma separated string.
:param data: the input data
"""
data = super(CommaSeparatedMultipleChoiceField, self).clean(data)
return ",".join(data)
class CommaSeparatedRangeField(RangeField):
def compress(self, data_list):
data = super(CommaSeparatedRangeField, self).compress(data_list)
if data:
return ",".join(data)
return None
|
#-*- coding: utf-8 -*-
"""
Author: guohaozhao116008@sohu-inc.com
Since: 13-6-13 17:45
py 中的locals()函数以及 globals()函数
"""
def test(ars):
x = 1
print locals()
if __name__ == "__main__":
test(5)
test("123")
print globals()
|
from dataclasses import dataclass
@dataclass
class PlayingCard:
rank: str
suit: str
def __str__(self):
return f'{self.suit}{self.rank}'
queen_of_hearts = PlayingCard('Q', '♡')
ace_of_spades = PlayingCard('A', '♠')
ace_of_spades > queen_of_hearts
# TypeError: '>' not supported between instances of 'PlayingCard' and 'PlayingCard' |
import sys
sys.path.append("F:\Algorithmica\MyCodes")
import spacy
#F:\Algorithmica\MyCodes\NLPCodes
with open('F:\Algorithmica\MyCodes\Tripadvisor_hotelreviews.txt','r',encoding='utf-8') as d:
reviews = d.read()
#encoding - it is nothing but ASCII version where different computer can be used to get on same page
#load langauge library
nlp = spacy.load('en_core_web_sm') #This language model,en_core_web_md(medium),en_core_web_lg(large)
#Creating a doc object
doc = nlp(reviews)
nlp.pipeline
# The named entities in the document. Returns a tuple of named entity Span objects
for ent in doc.ents[:50] :
print(ent.text+' - '+ent.label_+' - '+str(spacy.explain(ent.label_)))
'''
Doc.ents are token spans with their own set of annotations.
ent.text The original entity text
ent.label The entity type's hash value
ent.label_ The entity type's string description
ent.start The token span's *start* index position in the Doc
ent.end The token span's *stop* index position in the Doc
ent.start_char The entity text's *start* index position in the Doc
ent.end_char The entity text's *stop* index position in the Doc
'''
#Noun Chunks
#.text The original noun chunk text.
#Doc.noun_chunks are base noun phrases
#Doc.root.text The original text of the word connecting the noun chunk to the rest of the parse.
#.root.dep_ Dependency relation connecting the root to its head.
for chunk in doc[:50].noun_chunks:
print(chunk.text+' - '+chunk.root.text+' - '+chunk.root.dep_+' - '+chunk.root.head.text)
#Visualising NERs
import warnings
warnings.filterwarnings('ignore')
for sent in list(doc.sents)[:50]:
displacy.render(nlp(sent.text), style='ent', jupyter=True) |
import numpy as np
'''
T
O
D
O
THIS IS CURRENTLY A COPY OF THE NEURAL_NETWORK CLASS.. NEEDS WORK TO CONVERT TO CNN
'''
# Neural Network Class for Feature Approximation in Reinforcement Learning
class convolutional_neural_network():
def __init__(self, layer_sizes):
# Track layersizes as a numpy array
self.layersizes = np.array([int(i) for i in layer_sizes])
# Initialize Node Arrays
self.a = []
self.z = []
self.y_hat = None
self.y_prob = None
# Initialize Weight Arrays
self.w = []
self.b = []
for i in np.arange(1, len(self.layersizes)):
self.w.append(0.01 * np.random.randn(self.layersizes[i], self.layersizes[i-1]))
self.b.append(np.zeros(self.layersizes[i]))
# Misc. Network Settings
self.training_batch_size = 1
self.learning_rates = 0.01 * np.ones(len(self.w))
self.leaky_relu_rates = 0.01 * np.ones(len(self.w))
self.huber_cost_delta = 5
# Initialize Cost Function Settings
# DEFAULT: Huber Cost Function
self.use_huber_cost = True
self.use_hellinger_cost = False
self.use_quadratic_cost = False
# Initialize Activation Function Settings
# DEFAULT: ReLU for hidden layers and Sigmoid output layer
self.use_leaky_relu = [True] * (len(self.w) - 1) + [False]
self.use_sigmoid = [False] * (len(self.w) - 1) + [True]
self.use_relu = [False] * len(self.w)
self.use_linear = [False] * len(self.w)
self.use_tanh = [False] * len(self.w)
# Error Tracking - Diagnostics
self.mean_squared_errors = []
self.relative_squared_errors = []
self.number_of_stored_errors = 50000
# Function to perform NN training steps (iterative prediction / backpropagation)
def train_network(self, data, labels, iter):
# Reshape vector into 2D array if necessary
if labels.ndim == 1:
labels.shape = (1, -1)
# Loop over random batches of data for "iter" training iterations
for ation in np.arange(iter):
if ation%1000 == 0: print("Current Training Step: " + str(ation))
batch_idx = np.random.choice(data.shape[1], size=self.training_batch_size, replace=False)
X = data[:,batch_idx]
Y = labels[:,batch_idx]
self.predict(X)
self.learn(Y)
# Perform a single prediction-only step over a given dataset
def classify_data(self, data):
self.predict(data)
return self.y_hat
# Function to perform NN prediction on a matrix of data columns
def predict(self, X):
# Empty stored training values
self.a = [X]
self.z = []
# Loop over all layers
for i in np.arange(len(self.layersizes) - 1):
# Calculate Z (pre-activated node values for layer)
z = np.matmul(self.w[i], self.a[i])
self.z.append(z)
# Calculate A (activated node values for layer)
if self.use_leaky_relu[i]: a = leaky_ReLU(z, self.leaky_relu_rates[i])
elif self.use_relu[i]: a = ReLU(z)
elif self.use_linear[i]: a = linear(z)
elif self.use_tanh[i]: a = tanh(z)
elif self.use_sigmoid[i]: a = sigmoid(z)
else: a = ReLU(z)
self.a.append(a)
# Store prediction
self.y_hat = self.a[len(self.a) - 1]
self.y_prob = self.y_hat / np.sum(self.y_hat, axis=0)
# Function to perform backpropagation on network weights after a prediction has been stored in self.y_hat
def learn(self, Y):
# Reshape vector into 2D array if necessary
if Y.ndim == 1:
Y.shape = (1, -1)
# Store number of datapoints
m = Y.shape[1]
# Calculate and Store Error - Diagnostics
self.error_calc(Y)
# Loop over layers backwards
for i in np.flip(np.arange(len(self.w))):
# Calculate Loss Function Derivatiove dL/dA
if self.use_huber_cost: dL = d_huber(Y, self.y_hat, self.huber_cost_delta)
elif self.use_hellinger_cost: dL = d_hellinger(Y, self.y_hat)
elif self.use_quadratic_cost: dL = d_quadratic(Y, self.y_hat)
else: dL = d_hellinger(Y, self.y_hat)
# Calculate Activation Function Derivative dA/dZ
if self.use_leaky_relu[i]: dA = d_leaky_ReLU(self.z[i], self.leaky_relu_rates[i])
elif self.use_relu[i]: dA = d_ReLU(self.z[i])
elif self.use_relu[i]: dA = d_linear(self.z[i])
elif self.use_tanh[i]: dA = d_tanh(self.z[i])
elif self.use_sigmoid[i]: dA = d_sigmoid(self.z[i])
else: dA = d_sigmoid(self.z[i])
# Calculated pre-activated node derivative
if i == (len(self.w) - 1):
dz = dL * dA
prev_dz = dz
else:
dz = np.matmul(self.w[i + 1].T, prev_dz) * dA
prev_dz = dz
# Calculate Weight Derivatives
dw = (1/m) * np.matmul(dz, self.a[i].T)
db = (1/m) * np.sum(dz, axis=1, keepdims=True)
# Apply Learning Functions
self.w[i] = self.w[i] - self.learning_rates[i] * dw
self.b[i] = self.b[i] - self.learning_rates[i] * db
# Function to calculate error and append to error storage
def error_calc(self, Y):
# Calculate Mean Squared Error
sqr_err = (self.y_hat - Y)**2
sum_sqr_err = np.sum(sqr_err)
self.mean_squared_errors.append(sum_sqr_err/len(Y))
while len(self.mean_squared_errors) > self.number_of_stored_errors:
self.mean_squared_errors.pop(0)
'''
COST FUNCTION DERIVATIVES
'''
def d_huber(Y, Y_hat, delta):
if np.linalg.norm(Y_hat - Y) < delta: return Y_hat - Y
else: return delta * np.sign(Y_hat - Y)
def d_hellinger(Y, Y_hat):
return (1/np.sqrt(2))*(np.ones(Y.shape) - np.divide(np.sqrt(Y), np.sqrt(Y_hat)))
def d_quadratic(Y, Y_hat):
return Y_hat - Y
'''
ACTIVATION FUCNTIONS
'''
def leaky_ReLU(x, e):
return np.maximum(e*x, x)
def ReLU(x):
return np.maximum(0, x)
def linear(x):
return x
def tanh(x):
return (np.exp(x) - np.exp(-1*x))/(np.exp(x) + np.exp(-1*x))
def sigmoid(x):
return 1/(1+np.exp(-1*x))
'''
ACTIVATION FUCNTION DERIVATIVES
'''
def d_leaky_ReLU(x, e):
return np.where(x > 0, 1.0, e)
def d_ReLU(x):
return np.where(x > 0, 1.0, 0)
def d_linear(x):
return 1
def d_tanh(x):
return 1 - (tanh(x))**2
def d_sigmoid(x):
return sigmoid(x)*(1 - sigmoid(x)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask_script import Manager, Shell
from app import create_app, db
# 读取配置(此配置再数据迁移中被引入)
config_name = (os.getenv('FLASK_CONFIG') or 'default')
app = create_app(config_name)
manager = Manager(app)
def make_shell_context():
return dict(app=app, db=db)
manager.add_command('shell', Shell(make_context=make_shell_context))
if __name__ == '__main__':
manager.run() |
fname = input('Enter file name: ')
if len(fname) < 1 : fname = 'clown.txt'
fhand = open(fname)
counts = dict()
for line in fhand:
line = line.rstrip()
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
temp = list()
for k, v in counts.items() :
newTup = (v , k)
temp.append(newTup)
temp = sorted(temp, reverse=True)
#print('Sorted', temp[:5])
for v, k in temp[:5] :
print(k, v)
|
def InitializeRow(entity, row):
row.GetCellByName("STATUS").Tooltip = row.GetCellByName("STATUS").Text
row.GetCellByName("STATUS").Text = ""
if (entity["STATUS"].GetInt32() == 1):
row.GetCellByName("STATUS").FontIcon = "fa fa-clock-o"
row.GetCellByName("STATUS").TextColor = "#c49f47"
if (entity["STATUS"].GetInt32() == 2):
row.GetCellByName("STATUS").FontIcon = "fa fa-thumbs-up"
row.GetCellByName("STATUS").TextColor = "#3598dc"
if (entity["STATUS"].GetInt32() == 3):
row.GetCellByName("STATUS").FontIcon = "fa fa-thumbs-down"
row.GetCellByName("STATUS").TextColor = "#cb5a5e"
if (entity["STATUS"].GetInt32() == 4):
row.GetCellByName("STATUS").FontIcon = "fa fa-mail-reply-all"
row.GetCellByName("STATUS").TextColor = "#95a5a6"
if (entity["STATUS"].GetInt32() == 5):
row.GetCellByName("STATUS").FontIcon = "fa fa-dollar"
row.GetCellByName("STATUS").TextColor = "#1ba39c"
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 08:07:01 2020
@author: shino
"""
import numpy as np
import glob
import scipy
from dataset import Dataset
from scipy.spatial import ckdtree
path = "/Volumes/ssd/nyu_2451_38586_las/T_315500_234500/*.txt"
files = []
files = glob.glob(path)
print(files)
maxleng=[]
laspath = "/Volumes/ssd/Dublin/*.las"
lasfiles = []
lasfiles = glob.glob(laspath)
#for file in files:
# with open(file) as f:
# l_strip = [s.strip() for s in f.readlines()]
# print(l_strip[0].split())
## print(type(l_strip[0].split()))
# # l = f.readlines()
# # print(type(l))
# # print(l[0])
# length = []
# waves = []
# for lasfile in lasfiles:
# ref_ds = Dataset(lasfile)
# ref_points = ref_ds._xyz
# out_labels = ref_ds.labels
# tree = ckdtree.cKDTree(ref_points[:, 0:2]) # only on 2D
# xyzc_arr = []
# wave_arr = []
# for line in l_strip:
# line = line.split()
## print((line[8]))
# # print(len(line[9:]))
# if(line[4] != "no_waveform"):
# xyz = (line[:3])
# print(xyz)
for lasfile in lasfiles:
ref_ds = Dataset(lasfile)
ref_points = ref_ds._xyz
out_labels = ref_ds.labels
tree = ckdtree.cKDTree(ref_points[:, 0:2]) # only on 2D
xyzc_arr = []
wave_arr = []
for file in files:
with open(file) as f:
l_strip = [s.strip() for s in f.readlines()]
print(l_strip[0].split())
print(type(l_strip[0].split()))
# l = f.readlines()
# print(type(l))
# print(l[0])
length = []
waves = []
for line in l_strip:
line = line.split()
# print((line[8]))
# print(len(line[9:]))
if(line[4] != "no_waveform"):
xyz = (line[:3])
print(line[:3])
#lasとマッチング
multiples = tree.query_ball_point([xyz[0], xyz[1]], r=0.001, eps=0.0001) ## xy
if(len(multiples)>0):
print(multiples)
# xyzc_arr.append()
length.append(int(line[2]))
waves.append(line[3:])
# length = np.array(length)
# waves = np.array(waves)
# maxleng.append(np.amax(length))
# print(np.amax(length))
# print(np.amax(waves))
#print("max is :")
#print(np.amax(maxleng)) |
""" Modules for performing conversions between file types, or for
resampling a given file.
In general, the naming convention follows this rule:
<file_ext_in>2<file_ext_out>('filename_in', 'filename_out')
for example:
sww2dem('northbeach.sww', 'outfile.dem')
Some formats input and output across multiple files. In that case the
convention is so:
urs2nc('northbeach', 'outfile')
Where an array of 3 input files produce 4 output files.
"""
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
|
# Open the data and make list
advent_input = open('advent_day_1/input.txt', 'r')
a_list = list(advent_input)
advent_input.close()
# Make the list proper
advent_list = [x[:-1] for x in a_list]
advent_list = [int(i) for i in advent_list]
# Look for the 2020 ~ part 1
for i in advent_list:
for x in advent_list:
if i + x == 2020:
print(f'{i} and {x}')
print(i*x)
# Look for the 2020 ~ part 2
for i in advent_list:
for x in advent_list:
for y in advent_list:
if i + x + y == 2020:
print(f'{i}, {x}, {y}')
print(i*x*y)
|
#!/usr/bin/env python
# /****************************************************************************
# * Copyright (c) 2018 John A. Dougherty. All rights reserved.
# *
# * Redistribution and use in source and binary forms, with or without
# * modification, are permitted provided that the following conditions
# * are met:
# *
# * 1. Redistributions of source code must retain the above copyright
# * notice, this list of conditions and the following disclaimer.
# * 2. Redistributions in binary form must reproduce the above copyright
# * notice, this list of conditions and the following disclaimer in
# * the documentation and/or other materials provided with the
# * distribution.
# * 3. Neither the name ATLFlight nor the names of its contributors may be
# * used to endorse or promote products derived from this software
# * without specific prior written permission.
# *
# * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE.
# * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# * POSSIBILITY OF SUCH DAMAGE.
# *
# * In addition Supplemental Terms apply. See the SUPPLEMENTAL file.
# ****************************************************************************/
from Tkinter import *
import rospy
import actionlib
import snav_msgs.msg
from std_msgs.msg import String
from snav_msgs.msg import WaypointWithConfigArray
class TopGui:
def __init__(self):
self.props_state = "NOT_SPINNING"
self.master = Tk()
self.debug_window_open = False
self.tk_action_sv = StringVar()
self.action = "NONE"
self.tk_action_sv.set("Current action: {}".format(self.action))
self.tk_status_sv = StringVar()
self.tk_status_sv.set("")
self.takeoff_client = actionlib.SimpleActionClient('takeoff', snav_msgs.msg.TakeoffAction)
self.land_client = actionlib.SimpleActionClient('land', snav_msgs.msg.LandAction)
self.execute_client = actionlib.SimpleActionClient('execute_mission', snav_msgs.msg.ExecuteMissionAction)
self.go_to_client = actionlib.SimpleActionClient('go_to_waypoint', snav_msgs.msg.GoToWaypointAction)
self.compute_traj_client = actionlib.SimpleActionClient('compute_traj', snav_msgs.msg.ComputeTrajAction)
# Buttons
self.b_takeoff_land = Button(self.master, text="Take Off", command=self.__takeoff, width=12)
self.b_takeoff_land.grid(row=0, column=0)
self.b_execute = Button(self.master, text="Execute Mission", command=self.__execute, width=12)
self.b_execute.grid(row=0, column=1)
self.b_recompute = Button(self.master, text="Recompute Traj", command=self.__recompute_traj, width=12)
self.b_recompute.grid(row=0, column=2)
self.b_clear = Button(self.master, text="Clear Waypoints", command=self.__clear, width=12)
self.b_clear.grid(row=0, column=3)
self.b_go_to = Button(self.master, text="Go To", command=self.__go_to, width=12)
self.b_go_to.grid(row=1, column=0)
self.b_abort = Button(self.master, text="Abort", command=self.__abort, width = 36)
self.b_abort.grid(row=2, column=0, columnspan=4)
# Entry
self.waypoint = StringVar()
self.e_wp = Entry(self.master, textvariable=self.waypoint, width=24)
self.e_wp.grid(row=1, column=1, columnspan=2)
self.e_wp.insert(0, "x, y, z, yaw")
# Labels
self.l_current_action = Label(self.master, textvariable=self.tk_action_sv, width=36)
self.l_current_action.grid(row=3, column=0, columnspan=4)
self.l_last_action_status = Label(self.master, textvariable=self.tk_status_sv, width=45)
self.l_last_action_status.grid(row=4, column=0, columnspan=4)
self.b_debug = Button(self.master, text="Debug", command=self.__create_debug_window, width=12)
self.b_debug.grid(row=1, column=3)
rospy.init_node("tk_test")
rospy.Subscriber("props_state", String, self.__props_state_sub_cb)
self.wp_pub = rospy.Publisher("input_waypoints", WaypointWithConfigArray, queue_size=10)
def __props_state_sub_cb(self, data):
self.props_state = data.data
self.__update_takeoff_land_button()
def __update_takeoff_land_button(self):
if self.props_state == "NOT_SPINNING":
self.b_takeoff_land.config(text="Take Off", command=self.__takeoff)
else:
self.b_takeoff_land.config(text="Land", command=self.__land)
def wait_for_server(self):
self.takeoff_client.wait_for_server()
self.land_client.wait_for_server()
self.execute_client.wait_for_server()
self.go_to_client.wait_for_server()
def __takeoff(self):
if self.action == "NONE":
goal = snav_msgs.msg.TakeoffGoal()
self.takeoff_client.send_goal(goal, self.__done_cb, self.__takeoff_active_cb, self.__feedback_cb)
def __takeoff_active_cb(self):
self.__update_action("TAKEOFF")
def __land(self):
if self.action == "NONE":
goal = snav_msgs.msg.LandGoal()
self.land_client.send_goal(goal, self.__done_cb, self.__land_active_cb, self.__feedback_cb)
def __land_active_cb(self):
self.__update_action("LAND")
def __abort(self):
if self.action == "TAKEOFF":
self.takeoff_client.cancel_goal()
elif self.action == "LAND":
self.land_client.cancel_goal()
elif self.action == "EXECUTE":
self.execute_client.cancel_goal()
elif self.action == "GO TO WAYPOINT":
self.go_to_client.cancel_goal()
def __execute(self):
if self.action == "NONE":
goal = snav_msgs.msg.ExecuteMissionGoal()
self.execute_client.send_goal(goal, self.__done_cb, self.__execute_active_cb, self.__feedback_cb)
def __execute_active_cb(self):
self.__update_action("EXECUTE")
def __clear(self):
self.wp_pub.publish(WaypointWithConfigArray())
def __go_to(self):
if self.action == "NONE":
waypoint = self.waypoint.get().split(',')
if len(waypoint) != 4:
print("Waypoint input must be four comma-separated values")
return
goal = snav_msgs.msg.GoToWaypointGoal()
goal.position.x = float(waypoint[0])
goal.position.y = float(waypoint[1])
goal.position.z = float(waypoint[2])
goal.yaw = float(waypoint[3])
self.go_to_client.send_goal(goal, self.__done_cb, self.__go_to_active_cb, self.__feedback_cb)
def __go_to_active_cb(self):
self.__update_action("GO TO WAYPOINT")
def __recompute_traj(self):
if self.action == "NONE":
goal = snav_msgs.msg.ComputeTrajGoal()
self.compute_traj_client.send_goal(goal, self.__done_cb, self.__recompute_traj_active_cb, self.__feedback_cb)
def __recompute_traj_active_cb(self):
self.__update_action("RECOMPUTE TRAJ")
def __update_action(self, action):
self.action = action
self.tk_action_sv.set("Current action: {}".format(action))
def __feedback_cb(self, feedback):
if self.debug_window_open:
self.debug_window_t.config(state=NORMAL)
self.debug_window_t.delete(1.0, END)
self.debug_window_t.insert(1.0, "Feedback of {}:\n{}\n".format(self.action, feedback))
self.debug_window_t.config(state=DISABLED)
def __done_cb(self, goal_status, result):
self.tk_status_sv.set("{} finished with result: {}".format(self.action, self.__actionlib_status_to_string(goal_status)))
if self.debug_window_open:
self.debug_window_t.config(state=NORMAL)
self.debug_window_t.delete(1.0, END)
self.debug_window_t.insert(1.0, "Result of {}:\n{}\n".format(self.action, result))
self.debug_window_t.config(state=DISABLED)
self.__update_action("NONE")
def __actionlib_status_to_string(self, status):
if status == actionlib.GoalStatus.PENDING:
return "PENDING"
elif status == actionlib.GoalStatus.ACTIVE:
return "ACTIVE"
elif status == actionlib.GoalStatus.RECALLED:
return "RECALLED"
elif status == actionlib.GoalStatus.PREEMPTED:
return "PREEMPTED"
elif status == actionlib.GoalStatus.ABORTED:
return "ABORTED"
elif status == actionlib.GoalStatus.SUCCEEDED:
return "SUCCEEDED"
elif status == actionlib.GoalStatus.LOST:
return "LOST"
else:
return "UNDEFINED"
def __create_debug_window(self):
if not self.debug_window_open:
self.debug_window = Toplevel(self.master)
self.debug_window.attributes('-topmost', True)
self.debug_window.update()
self.debug_window.protocol("WM_DELETE_WINDOW", self.__on_closing_debug_window)
self.debug_window.wm_title("Action Debug")
self.debug_window_s = Scrollbar(self.debug_window)
self.debug_window_t = Text(self.debug_window, height=5, width=50)
self.debug_window_s.pack(side=RIGHT, fill=Y)
self.debug_window_t.pack(side=LEFT, fill=Y)
self.debug_window_s.config(command=self.debug_window_t.yview)
self.debug_window_t.config(yscrollcommand=self.debug_window_s.set)
self.debug_window_t.config(state=DISABLED)
self.debug_window_open = True
def __on_closing_debug_window(self):
self.debug_window_open = False
self.debug_window.destroy()
def run(self):
self.master.attributes('-topmost', True)
self.master.update()
mainloop()
if __name__ == '__main__':
gui = TopGui()
gui.run()
|
from impl.labyrinth.Cell import Cell
from impl.labyrinth.CellType import CellType
from services.ICell import ICell
class CellEmpty(Cell, ICell):
"""Empty cell where the player can walk"""
def __init__(self):
super().__init__(CellType.EMPTY)
def __str__(self):
return "*"
def execute_action(self, labyrinth, player): pass
|
import requests
import urllib
url = 'http://api-xl9-ssl.xunlei.com/sl/group_accel/motorcade_mem?'
data = {
'uid':'493627929',
'send_from':'web',
'group_id':'1759602',
'_uid':'493627929',
'_sessid':'6F8D250C527FD37F680F7097C6915B3A',
'_h[]':'Peer-Id:1C1B0D3E68A0QW7Q',
'_dev':'1',
'_callback':'_jsonpf7qd61x6a29gnoajbj9hehfr',
}
headers = {
'Host':'api-xl9-ssl.xunlei.com',
'Connection':'keep-alive',
'User-Agent':'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36 Thunder/9.1.35.816 ThunderComponent/1.0.10.99',
'Referer':'http://pc.xunlei.com/racing',
'Accept-Language':'en-US,en;q=0.8',
}
data = urllib.urlencode(data)
nurl = url+data
gets = requests.get(nurl,headers=headers)
print gets.text |
# Escribir un programa que pregunte al usuario su edad y muestre por pantalla si es mayor de
# edad o no.
edad = int(input("Cuatos años tienes? "))
if edad > 18:
print("Usted es mayor")
else :
print ("Usted es menor")
|
import sys
def solve():
N = int(input())
print(N)
print(*[1]*N, sep='\n')
if __name__ == '__main__':
solve() |
import mido
from mido import MidiFile
import time
print(mido.get_output_names())
port = mido.open_output()
# print(port)
msg = mido.Message('note_on', note=60, time=5)
port.send(msg)
time.sleep(msg.time)
port.send(mido.Message('note_off', note=60))
|
print("Hello! I am going to ask you questions about your device to create a commercial.")
yourObject = input("What is your object? ")
yourData = input("What data does it take? ")
how = input("How will you record the "+yourData+" from your "+yourObject+"?")
where = input("Where will the "+how+" be located? ")
cost = input("How expensive will your "+yourObject+" be in dollars? ")
print("Coming soon! For the low price of "+cost+" dollars, ",end="")
print("this new "+yourObject+" will easily record "+yourData+". It is easy to control from "+how+" located ",end="")
print("on "+where+".")
|
import re
import timeit
from datetime import date
import requests
from bs4 import BeautifulSoup
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
# Wraper function to calculate runtime of a function (function is able to
# return value if needed)
def calculate_runtime(func):
def inner_function(*args, **kwargs):
begin = timeit.default_timer()
return_value = func(*args, **kwargs)
end = timeit.default_timer()
print(f"Runtime of '{func.__name__}' function : {str(end - begin)}", "\n")
return return_value
return inner_function
# Scrapes data from 6 MyAnimeList top rankings and stores it in different
# worksheets. Function also adds "Excel functions" that calculate order of
# animanga and stores it in seperate sheet.
@calculate_runtime
def _scrape_worksheet(value_ws, order_ws):
def _request_specific_website(ws):
def _get_specific_url(ws_title):
URL_DICTIONARY = {
'ARV': 'https://myanimelist.net/topanime.php',
'AMV': 'https://myanimelist.net/topanime.php?type=bypopularity',
'AFV': 'https://myanimelist.net/topanime.php?type=favorite',
'MRV': 'https://myanimelist.net/topmanga.php',
'MMV': 'https://myanimelist.net/topmanga.php?type=bypopularity',
'MFV': 'https://myanimelist.net/topmanga.php?type=favorite'
}
return URL_DICTIONARY.get(ws_title)
return requests.get(_get_specific_url(ws.title)).text
def _find_specific_animanga_data(ws, soup):
if ws.title == 'ARV':
title = soup.find('h3', class_
= 'hoverinfo_trigger fl-l fs14 fw-b anime_ranking_h3').text
core = soup.find('td', class_
= 'score ac fs14').text.replace('\n','').replace(' ','')
if ws.title == 'AMV':
title = soup.find('h3', class_
= 'hoverinfo_trigger fl-l fs14 fw-b anime_ranking_h3').text
temp = soup.find(string = re.compile('members'))
core = temp.replace(' ','').replace(',','')\
.replace('members','').replace('\n','')
if ws.title == 'AFV':
title = soup.find('h3', class_
= 'hoverinfo_trigger fl-l fs14 fw-b anime_ranking_h3').text
temp = soup.find(string = re.compile('favorites'))
core = temp.replace(' ','').replace(',','')\
.replace('favorites','').replace('\n','')
if ws.title == 'MRV':
title = soup.find('h3', class_ = 'manga_h3').text
core = soup.find('td', class_
= 'score ac fs14').text.replace('\n','')
if ws.title == 'MMV':
title = soup.find('h3', class_ = 'manga_h3').text
temp = soup.find(string = re.compile('members'))
core = temp.replace(' ','').replace(',','')\
.replace('members','').replace('\n','')
if ws.title == 'MFV':
title = soup.find('h3', class_ = 'manga_h3').text
temp = soup.find(string = re.compile('favorites'))
core = temp.replace(' ','').replace(',','')\
.replace('favorites','').replace('\n','')
return (title, core)
def _add_data_to_worksheets(v_ws, o_ws, title, info, col_idx):
def _get_worksheet_row_count(ws):
row_count = 1
while ws['A' + str(row_count)].value:
row_count += 1
return row_count
data_has_changed_for_animanga = False
for i in range(2, _get_worksheet_row_count(v_ws)):
if v_ws['B' + str(i)].value == title:
v_ws[col_idx + str(i)] = info
o_ws[col_idx + str(i)] = ('=COUNTIF(' + v_ws.title + '!$'
+ col_idx + '$2:$' + col_idx + '$100,">"&' + v_ws.title
+ '!' + col_idx + str(i) + ')+1')
if v_ws[chr(ord(col_idx) - 2) + str(i)].value:
v_ws[chr(ord(col_idx) - 1) + str(i)].value = (info
- v_ws[chr(ord(col_idx) - 2) + str(i)].value)
if info != v_ws[chr(ord(col_idx) - 2) + str(i)].value\
and (v_ws.title == 'ARV' or v_ws.title == 'MRV'):
print(f"{title} data changed: {str(v_ws[chr(ord(col_idx) - 2) + str(i)].value)} -> {str(info)}")
data_has_changed_for_animanga = True
o_ws[chr(ord(col_idx) - 1) + str(i)].value = ('='
+ (chr(ord(col_idx) - 2) + str(i)) + ' - '
+ (col_idx + str(i)))
else:
print(f"{title} data changed: NULL -> {str(info)}")
data_has_changed_for_animanga = True
break
else:
print(f"+ New animanga added to {v_ws.title}: {title} | {str(info)}")
ws_row_count = _get_worksheet_row_count(v_ws)
v_ws['A' + str(ws_row_count)] = '#' + str(ws_row_count - 1)
v_ws['B' + str(ws_row_count)] = title
v_ws[col_idx + str(ws_row_count)] = info
o_ws['A' + str(ws_row_count)] = '#' + str(ws_row_count - 1)
o_ws['B' + str(ws_row_count)] = title
o_ws[col_idx + str(ws_row_count)]\
= f"=COUNTIF({v_ws.title}!${col_idx}$2:${col_idx}$100,>&{v_ws.title}!{col_idx}{str(ws_row_count)})+1"
data_has_changed_for_animanga = True
return data_has_changed_for_animanga
COLLUM_INDEX = get_column_letter(value_ws.max_column + 2)
HTML_TEXT = _request_specific_website(value_ws)
SOUP = BeautifulSoup(HTML_TEXT, 'lxml')
RANKING_LIST = SOUP.find_all('tr', class_ = 'ranking-list')
data_has_changed_for_ws = False
for animanga_soup_data in RANKING_LIST:
TEMP = _find_specific_animanga_data(value_ws, animanga_soup_data)
if _add_data_to_worksheets(value_ws, order_ws, TEMP[0], float(TEMP[1]),
COLLUM_INDEX) == True:
data_has_changed_for_ws = True
value_ws.auto_filter.ref = "A1:" + COLLUM_INDEX + str(value_ws.max_row)
value_ws[COLLUM_INDEX + '1'] = date.today()
value_ws[chr(ord(COLLUM_INDEX) - 1) + '1'] = 'Change'
order_ws.auto_filter.ref = "A1:" + COLLUM_INDEX + str(value_ws.max_row)
order_ws[COLLUM_INDEX + '1'] = date.today()
order_ws[chr(ord(COLLUM_INDEX) - 1) + '1'] = 'Change'
if not data_has_changed_for_ws:
print("No major changes in worksheet")
# Program adds aditional data to premade data worksheets
def main():
workbook = load_workbook("./input.xlsx")
WORKSHEET_TITLE_DICTIONARY = {
'ARV': 'ARO',
'AMV': 'AMO',
'AFV': 'AFO',
'MRV': 'MRO',
'MMV': 'MMO',
'MFV': 'MFO'
}
TEMP = date.today()
TODAYS_DATE = TEMP.strftime("%Y.%m.%d")
for main_worksheet_title in WORKSHEET_TITLE_DICTIONARY:
_scrape_worksheet(workbook[main_worksheet_title],
workbook[WORKSHEET_TITLE_DICTIONARY[main_worksheet_title]])
START_TIME = timeit.default_timer()
workbook.save(f"./Excel/{TODAYS_DATE}.xlsx")
END_TIME = timeit.default_timer()
print(f"Saved as '{TODAYS_DATE}.xlsx in {str(END_TIME - START_TIME)}")
if __name__ == '__main__':
main() |
PLAYER = 'PL'
OWNER = 'OW'
PROFILE_TYPE_CHOICES = (
(PLAYER, 'Player'),
(OWNER, 'Owner'),
)
PUNE = 'PUN'
MUMBAI = 'BOM'
DELHI = 'DEL'
BANGALORE = 'BAN'
CHENNAI = 'CHE'
PLACE_CHOICES = (
(PUNE,'Pune'),
(MUMBAI,'Mumbai'),
(DELHI,'Delhi'),
(BANGALORE,'Bangalore'),
(CHENNAI,'Chennai'),
)
DOY = ('1970', '1971', '1972', '1973', '1974', '1975', '1976', '1977',
'1978', '1979','1980', '1981', '1982', '1983', '1984', '1985', '1986', '1987',
'1988', '1989', '1990', '1991', '1992', '1993', '1994', '1995',
'1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003',
'2004', '2005', '2006', '2007', '2008', '2009', '2010',)
PLAYER = 'P'
OWNER = 'O'
GROUND = 'G'
SEARCH_CHOICES = (
(PLAYER,'Player'),
(OWNER,'Turf Owners'),
(GROUND,'Ground/Turfs'),
)
AMETUER = 'Ametuer'
SEMI_PRO = 'Semi Pro'
PRO = 'Professional'
WORLD_CLASS = 'World Class'
EXPERTISE_CHOICES = (
(AMETUER,'Ametuer'),
(SEMI_PRO,'Semi Pro'),
(PRO,'Professional'),
(WORLD_CLASS,'World Class'),
) |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Wang Ye (Wayne)
@file: Maximum Profit of Operating a Centennial Wheel.py
@time: 2020/09/27
@contact: wangye@oppo.com
@site:
@software: PyCharm
# code is far away from bugs.
"""
from typing import *
class Solution:
def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:
ret, res = 1, -1
board = 0
wait = 0
for i, cus in enumerate(customers):
prep = cus + wait
if prep > 4:
cur = 4
wait = prep - 4
else:
cur = prep
wait = 0
board += cur
cost = board * boardingCost - (i + 1) * runningCost
if cost > res:
res = cost
ret = i + 1
n = len(customers)
while wait > 0:
n += 1
cur = min(wait, 4)
board += cur
wait -= cur
cost = board * boardingCost - n * runningCost
if cost > res:
res = cost
ret = n
return ret if res > 0 else -1
so = Solution()
# print(so.minOperationsMaxProfit(customers=[8, 3], boardingCost=5, runningCost=6))
print(so.minOperationsMaxProfit(customers=[10, 10, 6, 4, 7], boardingCost=3, runningCost=8))
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
T = np.linspace(0, 1, 81)
u = pd.read_csv("Z.txt", header=None)
df = pd.DataFrame(index=np.arange((u.size)/31), columns=np.arange(1))
n = 0
for i in range(0, 81):
df.iloc[i, 0] = u.iloc[i*31 + n, 0]
df.to_csv("Z_final.txt", header=None, index=False)
fig = plt.gcf()
plt.plot(T, df, label="z")
plt.show()
|
from django.shortcuts import render
from arches.app.models.system_settings import settings
from arches.app.views.base import BaseManagerView
from arches.app.views.plugin import PluginView
class ConsultationView(PluginView):
def get(self, request, pluginid=None, slug='consultation-workflow'):
return super(ConsultationView, self).get(request, pluginid=pluginid, slug=slug)
|
# python3
#credit to: http://personal.denison.edu/~havill/algorithmics/python/knapsack.py
import sys
data = list(map(int, sys.stdin.read().split()))
n, cap = data[0:2]
vals = data[2:(2 * n + 2):2]
whts = data[3:(2 * n + 2):2]
collected_value = 0
def KnapsackFrac(v, w, W):
order = bubblesortByRatio(v, w) # sort by v/w (see bubblesort below)
weight = 0.0 # current weight of the solution
value = 0.0 # current value of the solution
knapsack = [] # items in the knapsack - a list of (item, faction) pairs
n = len(v)
index = 0 # order[index] is the index in v and w of the item we're considering
while (weight < W) and (index < n):
if weight + w[order[index]] <= W: # if we can fit the entire order[index]-th item
knapsack.append((order[index], 1.0)) # add it and update weight and value
weight = weight + w[order[index]]
value = value + v[order[index]]
else:
fraction = (W - weight) / w[order[index]] # otherwise, calculate the fraction we can fit
knapsack.append((order[index], fraction)) # and add this fraction
weight = W
value = value + v[order[index]] * fraction
index = index + 1
return (knapsack, value) # return the items in the knapsack and their value
# sort in descending order by ratio of list1[i] to list2[i]
# but instead of rearranging list1 and list2, keep the order in
# a separate array
def bubblesortByRatio(list1, list2):
n = len(list1)
order = list(range(n))
for i in range(n - 1, 0, -1): # i ranges from n-1 down to 1
for j in range(0, i): # j ranges from 0 up to i-1
# if ratio of jth numbers > ratio of (j+1)st numbers then
if ((1.0 * list1[order[j]]) / list2[order[j]]) < ((1.0 * list1[order[j+1]]) / list2[order[j+1]]):
temp = order[j] # exchange "pointers" to these items
order[j] = order[j+1]
order[j+1] = temp
return order
#cap = 50
#collected_value = 0
#vals = [60, 100, 120]
#whts = [20, 50, 30]
print(KnapsackFrac(vals, whts, cap)[1]) |
import os
import psutil
from .base import Base
class System(Base):
"""
Collector for system.
This collector is always enabled, and you can't disable it. This is
intentional, as I can't think of a reason why you'd want to collect
metrics from a server without caring about its health. :) This also
enables Pikka Bird to be useful out the box; even with no configuration,
it should at least start monitoring useful things.
Every type of metric within this collector is always gathered.
This collector gathers metrics for:
- load average
- CPU usage
- memory usage
- disk usage
DEPENDENCIES:
None
SETTINGS:
minimal:
None
supported:
None
"""
# accuracy to use for ratios (decimal places)
RATIO_DP = 4
# time to sample CPUs (s)
CPU_SAMPLE_S = 0.1
def enabled(self):
return True
def collect(self):
return {
'load': self.__load(),
'cpu': self.__cpu(),
'memory': self.__memory(),
'disk': self.__disk()}
def __load(self):
l_round = lambda e: round(e, self.RATIO_DP)
try:
load1, load5, load15 = os.getloadavg()
return {
'avg': {
'1': l_round(load1),
'5': l_round(load5),
'15': l_round(load15)}}
except OSError:
return {}
def __cpu(self):
metrics = {}
ctps = psutil.cpu_times_percent(self.CPU_SAMPLE_S, percpu=True)
l_round = lambda e: round(e / 100.0, self.RATIO_DP)
for cpu_i, ctp in enumerate(ctps):
ctp_fs = ctp._fields
metrics_cpu = {
'idle': {
'/': l_round(ctp.idle)},
'busy': {
'/': l_round(100 - ctp.idle),
'user': {
'/': l_round(ctp.user)},
'system': {
'/': l_round(ctp.system)}}}
if 'nice' in ctp_fs and ctp.nice:
metrics_cpu['busy']['nice'] = {
'/': l_round(ctp.nice)}
if 'iowait' in ctp_fs and ctp.iowait:
metrics_cpu['busy']['iowait'] = {
'/': l_round(ctp.iowait)}
if 'irq' in ctp_fs and ctp.irq:
metrics_cpu['busy']['irq'] = {
'/': l_round(ctp.irq)}
if 'softirq' in ctp_fs and ctp.softirq:
metrics_cpu['busy']['softirq'] = {
'/': l_round(ctp.softirq)}
if 'steal' in ctp_fs and ctp.steal:
metrics_cpu['busy']['steal'] = {
'/': l_round(ctp.steal)}
if 'guest' in ctp_fs and ctp.guest:
metrics_cpu['busy']['guest'] = {
'/': l_round(ctp.guest)}
if 'guest_nice' in ctp_fs and ctp.guest_nice:
metrics_cpu['busy']['guest_nice'] = {
'/': l_round(ctp.guest_nice)}
metrics[cpu_i] = metrics_cpu
return metrics
def __memory(self):
metrics = {}
virtual = psutil.virtual_memory()
virtual_fs = virtual._fields
virtual_unavail = virtual.total - virtual.available
virtual_total = float(virtual.total) # COMPAT: Python 2.7
l_round = lambda e: round(e / virtual_total, self.RATIO_DP)
metrics_virtual = {
'b': virtual.total,
'avail': {
'b': virtual.available,
'/': l_round(virtual.available)},
'used': {
'b': virtual.used,
'/': l_round(virtual.used)},
'free': {
'b': virtual.free,
'/': l_round(virtual.free)},
'unavail': {
'b': virtual_unavail,
'/': l_round(virtual_unavail)}}
if 'active' in virtual_fs and virtual.active:
metrics_virtual['active'] = {
'b': virtual.active,
'/': l_round(virtual.active)}
if 'inactive' in virtual_fs and virtual.inactive:
metrics_virtual['inactive'] = {
'b': virtual.inactive,
'/': l_round(virtual.inactive)}
if 'buffers' in virtual_fs and virtual.buffers:
metrics_virtual['buffers'] = {
'b': virtual.buffers,
'/': l_round(virtual.buffers)}
if 'cached' in virtual_fs and virtual.cached:
metrics_virtual['cached'] = {
'b': virtual.cached,
'/': l_round(virtual.cached)}
if 'wired' in virtual_fs and virtual.wired:
metrics_virtual['wired'] = {
'b': virtual.wired,
'/': l_round(virtual.wired)}
if 'shared' in virtual_fs and virtual.shared:
metrics_virtual['shared'] = {
'b': virtual.shared,
'/': l_round(virtual.shared)}
metrics['virtual'] = metrics_virtual
swap = psutil.swap_memory()
metrics_swap = {
'b': swap.total,
'used': {
'b': swap.used},
'free': {
'b': swap.free},
'sin': {
'b': swap.sin},
'sout': {
'b': swap.sout}}
swap_total = float(swap.total) # COMPAT: Python 2.7
if swap.total > 0:
metrics_swap['free']['/'] = round(swap.free / swap_total, self.RATIO_DP)
metrics_swap['used']['/'] = round(swap.used / swap_total, self.RATIO_DP)
metrics['swap'] = metrics_swap
return metrics
def __disk(self):
metrics = {}
partitions = [p for p in psutil.disk_partitions(all=False)]
l_round = lambda e, f: round(e / f, self.RATIO_DP)
for partition in partitions:
try:
stats = os.statvfs(partition.mountpoint)
usage = psutil.disk_usage(partition.mountpoint)
stats_f_blocks = float(stats.f_blocks) # COMPAT: Python 2.7
stats_f_files = float(stats.f_files) # COMPAT: Python 2.7
usage_total = float(usage.total) # COMPAT: Python 2.7
metrics[partition.mountpoint] = {
'block_size': {
'b': stats.f_bsize},
'blocks': {
'n': stats.f_blocks,
'free': {
'n': stats.f_bfree,
'/': l_round(stats.f_bfree, stats_f_blocks)},
'avail': {
'n': stats.f_bavail,
'/': l_round(stats.f_bavail, stats_f_blocks)}},
'device': partition.device,
'filename_len_max': stats.f_namemax,
'flags': stats.f_flag,
'fragment_size': {
'b': stats.f_frsize},
'fstype': partition.fstype,
'inodes': {
'n': stats.f_files,
'free': {
'n': stats.f_ffree,
'/': l_round(stats.f_ffree, stats_f_files)},
'avail': {
'n': stats.f_favail,
'/': l_round(stats.f_favail, stats_f_files)}},
'space': {
'b': usage.total,
'free': {
'b': usage.free,
'/': l_round(usage.free, usage_total)},
'used': {
'b': usage.used,
'/': l_round(usage.used, usage_total)}}}
except (IOError, OSError):
metrics[partition.mountpoint] = {}
return metrics
|
from . import globals
class UniformModel(object):
def __init__(self, b=(1., 0., 0.), e=(0., 0., 0.), **kwargs):
self.model = {"model": "model", "model_name": "uniform"}
if globals.sim is None:
raise RuntimeError("A simulation must be declared before a model")
if globals.sim.model is not None:
raise RuntimeError("A model is already created")
else:
globals.sim.set_model(self)
if len(b) != 3 or (not isinstance(b, tuple) and not isinstance(b, list)):
raise ValueError("invalid B")
if len(e) != 3 or (not isinstance(e, tuple) and not isinstance(e, list)):
raise ValueError("invalid E")
self.model.update({"bx": lambda x : b[0],
"by": lambda x : b[1],
"bz": lambda x : b[2],
"ex": lambda x : e[0],
"ey": lambda x : e[1],
"ez": lambda x : e[2]})
self.populations = kwargs.keys()
for population in self.populations:
self.add_population(population, **kwargs[population])
# ------------------------------------------------------------------------------
def nbr_populations(self):
"""
returns the number of species currently registered in the model
"""
return len(self.populations)
#------------------------------------------------------------------------------
def add_population(self, name,
charge=1.,
mass=1.,
nbr_part_per_cell=100,
density=1.,
vbulk=(0., 0., 0.),
beta=1.0,
anisotropy=1.):
"""
add a particle population to the current model
add_population(name,charge=1, mass=1, nbrPartCell=100, density=1, vbulk=(0,0,0), beta=1, anisotropy=1)
Parameters:
-----------
name : name of the species, str
Optional Parameters:
-------------------
charge : charge of the species particles, float (default = 1.)
nbrPartCell : number of particles per cell, int (default = 100)
density : particle density, float (default = 1.)
vbulk : bulk velocity, tuple of size 3 (default = (0,0,0))
beta : beta of the species, float (default = 1)
anisotropy : Pperp/Ppara of the species, float (default = 1)
"""
idx = str(self.nbr_populations())
new_population = {name: {
"charge": charge,
"mass": mass,
"density": lambda x : density,
"vx": lambda x : vbulk[0],
"vy": lambda x : vbulk[1],
"vz": lambda x : vbulk[2],
"beta": lambda x : beta,
"anisotropy": lambda x : anisotropy,
"nbrParticlesPerCell": nbr_part_per_cell}}
keys = self.model.keys()
if name in keys:
raise ValueError("population already registered")
self.model.update(new_population)
#------------------------------------------------------------------------------
def to_dict(self):
self.model['nbr_ion_populations'] = self.nbr_populations()
return self.model
|
import numpy as np
def rombf(a,b,N,func,param) :
"""Function to compute integrals by Romberg algorithm
R = rombf(a,b,N,func,param)
Inputs
a,b Lower and upper bound of the integral
N Romberg table is N by N
func Name of integrand function in a string such as
func='errintg'. The calling sequence is func(x,param)
param Set of parameters to be passed to function
Output
R Romberg table; Entry R(N,N) is best estimate of
the value of the integral
"""
#* Compute the first term R(1,1)
h = b - a # This is the coarsest panel size
npanels = 1 # Current number of panels
R = np.zeros((N+1,N+1))
R[1,1] = h/2. * (func(a,param) + func(b,param))
#* Loop over the desired number of rows, i = 2,...,N
for i in range(2,N+1) :
#* Compute the summation in the recursive trapezoidal rule
h = h/2. # Use panels half the previous size
npanels *= 2 # Use twice as many panels
sumT = 0.
# This for loop goes k=1,3,5,...,npanels-1
for k in range(1,npanels,2) :
sumT += func(a + k*h, param)
#* Compute Romberg table entries R(i,1), R(i,2), ..., R(i,i)
R[i,1] = 0.5 * R[i-1,1] + h * sumT
m = 1
for j in range(2,i+1) :
m *= 4
R[i,j] = R[i,j-1] + ( R[i,j-1] - R[i-1,j-1] )/(m-1)
return R |
import os
import sys
import pika
import uuid
from conversation_types import Invitation, ConversationMessage, LocalType
from core.message_adapter import AMQPConversationMessageAdapter
from core.conversation_interceptor import ConversationInterceptor
"""Start a test for monitoring an existing conversation"""
def start_monitor(participant):
try:
initiator_monitor = ConversationInterceptor(participant)
initiator_monitor.start()
except:
sys.exit()
def create_invitation(cid, role, participant, lt_file):
return Invitation(cid = cid,
role = role,
local_capability = lt_file,
participant = participant)
class Protocol(object):
""" participant_description contains lists with elements of the form:
[participant, role, lt_file]
"""
def __init__(self, cid, particpants_description):
self.cid = cid
self.participants_description = particpants_description
self.invitations = self.create_invitations()
def create_invitations(self):
invitations = {}
[invitations.setdefault(create_invitation(self.cid, node[1], node[0], node[2]))
for node in self.participants_description]
return invitations
class InterruptExcpetion(object):
"""This is the Interrupt Exception class."""
def __init__(self, value):
self.value = value
def __str__(self):
return 'self.value'
"""
Example of configure_protocol
def create_data_acquisition_conversation(cid):
participants = [['carol', 'A', apps_utils.get_lt_full_name('DataAcquisition_at_A.spr')],
['bob', 'U', apps_utils.get_lt_full_name('DataAcquisition_at_U.spr')],
['alice', 'I', apps_utils.get_lt_full_name('DataAcquisition_at_I.spr')]]
conversation = Protocol(cid, participants)
return conversation
"""
class Conversation(object):
def __init__(self, role,
participant,
participants_config = None,
is_monitorable = False):
# Participant attributes
self.role = str.lower(role)
self.participant = str.lower(participant)
# Communication related
#self.cid = str(uuid.uuid4())
self.adapter = AMQPConversationMessageAdapter()
self.invitation_queue = self.participant
#Protocol related
self.participants_description = participants_config if participants_config else None
self.protocol = None
interrupt_msg = None
interrup_callback = None
#TODO: Fix me!!!
self.is_monitorable = is_monitorable
self.configure_invitation_bindings()
@classmethod
def join(cls, configuration, self_role, participant, is_originator = False, is_monitorable = False):
conversation = Conversation(self_role, participant, configuration, is_monitorable)
conversation.__establish_connection()
if (is_originator):
conversation.cid = str(uuid.uuid4())
invitations = conversation.create_invitations()
conversation.invite_self_role(invitations)
conversation.invite_participants(invitations)
else:
conversation.receive_invitation()
return conversation
def send(self, other_role, label, *args):
conv_msg = ConversationMessage(self.cid, label,
args, self.role,
other_role)
msg = self.adapter.from_converastion_msg(conv_msg)
print "Publishing msg to exchange:%s with binding: %s \n message: %s" %(self.exchange_name,
conv_msg.get_binding(), msg)
self.channel.basic_publish(exchange = self.exchange_name,
routing_key = conv_msg.get_binding(),
body = msg)
def receive(self, role):
self.received_msg = None
while self.received_msg == None:
method_frame, _ , body = self.channel.basic_get(queue=str.lower(self.role), no_ack = True)
# It can be empty if the queue is empty so don't do anything
if method_frame.NAME == 'Basic.GetEmpty':
pika.log.info("Empty Basic.Get Response (Basic.GetEmpty)")
# We have data
else: self.received_msg = self.adapter.to_conversation_msg(body)
# Acknowledge the receipt of the data
print 'I have received the message!'
print 'The received message is:%s' %(self.received_msg)
return self.received_msg
def create_invitations(self):
invitations = []
[invitations.append(create_invitation(self.cid, node[1], node[0], node[2]))
for node in self.participants_description]
return invitations
def configure_interrup(self, interaction_msg, callback):
self.interrupt_msg = interaction_msg
self.interrup_callback = callback
def configure_invitation_bindings(self):
self.invitation_exchange = self.participant if self.is_monitorable else ''
def configure_bindings(self):
self.exchange_name = str.lower(self.participant) if self.is_monitorable else str(self.cid)
def __handle_receive(self, ch, method, properties, body):
print 'In received messages!'
self.received_msg = self.adapter.to_conversation_msg(body)
#self.channel.stop_consuming()
#TODO: Handle interrupt message, please
#if (self.interrupt_msg and (self.interrupt_msg.label == self.received_msg.label)):
# raise InterruptExcpetion('interrupt')
def invite_self_role(self, invitations):
self_invitation = [inv for inv in invitations
if (inv.participant == self.participant)]
if (not self_invitation):
raise Exception('List of invitations does not have the participant name: %s' %(self.participant))
self_invitation = self_invitation.pop()
self.send_invitation(self_invitation)
self.receive_invitation()
def invite_participants(self, invitations):
[self.send_invitation(inv) for inv in invitations
if not(inv.participant == self.participant)]
def receive_invitation(self):
channel= self.channel
print "receive_invitation: wait on exchange:%s binding:%s" %(self.invitation_exchange, self.invitation_queue)
channel.queue_declare(queue=self.invitation_queue)
if not(self.invitation_exchange==''):
channel.queue_bind(exchange = self.invitation_exchange,
queue=self.invitation_queue,
routing_key=self.invitation_queue)
channel.basic_consume(self.accept_invitation,
queue = self.invitation_queue,
no_ack = True)
self.channel.start_consuming()
def accept_invitation(self, ch, method, properties, body):
print "accept_invitation: %s" %(body)
self.channel.stop_consuming()
invitation = self.adapter.to_invitation_msg(body)
awaiting_invitation = create_invitation(invitation.cid, self.role, self.participant, invitation.local_capability)
# Monitor also checks the invitation
if (awaiting_invitation.participant==invitation.participant):
self.cid = invitation.cid
self.configure_bindings()
self.incoming_binding = str.lower("*.*.%s" %(self.role))
print"in accept: queue%s, exchange: %s" %(self.role, self.exchange_name)
self.channel.exchange_declare(exchange = self.exchange_name, type='topic')
self.channel.queue_declare(queue=str.lower(self.role))
self.channel.queue_bind(exchange=self.exchange_name,
queue=str.lower(self.role),
routing_key=self.incoming_binding)
else:
raise Exception("Invitation:%s does not match with participant awaiting invitation:%s"
%(invitation.__dict__, awaiting_invitation.__dict__))
def send_invitation(self, invitation):
"""
We create participant queue that will handle the invitation
to handle the case when the required participant has not yet started
"""
print "send_invitation: %s" %(invitation)
self.channel.queue_declare(queue=invitation.invitation_queue_name())
msg = self.adapter.from_invitation_msg(invitation)
self.channel.basic_publish(exchange = '',
routing_key=invitation.invitation_queue_name(),
body=msg)
def __establish_connection(self):
print "establish_connection %s" %(self.participant)
self.connection = pika.BlockingConnection(pika.ConnectionParameters(host = 'localhost'))
self.channel = self.connection.channel()
def close(self):
self.connection.close()
def receive_async(self, role, callback):
# FIX me!. I should be asynchronous
self.received_msg = None
self.callback = callback
self.channel.basic_consume(self.__handle_async_receive,
queue = str.lower(self.role),
no_ack = True)
self.channel.start_consuming()
def __handle_async_receive(self, ch, method, properties, body):
self.channel.stop_consuming()
msg = self.adapter.to_conversation_msg(body)
self.callback(self, msg)
|
# implement an algorithm to find the kth to last element in a linked list
import random
import linkedlist
def kth_to_last(_list, k):
_list.reverse()
current = _list.head
counter = 1
while counter < k:
current = current.next
counter += 1
return current.value
if __name__ == "__main__":
linked = linkedlist.LinkedList()
for i in range(20):
linked.push(random.randint(0, 10))
linked.traverse()
print ("\n------------")
print kth_to_last(linked, 3)
|
'''Booleans: True False Logic'''
# Boolean values are the two constant objects False and True. In numeric
# contexts, they behave like the integers 0 and 1, respectively. The built-in
# function bool() can be used to check any value as a Boolean, if the value can
# be interpreted as a truth value.
a = [1, 3, 6]
b = []
c = None
print(bool(a)) # True
print(bool(b)) # False
print(bool(c)) # False
# True
# False
# and
# or
# in
# is
# not
# not ... or
# not ... and
# not in
# is not
# ==
# !=
# >=
# <=
# Any 'and' expression that has a False is immediately False
# Any 'or' expression that has a True is immediately True
print(not False) # True
print(not True) # False
print(True or False) # True
print(True or True) # True
print(False or True) # True
print(False or False) # False
print(True and False) # False
print(True and True) # True
print(False and True) # False
print(False and False) # False
print(not (True or False)) # False
print(not (True or True)) # False
print(not (False or True)) # False
print(not (False or False)) # True
print(not (True and False)) # True
print(not (True and True)) # False
print(not (False and True)) # True
print(not (False and False)) # True
print(1 != 0) # True
print(1 != 1) # False
print(0 != 1) # True
print(0 != 0) # False
print(1 == 0) # False
print(1 == 1) # True
print(0 == 1) # False
print(0 == 0) # True
|
import numpy as np
import random
import math
from scipy.optimize import minimize
from tabulate import tabulate
import matplotlib.pyplot as plt
class SVM:
def __init__(self, classA, classB, C=0.1, filename='', kernel='linear', sigma=1.0, degree=3):
self.inputs = np.concatenate((classA, classB))
self.targets = np.concatenate((np.ones(classA.shape[0]), -np.ones(classB.shape[0])))
N = self.inputs.shape[0] # Number of rows (samples)
self.filename = filename
self.kernel = kernel
self.degree = degree
self.sigma = sigma
# C = 3.0
# shuffle data
permute = list(range(N))
random.shuffle(permute)
self.inputs = self.inputs[permute, :]
self.targets = self.targets[permute]
# Calculate helper variable P (used for
self.P = np.transpose(np.matrix(self.targets)) * self.targets
for i in range(self.P.shape[0]):
for j in range(self.P.shape[1]):
self.P[i, j] *= self.kernel_caller(self.inputs[i], self.inputs[j])
start = np.zeros(N) # Initial guess of the alpha-vector
B = [(0, C) for b in range(N)]
XC = {'type': 'eq', 'fun': self.zerofun}
# find minimum of objective function
ret = minimize(self.objective, start, bounds=B, constraints=XC)
alpha = ret['x']
if ret['success']:
print("Minimize function was successfull :)\n")
else:
print("Minimize function was not successfull :(\n")
# calculate the alpha values that drive SVM
self.non_zero_alpha = []
for index, value in enumerate(alpha):
if value > 10 ** (-5):
self.non_zero_alpha.append((self.inputs[index], self.targets[index], value))
print(tabulate(self.non_zero_alpha, headers=['input', 'target', 'alpha']), "\n")
# Bias calculation
# First: find support vector. This "corresponds to any point with an α-value larger than zero, but less than C"
sv = 0
for i, entry in enumerate(self.non_zero_alpha):
if entry[2] < C - 10 ** (-5):
print(entry[2], "<", C - 10 ** (-5))
sv = i
break
# Now calulate bias:
self.bias = 0
for entry in self.non_zero_alpha:
self.bias += entry[2] * entry[1] * self.kernel_caller(self.non_zero_alpha[sv][0], entry[0])
self.bias -= self.non_zero_alpha[sv][1]
print("Calculated bias:", self.bias)
self.calc_plot_points(classA, classB)
self.plotter(classA, classB)
# The kernel caller function is used to specify, which kernel & kernel parameters should be used:
def kernel_caller(self, x, y):
if self.kernel == 'linear':
return self.kernel_linear(x, y)
elif self.kernel == 'polynomial':
return self.kernel_polynomial(x, y, self.degree)
else:
return self.kernel_RBF(x, y, self.sigma)
def kernel_linear(self, x, y):
return np.transpose(x) @ y
def kernel_polynomial(self, x, y, degree):
return (np.transpose(x) @ y + 1) ** degree
def kernel_RBF(self, x, y, sigma):
return math.exp(-np.linalg.norm(x - y, 2) / (2 * (sigma ** 2)))
def objective(self, alphas):
alph = np.dot(self.P, np.transpose(alphas))
alph = np.dot(alphas, np.transpose(alph))
alph /= 2
alph -= sum(alphas)
return alph
def zerofun(self, alphas):
return np.transpose(self.targets) @ alphas
def indicator(self, x, y):
ind = 0
for entry in self.non_zero_alpha:
ind += entry[2] * entry[1] * self.kernel_caller([x, y], entry[0])
ind -= self.bias
return ind
def calc_plot_points(self, classA, classB):
self.plotting_classA = []
self.plotting_classB = []
self.plotting_classA_SV = []
self.plotting_classB_SV = []
for i, entry_i in enumerate(classA):
sv = False
for j, entry_j in enumerate(self.non_zero_alpha):
if np.array_equal(entry_i[0], entry_j[0][0]) & np.array_equal(entry_i[1], entry_j[0][1]):
self.plotting_classA_SV.append(entry_i)
sv = True
break
if not sv:
self.plotting_classA.append(entry_i)
for i, entry_i in enumerate(classB):
sv = False
for j, entry_j in enumerate(self.non_zero_alpha):
if np.array_equal(entry_i[0], entry_j[0][0]) & np.array_equal(entry_i[1], entry_j[0][1]):
self.plotting_classB_SV.append(entry_i)
sv = True
break
if not sv:
self.plotting_classB.append(entry_i)
def plotter(self, classA, classB):
# Plotting:
plt.plot([p[0] for p in classA], [p[1] for p in classA], 'b.')
plt.plot([p[0] for p in classB], [p[1] for p in classB], 'r.')
plt.plot([p[0] for p in self.plotting_classA_SV], [p[1] for p in self.plotting_classA_SV], 'b+', markersize=12)
plt.plot([p[0] for p in self.plotting_classB_SV], [p[1] for p in self.plotting_classB_SV], 'r+', markersize=12)
plt.axis('equal') # Force same scale on both axes
plt.xlabel('x1')
plt.ylabel('x2')
xgrid = np.linspace(-5, 5)
ygrid = np.linspace(-4, 4)
grid = np.array([[self.indicator(x, y) for x in xgrid] for y in ygrid])
plt.contour(xgrid, ygrid, grid, 0, colors='black', linewidths=1)
plt.contour(xgrid, ygrid, grid, (-1, 1), colors='green', linewidths=1, linestyles='dashed')
if self.filename:
plt.savefig('figures/' + self.filename + '.jpg') # Save a copy in a file
plt.show() # Show the plot on the screen
|
import cv2
cap = cv2.VideoCapture(0)
haar_cascade_face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
while True:
ret, frame = cap.read()
if ret:
faces_rects = haar_cascade_face.detectMultiScale(frame, scaleFactor=1.2, minNeighbors=5)
print(' ', len(faces_rects))
for (x, y, w, h) in faces_rects:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
crop_image = frame[y:y + h, x:x + w]
cv2.putText(frame,"asd",(x,y),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(0,0,255),2)
cv2.imshow('frame',frame)
cv2.waitKey(0)
|
import AllServers
import Server
import sys
import os
import subprocess
class Main:
try:
#print "\n\n\nNow the client will logon to the connect command. \nThere are four commands that will be run, \'connect\', \'*username*\' \'*password*\' \'cd /root\'. \n You need to press enter for each one to be run. It is important that you do not run the \'connect\' command untill you se the admin-flag.\n It is also important that you do not send the username before you see a clear terminal. And that you send the password shortly after you have supplied the username.\nYou need to keep track of which command is to be run since there will be no further instruction until you have logged in successfully. \n\nIt sounds hard but it's really not, let's get started! \n\nThe first step is manually logging in in the window to the right."
client=AllServers.AllServers()
client.IpCasesFile = 'IpCasesFile.txt'
client.ServerMacIp = 'ServerMacIp.txt'
client.ECUT = 'ECUT_file_basic_info.txt'
client.pipeList = [sys.argv[1], sys.argv[2]]
print "Welcome to ExCALIBUR"
client.prepareOnceForAll()
client.setCurrentServer()
while client.iCounter<len(client.SMIpList):
client.currentServer.serverName=client.SMIpList[client.iCounter][0]
client.currentServer.macAddress=client.SMIpList[client.iCounter][1]
os.system("gnome-terminal -e 'bash -c \"ssh -tt root@" +client.currentServer.serverName+"-idrac < en.fifo > en2.fifo; bash\" '")
client.doAllThings()
client.iCounter += 1
client.fileText = 0
client.possibleExistence=0
client.bStop=False
#except LookupError:
#client.iCounter+=1
#This is supposed to make the program logout from the iDRAC even if CTRL+C is pressed.
except KeyboardInterrupt:
print "\nJust logging out first...\n"
try:
client.doFinalThings()
except NameError:
pass
finally:
sys.exit(0)
|
def getOrderFromDict(d):
return RobinhoodOrder(d['symbol'],d['action'],d['shares'],d['price'],d['date'])
class RobinhoodOrder(object):
def __init__(self, symbol, action, shares, price, date):
self.symbol = symbol
self.action = action
self.shares = shares
self.price = price
self.date = date
def __str__(self):
return "{} {} shares of {} on {} for ${}".format(self.action, self.shares, self.symbol, self.date, self.price)
def getPrice(self):
if self.action == "buy":
return -1 * float(self.price) * float(self.shares)
return float(self.price) * float(self.shares)
def getDate(self):
return self.date.split("T")[0]
def getCsvHeader(self):
return ["symbol", "action", "shares", "price", "date"]
def getCsvRow(self):
return [self.symbol, self.action, self.shares, self.price, self.date] |
from random import randint
tentativas = escolhido = 0
sorteado = 1
while escolhido != sorteado:
escolhido = int(input('Digite um número: '))
sorteado = randint(0, 10)
if escolhido < 0 or escolhido > 10:
print('Número inválido, digite um número de 0 a 5')
elif escolhido == sorteado:
print('Parabéns você acertou')
else:
print('Errrrôoou, o número sorteado pelo computador foi: {}'.format(sorteado))
tentativas += 1
print("Você tentou {} vezes para acertar".format(tentativas)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.