def __init__(self, board, filename): """Save a board as an image. Arguments: board -- the board filename -- the filename """ self.numbers = board.numbers self.cellsize = board.cellsize self.boardsize = board.boardsize self.filename = filename if options.get("image", "format"): self.format = options.get("image", "format") else: self.format = re.sub(".*\.", "", filename) # 10% for borders self.square_width = options.getint("image", "width") / \ (self.boardsize + 1) self.square_height = options.getint("image", "height") / \ (self.boardsize + 1) self.create() self.draw_board() self.draw_numbers() self.save()
def verify_auth(): if request.path.startswith('/api/'): auth_header = request.headers.get('X-Auth-Key', None) nonce = request.headers.get('X-Auth-Nonce', None) timestamp = request.headers.get('X-Auth-Timestamp', None) sig = request.headers.get('X-Auth-Sig', None) skip_auth = options.get('skipAuth', False) if options.get('testEnabled', False): testingMode = int(request.headers.get('X-Auth-TestingMode', 0)) if testingMode == 1: skip_auth = True if not skip_auth: req_body = request.data if None in [auth_header, nonce, timestamp, sig]: return abort(401) if abs(int(time.time()) - int(timestamp)) > 60 * 5: return abort(401) if req_body == "": req_body = {} else: req_body = json.loads(req_body) body_str = json.dumps(req_body, sort_keys=True, separators=(',', ':')) Key = Api_Key.query.filter_by(api_key=auth_header).first() if Key is None: return abort(401) message = ''.join([str(auth_header), str(nonce), str(timestamp), body_str, request.path]) hash_digest = hashlib.sha256(message).digest() hmac_digest = hmac.new(str(Key.secret_key), hash_digest, hashlib.sha512).digest() g.username = Key.user.username if not base64.b64encode(hmac_digest) == sig: abort(401)
def draw_numbers(self): """Draw the numbers.""" font = PIL.ImageFont.truetype(options.get("image", "font"), options.getint("image", "font_size")) # 5% margin + half square x = options.getint("image", "width") / 20 + self.square_width / 2 y = options.getint("image", "height") / 20 + self.square_height / 2 for i in xrange(self.boardsize): for j in xrange(self.boardsize): if self.numbers[j][i] != 0: if options.getboolean("sudoku", "use_letters"): text = str(Value(self.numbers[j][i])) else: text = str(Value(self.numbers[j][i]).integer()) size = self.draw.textsize(text, font=font) # this should be: #self.draw.text((x + i * self.square_width - size[0] / 2, # y + j * self.square_height - size[1] / 2), # text) # but it's not centered without the + 2 in the y coord self.draw.text((x + i * self.square_width - size[0] / 2, y + j * self.square_height - size[1] / 2 + 2), text, fill=options.get("image", "font_colour"), font=font)
def draw_numbers(self): """Draw the numbers.""" self.c.setFillColor(options.get("pdf", "font_colour")) self.c.setFont(options.get("pdf", "font"), options.getint("pdf", "font_size")) face = reportlab.pdfbase.pdfmetrics.getFont("Helvetica").face height = (face.ascent - face.descent) * \ options.getint("pdf", "font_size") / 1000.0 if self.page_size[0] < self.page_size[1]: square_length = self.page_size[0] / (self.boardsize) * 0.9 x = self.page_size[0] / 20 + square_length / 2 y = (self.page_size[1] - self.page_size[0] * 0.9 + \ square_length - height) / 2 else: square_length = self.page_size[1] / (self.boardsize) * 0.9 y = self.page_size[1] / 20 + square_length / 2 x = (self.page_size[0] - self.page_size[1] * 0.9 + \ square_length - height) / 2 for i in xrange(self.boardsize): for j in xrange(self.boardsize): if self.numbers[self.boardsize - 1 - j][i] != 0: if options.getboolean("sudoku", "use_letters"): text = str(Value(self.numbers[self.boardsize - 1 - j][i])) else: text = str(Value(self.numbers[self.boardsize - 1 - j][i]).integer()) self.c.drawCentredString(x + i * square_length, y + j * square_length, text)
def create_sudoku(filename): """Create a sudoku with handicap and save it to filename. The handicap are the extra numbers given. Arguments: filename -- the file name """ while True: print _(u"Creating sudoku..."), sys.stdout.flush() sudoku = Sudoku(Board((options.getint("sudoku", "region_width"), options.getint("sudoku", "region_height"))), difficulty=options.get("sudoku", "difficulty")) sudoku.create(options.getint("sudoku", "handicap")) if options.getboolean("sudoku", "force") and \ (difficulty(sudoku.to_board()) != options.get("sudoku", "difficulty")): print _(u"sudoku with wrong difficulty!") else: sudoku.to_board().save(filename) print _(u"success!") break draw_board(sudoku.to_board()) return True
def create(self): """Create a blank image widthxheight.""" if not options.get("image", "background"): mode = "RGBA" elif self.in_greyscale(options.get("image", "background")) and \ self.in_greyscale(options.get("image", "lines_colour")) and \ self.in_greyscale(options.get("image", "font_colour")): mode = "L" else: mode = "RGB" self.im = PIL.Image.new(mode, (options.getint("image", "width"), options.getint("image", "height")), options.get("image", "background")) self.draw = PIL.ImageDraw.Draw(self.im)
def draw_filename(self): """Draw the filename.""" if options.getint("pdf", "filename_size") > 0 and self.filename: self.c.setFillColor(options.get("pdf", "filename_colour")) self.c.setFont(options.get("pdf", "filename_font"), options.getint("pdf", "filename_size")) face = reportlab.pdfbase.pdfmetrics.getFont("Helvetica").face height = (face.ascent - face.descent) * \ options.getint("pdf", "filename_size") / 1000.0 self.c.drawCentredString(self.page_size[0] / 2, (self.page_size[1] - \ self.page_size[0] * 0.9) / 2 + \ self.page_size[0] * 0.9 + \ height / 2, "(" + str(self.filename) + ")")
def draw_title(self): """Draw the title "sudou".""" if options.getint("pdf", "title_size") > 0: self.c.setFillColor(options.get("pdf", "title_colour")) self.c.setFont(options.get("pdf", "title_font"), options.getint("pdf", "title_size")) face = reportlab.pdfbase.pdfmetrics.getFont("Helvetica").face height = (face.ascent - face.descent) * \ options.getint("pdf", "title_size") / 1000.0 self.c.drawCentredString(self.page_size[0] / 2, (3 * self.page_size[1] + \ 0.9 * self.page_size[0]) / 4 - \ options.getint("pdf", "title_size") / 2 + \ height / 2, "sudoku")
def draw_board(self): """Draw the board. Only the board, to draw numbers draw_numbers it is used. """ # margins x = options.getint("image", "width") / 20 # 5% left margin y = options.getint("image", "height") / 20 # 5% top margin self.draw.rectangle(((x, y), (options.getint("image", "width") - x, options.getint("image", "height") - y)), outline=options.get("image", "lines_colour"), fill=None) linewidth = 0 # horizontal lines for i in xrange(self.boardsize): if i > 0 and i % self.cellsize[1] == 0: linewidth = 2 else: linewidth = 1 # PIL <= 1.1.4 for offset in range(linewidth): self.draw.line(((x, y + i * self.square_height + offset), (options.getint("image", "width") - x, y + i * self.square_height + offset)), options.get("image", "lines_colour")) # PIL > 1.1.5 #self.draw.line(((x, y + i * self.square_height), # (options.getint("image", "width") - x, # y + i * self.square_height)), # fill=options.get("image", "lines_colour"), # width=linewidth) # vertical lines for i in xrange(self.boardsize): if i > 0 and i % self.cellsize[0] == 0: linewidth = 2 else: linewidth = 1 # PIL <= 1.1.4 for offset in range(linewidth): self.draw.line(((x + i * self.square_width + offset, y), (x + i * self.square_width + offset, options.getint("image", "height") - y)), options.get("image", "lines_colour"))
def __init__(self, board): """Print a board. Arguments: board -- the board """ if not options.get("print", "command"): print >> sys.stderr, _(u"Print command not set") return dirname = tempfile.mkdtemp() filename = os.path.join(dirname, "sudoku.pdf") PDF(board, filename) # print it os.system("%s %s" % (options.get("print", "command"), filename)) # remove it os.unlink(filename) os.rmdir(dirname)
def verify_auth(): if request.path.startswith('/api/'): auth_header = request.headers.get('X-Auth-Key', None) nonce = request.headers.get('X-Auth-Nonce', None) timestamp = request.headers.get('X-Auth-Timestamp', None) sig = request.headers.get('X-Auth-Sig', None) skip_auth = options.get('skipAuth', False) if options.get('testEnabled', False): testingMode = int(request.headers.get('X-Auth-TestingMode', 0)) if testingMode == 1: skip_auth = True if not skip_auth: req_body = request.data if None in [auth_header, nonce, timestamp, sig]: return abort(401) if abs(int(time.time()) - int(timestamp)) > 60 * 5: return abort(401) if req_body == "": req_body = {} else: req_body = json.loads(req_body) body_str = json.dumps(req_body, sort_keys=True, separators=(',', ':')) Key = Api_Key.query.filter_by(api_key=auth_header).first() if Key is None: return abort(401) message = ''.join([ str(auth_header), str(nonce), str(timestamp), body_str, request.path ]) hash_digest = hashlib.sha256(message).digest() hmac_digest = hmac.new(str(Key.secret_key), hash_digest, hashlib.sha512).digest() g.username = Key.user.username if not base64.b64encode(hmac_digest) == sig: abort(401)
def put(self, user_id): """ edit user information --- tags: - users parameters: - in: body name: body schema: id: user_in responses: 201: description: User created schema: id: user_out 404: description: user not found schema: id: error """ # celery test # rq = tasks.hello.apply_asyc(args=["Put User"]) # results = async_result.AsyncResult(str(rq)) # print results.get() user = User.query.filter_by(id=user_id).first() if user is None: return jsonify(error="user not found"), 404 else: updates = request.get_json() for key, value in updates.iteritems(): if key == "password": if options.get('testEnabled', False): # less secure for testing - faster pw_hash = bcrypt.hashpw(value, bcrypt.gensalt(4)) else: pw_hash = bcrypt.hashpw(value, bcrypt.gensalt(14)) setattr(user, key, pw_hash) elif hasattr(user, key): setattr(user, key, value) db.session.add(user) db.session.commit() # return user info return jsonify(user=user.as_json()), 201
def OnKey(self, event): bkey = options.get('main-opts', 'bkey') keypress = event.GetKeyCode() valid_keys = list('HSDP') valid_keys.append(bkey) keylist = list() for key in valid_keys: keylist.append(ord(key)) if keypress in keylist: if keypress == ord(bkey): self.SwapView() else: self.CheckPlay(chr(keypress))
def draw_board(self): """Draw the board. Only the board, to draw numbers draw_numbers it is used. """ self.c.setStrokeColor(options.get("pdf", "lines_colour")) if self.page_size[0] < self.page_size[1]: x = self.page_size[0] / 20 y = (self.page_size[1] - self.page_size[0] * 0.9) / 2 square_length = self.page_size[0] / (self.boardsize) * 0.9 else: y = self.page_size[1] / 20 x = (self.page_size[0] - self.page_size[1] * 0.9) / 2 square_length = self.page_size[1] / (self.boardsize) * 0.9 self.c.rect(x, y, self.page_size[0] * 0.9, self.page_size[0] * 0.9, fill=0) # vertical lines for i in xrange(self.boardsize): if i > 0 and i % self.cellsize[0] == 0: self.c.setLineWidth(2) else: self.c.setLineWidth(1) self.c.line(x + i * square_length, y, x + i * square_length, y + square_length * self.boardsize) # horizontal lines for i in xrange(self.boardsize): if i > 0 and i % self.cellsize[1] == 0: self.c.setLineWidth(2) else: self.c.setLineWidth(1) self.c.line(x, y + i * square_length, x + square_length * self.boardsize, y + i * square_length)
def __init__(self, parent, id=wx.ID_ANY, title="Options", size=wx.DefaultSize, pos=wx.DefaultPosition, style=wx.DEFAULT_DIALOG_STYLE): super (ConfigDialog, self).__init__(parent, id, title, pos, size, style) panel = wx.Panel(self) #======================================================================= # Config (main) items... #======================================================================= ht_pref = options.get('main-opts', 'htype') ht_choices = ["A - xxxxx", "H - xxxxx", "S - xxxxx", "P - xxxxx"] ht_box = self.ht_box = wx.RadioBox(panel, -1, "HT", choices=ht_choices, majorDimension=1) ht_box.SetStringSelection(ht_pref) view_choices = ['Txt', 'Gfx'] view_box = self.view_box = wx.RadioBox(panel, -1, "View", choices=view_choices, majorDimension=1) view_box.SetStringSelection(options.get('main-opts', 'view')) bkey_label = wx.StaticText(panel, -1, "Bkey") bkey_pref = options.get('main-opts', 'bkey') bkey_letters = list('ABCEFGIJKLMNOQRTUVWXYZ') bkey_choice = self.bkey_choice = wx.Choice(panel, -1, choices=bkey_letters) bkey_choice.SetStringSelection(bkey_pref) btype_label = wx.StaticText(panel, -1, "BK Type") btype_choices = ['Grid', 'Image', 'Hide'] btype_picker = self.btype_picker = wx.Choice(panel, -1, choices=btype_choices) btype_picker.SetStringSelection(options.get('main-opts', 'bk_type')) disable_pref = options.getboolean('main-opts', 'btn_disable') # logging.info(disable_pref) btn_disable = self.btn_disable = wx.CheckBox(panel, -1, "Disable Invalid Buttons") btn_disable.SetValue(disable_pref) btn_hint = wx.StaticText(panel, -1, "Lorem ipsum dolor sit amet amet lorem ipsum dolor sit ametamet lorem ipsum dolor sit amet.") btn_hint.Wrap(150) #======================================================================= # Create GBS, add items #======================================================================= cfg_gbs = wx.GridBagSizer(5, 5) cfg_gbs.Add(ht_box, (0, 0), (3, 2), wx.ALL | wx.EXPAND | wx.ALIGN_CENTER, 5) cfg_gbs.Add(view_box, (0, 2), (3, 2), wx.ALL | wx.EXPAND | wx.CENTER, 5) cfg_gbs.Add(bkey_label, (3, 2)) cfg_gbs.Add(bkey_choice, (3, 3)) cfg_gbs.Add(btype_label, (4, 2)) cfg_gbs.Add(btype_picker, (4, 3)) cfg_gbs.Add(btn_disable, (4, 0), (1, 2), wx.EXPAND | wx.ALL, 5) cfg_gbs.Add(btn_hint, (6, 0), (2, 2), wx.EXPAND | wx.ALL, 5) # Add standard OK/Cancel buttons using Standard Dialog Button sizer sdbs = wx.StdDialogButtonSizer() ok_button = wx.Button(panel, wx.ID_OK) cancel_button = wx.Button(panel, wx.ID_CANCEL) sdbs.AddButton(ok_button) sdbs.AddButton(cancel_button) sdbs.Realize() # Add dialog button set to bottom of GBS cfg_gbs.Add(sdbs, (8, 1), (1, 4), wx.ALIGN_RIGHT | wx.EXPAND | wx.ALL , 5) panel.SetSizerAndFit(cfg_gbs) self.SetClientSize(panel.GetSize())
def __init__(self, board, filename): """Save a board as PDF. Arguments: board -- the board filename -- the filename """ self.page_size = getattr(reportlab.lib.pagesizes, options.get("pdf", "page")) self.c = reportlab.pdfgen.canvas.Canvas(filename) self.draw_title() if isinstance(board, list) or isinstance(board, tuple): self.c.scale(0.5, 0.5) # third self.numbers = board[2].numbers self.filename = board[2].filename self.cellsize = board[2].cellsize self.boardsize = board[2].boardsize self.c.translate(0, 0) self.draw_filename() self.draw_board() self.draw_numbers() # fourth self.numbers = board[3].numbers self.filename = board[3].filename self.cellsize = board[3].cellsize self.boardsize = board[3].boardsize self.c.translate(self.page_size[0], 0) self.draw_filename() self.draw_board() self.draw_numbers() # first self.numbers = board[0].numbers self.filename = board[0].filename self.cellsize = board[0].cellsize self.boardsize = board[0].boardsize self.c.translate(- self.page_size[0], self.page_size[1] / 1.3) self.draw_filename() self.draw_board() self.draw_numbers() # second self.numbers = board[1].numbers self.filename = board[1].filename self.cellsize = board[1].cellsize self.boardsize = board[1].boardsize self.c.translate(self.page_size[0], 0) self.draw_filename() self.draw_board() self.draw_numbers() else: self.numbers = board.numbers self.filename = board.filename self.cellsize = board.cellsize self.boardsize = board.boardsize self.draw_filename() self.draw_board() self.draw_numbers() self.c.showPage() self.c.save()
import hashlib,random from PIL import Image import os,sys, time sys.path.append('../') from models.models import * from lib.time_format import friendly_time from web.contrib.template import render_jinja from config import options ADMIN_LIST=["*****@*****.**"] STATIC_FILE=options.get("static_file","") TEMP=options.get("temp","") STATIC_FILE_URL=options.get("static_file_url","") urls=( '/' ,'Allusers', '/login','Login', '/logout','Logout', '/user/(.*)/','People', '/item/(\d+)/','Subject', '/allusers','Allusers', '/allposts','Allposts', '/allitems','Allshares',
from api.good.good_get import GoodGet from api.need.need_add import NeedSubmit from api.openid import GetOpenidHandler from api.upload import UploadHandler from api.test import Test from api.author.author_register import AuthorRegister from api.author.author_login import AuthorLogin app = tornado.web.Application([ (r'/fps/getopenid', GetOpenidHandler), (r'/upload', UploadHandler), (r'/fps/good/submit', GoodSubmit), (r'/fps/good/getlist', GoodGetList), (r'/fps/good/get', GoodGet), (r'/fps/need/submit', NeedSubmit), (r'/fps/test', Test), (r'/fps/author/register', AuthorRegister), (r'/fps/author/login', AuthorLogin), ]) if __name__ == "__main__": server = HTTPServer(app) server.listen(options.get('port')) # 只在单进程中这样使用 tornado.ioloop.IOLoop.current().start()
# -*- coding: utf-8-*- from config import options from mongoengine import * from datetime import datetime Model=Document DB=options.get("DB") connect(DB) STATIC_FILE_URL=options.get("static_file_url") class User(Model): ID=IntField(min_value=101,required=True,unique=True) #note that ID=count+101 username = StringField(max_length=100, unique=True,required=True) email = StringField(max_length=50) #微博登录是没有密码的 没有邮箱的 password = StringField(max_length=100, required=True) avatar = StringField(max_length=400) avatar_big=StringField(max_length=400) #need to remove big website = StringField(max_length=400) #todo urlfield role = IntField(default=2) location=StringField(max_length=50) reputation = IntField(default=10) token = StringField(max_length=16) created = DateTimeField(default=datetime.now) last_login=DateTimeField(default=datetime.now) last_notify = DateTimeField(default=datetime.now) intro=StringField(max_length=300) followings_count=IntField(default=0) followed_count=IntField(default=0)
Created on Jun 27, 2012 @author: sharvey3 ''' import wx import random import gui import cards import strategy import config from config import options import logging logging.basicConfig(level=logging.INFO) htype = options.get('main-opts', 'htype') # Yeah... this sucks. There must be a better way of handling buttons play_ids = dict({1000: "H", 2000: "S", 3000: "D", 4000: "S"}) # More temporary ugliness... htypes = dict({'A - xxxxx': 'all', 'H - xxxxx': 'hard', 'S - xxxxx' : 'soft', 'P - xxxxx': 'split'}) chart = strategy.table() class mf(gui.MainFrame): def __init__(self, parent): gui.MainFrame.__init__(self, parent)
def auth_check(): auth_required = options.get('authRequired', True) if auth_required: verify_auth()
# -*- coding: utf-8-*- from mongoengine import * from datetime import datetime from config import options Model=Document DB=options.get("DB") connect(DB) class Share_items(Model): ID=IntField(min_value=1,required=True,unique=True) creatorID=IntField(required=True) itemID=IntField() #content=StringField(max_length=100) flag=IntField() #flag 备用,如果赋值则不显示或者推荐等 created = DateTimeField(default=datetime.now)
from flask_admin.contrib.sqla import ModelView from flask.ext.rbac import RBAC from flask_swagger import swagger from flask.ext.cors import CORS from config import db_config import os try: from config import options except ImportError: options = {} application = Flask(__name__) CORS(application) application.config.update(RBAC_USE_WHITE=options.get('rbacEnabled', True), ) # DB Connection Information application.config['SQLALCHEMY_DATABASE_URI'] = \ 'postgres://' + db_config['dbuser'] + ':' + \ db_config['dbpass'] + '@' + \ db_config['dbhost'] + '/' + \ db_config['dbname'] application.config.update(RBAC_USE_WHITE=options.get('rbacEnabled', True), ) from webapp.model import * # register logging before RBAC so logs work when rbac denies access from webapp import logs
def post(self): """ Create a new user --- tags: - users parameters: - in: body name: body schema: id: user_in required: - username - password properties: username: type: string description: username for user login password: type: string description: password for user login fname: type: string description: first name of user lname: type: string description: last name of user email: type: string description: email address of user responses: 201: description: User created schema: id: user_out 400: description: username taken schema: id: error properties: error: type: string description: description of error """ # celery test # rq = tasks.hello.apply_asyc(args=["Post User"]) # results = async_result.AsyncResult(str(rq)) # print results.get() un = request.json.get('username', 'guest') user = User.query.filter_by(username=un).first() pw = str(request.json.get('password', '')) if user is not None: return jsonify(error='Username Taken'), 400 if options.get('testEnabled', False): # less secure for testing - faster pw_hash = bcrypt.hashpw(pw, bcrypt.gensalt(4)) else: pw_hash = bcrypt.hashpw(pw, bcrypt.gensalt(14)) fname = request.json.get('fname', '') lname = request.json.get('lname', '') em = request.json.get('email', '') hash_id = hashlib.sha256(str(random.getrandbits(256))).hexdigest() user_guid = uuid.uuid4() team_id = request.json.get('team_id') u = User(username=un, email=em, password=pw_hash, secure_id=None, first_name=fname, last_name=lname, hash_id=hash_id, user_guid=user_guid, team_id=team_id) db.session.add(u) db.session.commit() # Building out user to push out user = User.query.filter_by(username=un).first() return jsonify(user=user.as_json()), 201
# -*- coding: utf-8 -*- import tornado.web import tornado.ioloop import tornado.httpserver from config import options class IndexView(tornado.web.RequestHandler): def get(self): self.write('oo') if __name__ == '__main__': # 装换命令行的参数,并保存到tornado.options.optrons app = tornado.web.Application([(r'/', IndexView)]) # app.listen(8000) # 手动创建服务器(手动一个http服务器对象) httpServer = tornado.httpserver.HTTPServer(app) # 监听端口 # httpServer.listen(8000) httpServer.bind(options.get('port')) # 默认是单进程的 # 参数为None或为负数开进程个数为启硬件cpu的核数 httpServer.start() tornado.ioloop.IOLoop.current().start() # -*- coding: utf-8 -*-
from flask.ext.rbac import RBAC from flask_swagger import swagger from flask.ext.cors import CORS from config import db_config import os try: from config import options except ImportError: options = {} application = Flask(__name__) CORS(application) application.config.update( RBAC_USE_WHITE=options.get('rbacEnabled', True), ) # DB Connection Information application.config['SQLALCHEMY_DATABASE_URI'] = \ 'postgres://' + db_config['dbuser'] + ':' + \ db_config['dbpass'] + '@' + \ db_config['dbhost'] + '/' + \ db_config['dbname'] application.config.update( RBAC_USE_WHITE=options.get('rbacEnabled', True), ) from webapp.model import *