<commit_before>import json
import os
import hashlib
from os import listdir
from os.path import isfile, join
#import subprocess

import cherrypy

#from jinja2 import Environment, FileSystemLoader

#basePATH = './'
#env = Environment(loader=FileSystemLoader(basePATH+'frontend'))
#indexTmpl = env.get_template('index.html')

userData = {}# {ID: {STATS}}

with open('stats.json', 'r') as f:
	userData = json.loads(f.read())

#print(userData)

def writeUserData():
	with open('stats.json', 'w') as f:
		f.write(json.dumps(userData))

class Mod:
	def __init__(self, filename):
		self.name = filename
		self.filename = filename
		self.author = ""
		file = open("./mods/"+filename, "r")
		self.content = file.read()
		m = hashlib.md5(self.content.encode("utf-8"))
		self.md5 = m.hexdigest()
		file.close()
		if os.path.exists("./mods/"+filename.replace(".py", ".json")):
			#json file avalible
			with open("./mods/"+filename.replace(".py", ".json"), "r") as jf:
				d = json.load(jf)
				if 'author' in d:
					self.author = d['author']
				if 'name' in d:
					self.name = d['name']

	def dict(self):
		return {'name': self.name, 'filename': self.filename,
				'author': self.author,
				'md5': self.md5, 'uniqueInstalls': self.numInstalled()}

	def getData(self):
		return self.content

	def numInstalled(self):
		num = 0
		for user, data in userData.items():
			if self.filename in data['installedMods']:
				num += 1
		return num

class Root:

	_cp_config = {
		'tools.sessions.on': True,
	}

	def __init__(self):
		print('rootInit')
		self.files = os.listdir("./mods")
		print(self.files)
		self.mods = []
		for file in self.files:
			if file.endswith(".py"):
				self.mods.append(Mod(file))
		self.hash2Mod = {mod.md5:mod for mod in self.mods}
		#self.filename2mod = {mod.filename:mod for mod in self.mods}

	@cherrypy.expose
	def getModList(self):
		return repr([m.dict() for m in self.mods]) # no json in BombSquad-Python

	@cherrypy.expose
	def getData(self, md5):
		if md5 in self.hash2Mod:
			return self.hash2Mod[md5].getData()
		return False

	@cherrypy.expose
	def submitStats(self, stats):
		print(stats)
		stats = eval(stats)
		if not 'uniqueID' in stats:
			print('no id in stats', stats)
			return
		userData[stats['uniqueID']] = stats
		writeUserData()

	@cherrypy.expose
	def index(self):
		return "top kek"#indexTmpl.render(loginname = cherrypy.request.remote.ip, serverstatus=self.server.status, log=self.server.console_log)

path = os.path.dirname(os.path.abspath(__file__))+"/"
cherrypy.engine.autoreload.files.add("mods/")

cherrypy.config.update({'server.socket_host': '0.0.0.0',
						'server.socket_port': 3666,
					 	'log.error_file': './error.log'})

cherrypy.tree.mount(Root(), '/')
cherrypy.engine.start()
cherrypy.engine.block()
<commit_msg>literal eval<commit_after>import json
import os
import hashlib
import ast # literal eval for the win
from os import listdir
from os.path import isfile, join
#import subprocess

import cherrypy

#from jinja2 import Environment, FileSystemLoader

#basePATH = './'
#env = Environment(loader=FileSystemLoader(basePATH+'frontend'))
#indexTmpl = env.get_template('index.html')

userData = {}# {ID: {STATS}}

with open('stats.json', 'r') as f:
	userData = json.loads(f.read())

#print(userData)

def writeUserData():
	with open('stats.json', 'w') as f:
		f.write(json.dumps(userData))

class Mod:
	def __init__(self, filename):
		self.name = filename
		self.filename = filename
		self.author = ""
		file = open("./mods/"+filename, "r")
		self.content = file.read()
		m = hashlib.md5(self.content.encode("utf-8"))
		self.md5 = m.hexdigest()
		file.close()
		if os.path.exists("./mods/"+filename.replace(".py", ".json")):
			#json file avalible
			with open("./mods/"+filename.replace(".py", ".json"), "r") as jf:
				d = json.load(jf)
				if 'author' in d:
					self.author = d['author']
				if 'name' in d:
					self.name = d['name']

	def dict(self):
		return {'name': self.name, 'filename': self.filename,
				'author': self.author,
				'md5': self.md5, 'uniqueInstalls': self.numInstalled()}

	def getData(self):
		return self.content

	def numInstalled(self):
		num = 0
		for user, data in userData.items():
			if self.filename in data['installedMods']:
				num += 1
		return num

class Root:

	_cp_config = {
		'tools.sessions.on': True,
	}

	def __init__(self):
		print('rootInit')
		self.files = os.listdir("./mods")
		print(self.files)
		self.mods = []
		for file in self.files:
			if file.endswith(".py"):
				self.mods.append(Mod(file))
		self.hash2Mod = {mod.md5:mod for mod in self.mods}
		#self.filename2mod = {mod.filename:mod for mod in self.mods}

	@cherrypy.expose
	def getModList(self):
		return repr([m.dict() for m in self.mods]) # no json in BombSquad-Python

	@cherrypy.expose
	def getData(self, md5):
		if md5 in self.hash2Mod:
			return self.hash2Mod[md5].getData()
		return False

	@cherrypy.expose
	def submitStats(self, stats):
		print(stats)
		stats = ast.literal_eval(stats)
		if not 'uniqueID' in stats:
			print('no id in stats', stats)
			return
		userData[stats['uniqueID']] = stats
		writeUserData()

	@cherrypy.expose
	def index(self):
		return "top kek"#indexTmpl.render(loginname = cherrypy.request.remote.ip, serverstatus=self.server.status, log=self.server.console_log)

path = os.path.dirname(os.path.abspath(__file__))+"/"
cherrypy.engine.autoreload.files.add("mods/")

cherrypy.config.update({'server.socket_host': '0.0.0.0',
						'server.socket_port': 3666,
					 	'log.error_file': './error.log'})

cherrypy.tree.mount(Root(), '/')
cherrypy.engine.start()
cherrypy.engine.block()
<|endoftext|>


<commit_before>from flask import Flask, request
from pprint import pprint
import re
import json
import ConfigParser
import urllib2
import network
import os
import subprocess
import socket

def bitbucket(json):
  ret = {}
  ret['url'] = json['canon_url'] + json['repository']['absolute_url']
  ret['raw'] = ret['url'] + 'raw/'
  ret['config'] = ret['raw'] + 'integralgit/config'
  ret['name'] = json['repository']['name']
  ret['commits'] = [{'message' : j['message'], 'branch': j['branch'], 'time': j['timestamp']} for j in json['commits']]

  return ret

def github(json):
  ret = {}
  ret['url'] = json['repository']['url']
  ret['raw'] = re.sub('github', 'raw.github', ret['url'], 1) + '/'
  ret['config'] =  ret['raw'] + 'integralgit/config'
  ret['name'] = json['repository']['name']
  ret['commits'] = []
  for j in json['commits']:
    d = {'message' : j['message'], 'time' : j['timestamp']}
    d['branch'] = re.sub(r'([^\/])$', r'\1', json['ref'])
    ret['commits'].append(d)

  return ret

def shellescape(s):
  return s.replace("\\", "\\\\").replace("'", "'\\''")

def log(s, level = 0):
  logfile.write(str(s))
  logfile.write("\n")
  logfile.flush()
  print s

sources = {
    ('131.103.20.165', 1) : bitbucket,
    ('131.103.20.166', 1) : bitbucket,
    ('204.232.175.64', 27) : github,
    ('192.30.252.0', 22) : github,
  }

app = Flask(__name__)
state = {}

logfile = open('integralgit.log', 'a')

log('Starting up...')

@app.route("/")
def hello():
  return "IntegralGit: continuous integration via GitHub"

@app.route("/<repo>")
def latest(repo):
  return str(state.get(repo, "I don't recognize that repo name. Try committing something to it?"))

@app.route("/update", methods=["POST"])
def update():
  # Prevent requests from hosts we don't recognize
  source = request.remote_addr
  log('source: ' + str(source))
  decoder = None
  for n, d in sources.iteritems():
    if network.isAddressInNetwork(source, *n):
      decoder = d
      break
  else:
    log('Update request from illegal ip ' + str(source))
    return "Unrecognized source IP"

  jd = json.JSONDecoder()
  payload = jd.decode(request.form['payload'])
  info = decoder(payload)
  log(info)
  repo = info['name']
  url = info['url']
  state[repo] = info

  try:
    getConfigs(info)
    gitPull(info)
  except Exception as e:
    # Skip running host script...lessens chance of RCE
    return str(e)

  runHostScript(info)

  return "Good job"

# Get host configuration file from the integralgit branch
def getConfigs(info):
  config_data = None
  log('Host config location: ' + str(info['config']))
  try:
    page = urllib2.urlopen(info['config'])
    config_data = page.read()
    page.close()
  except:
    log("Host Config not found, quitting.")
    raise Exception("Could not load host config")

  jd = json.JSONDecoder()
  info['config'] = jd.decode(config_data)
  info['hostconfig'] = getHostConfig(info)

# Get specific host configuration
# by applying a base config (if it exists),
# applying configs for hostgroups in alphabetical order,
# then applying host-specific configs.
def getHostConfig(info):
  hostname = socket.gethostname()

  # get base config
  config = info['config'].get('configs',{}).get('base',{})

  # get hostgroup configs
  for group, hosts in iter(sorted(info['config'].get('groups', {}).iteritems())):
    if hostname in hosts:
      config.update(info['config'].get('configs', {}).get(group, {}))

  # get host specific config
  config.update(info['config'].get('configs', {}).get(hostname, {}))

  return config

def gitPull(info):
# Build repo folder
  repoFolder = info['hostconfig']['location']
  if repoFolder is None:
    log("No location found for repository!")
    raise Exception("No location found!")

  log("Checking if " + repoFolder + " is a git repository...")

  # Check for folder
  if(os.path.isdir(repoFolder)):
    # Check for git repo
    result = subprocess.call(['git', 'rev-parse'], cwd=repoFolder)
    if(result != 0):
      log("Folder exists but is not a git repository. Fix your shit.")
      raise Exception("Not a git repository")

    branch = info['hostconfig'].get('branch', 'master')
    remote = info['hostconfig'].get('remote', 'origin')

    # If local branch exists, checkout and pull
    result = subprocess.call(['git', 'show-branch', branch], cwd=repoFolder)
    if result == 0:
      log("Checking out branch...")
      result = subprocess.call(['git', 'checkout', branch], cwd=repoFolder)
      log("Checkout result: " + str(result))
      log("Doing git pull...")
      result = subprocess.call(['git', 'pull'], cwd=repoFolder)
      log("Pull result: " + str(result))

    # Local branch does not exist, fetch and track remote branch
    else:
      log("Local branch does not exist...")
      log("Doing git fetch...")
      result = subprocess.call(['git', 'fetch'], cwd=repoFolder)
      log("Fetch result: " + str(result))
      log("Checking out branch...")
      result = suprocess.call(['git', 'checkout', '--track', remote + '/' + branch], cwd=repoFolder)
      log("Checkout result: " + str(result))

  # Repo does not exist at all, clone and checkout
  else:
    log("Folder does not exist; doing git clone...")
    result = subprocess.call(['git', 'clone', info['url']], cwd=os.path.basename(repoFolder))
    log("Clone result: " + str(result))
    log("Checking out local branch...")
    result = subprocess.call(['git', 'checkout', '-b', branch, remote + '/' + branch], cwd=repoFolder)
    log("Checkout result: " + str(result))

def runHostScript(info):
  script_name = info['hostconfig']['script']
  repo_folder = info['hostconfig']['location']

  if(script_name is not None):
    script_path = os.path.join(repo_folder, script_name)
    log("Got script file for host: " + str(script_path))

    log("Running script...")
    subprocess.call(['chmod', '+x', script_path])
    result = subprocess.call([script_path], cwd = repo_folder)
    log("Script result: " + str(result))

#TODO: fix
def parseConfig(filename):
  config = ConfigParser.SafeConfigParser()
  config.read(filename)

  for section in config.sections():
    lastCommit[section] = "No recorded commits!"

if __name__=="__main__":
  app.run(host="0.0.0.0", debug=True)

<commit_msg>Removing spurious variables<commit_after>from flask import Flask, request
from pprint import pprint
import re
import json
import ConfigParser
import urllib2
import network
import os
import subprocess
import socket

def bitbucket(json):
  ret = {}
  ret['url'] = json['canon_url'] + json['repository']['absolute_url'][0:-1] # cut off trailing slash
  ret['clone'] = re.sub('bitbucket', json['repository']['owner'] + '@bitbucket', 1) + '.git'
  ret['raw'] = ret['url'] + '/raw'
  ret['config'] = ret['raw'] + '/integralgit/config'
  ret['name'] = json['repository']['name']
  ret['commits'] = [{'message' : j['message'], 'branch': j['branch'], 'time': j['timestamp']} for j in json['commits']]

  return ret

def github(json):
  ret = {}
  ret['url'] = json['repository']['url']
  ret['clone'] = ret['url'] + '.git'
  ret['raw'] = re.sub('github', 'raw.github', ret['url'], 1)
  ret['config'] =  ret['raw'] + '/integralgit/config'
  ret['name'] = json['repository']['name']
  ret['commits'] = []
  for j in json['commits']:
    d = {'message' : j['message'], 'time' : j['timestamp']}
    d['branch'] = re.sub(r'([^\/])$', r'\1', json['ref'])
    ret['commits'].append(d)

  return ret

def shellescape(s):
  return s.replace("\\", "\\\\").replace("'", "'\\''")

def log(s, level = 0):
  logfile.write(str(s))
  logfile.write("\n")
  logfile.flush()
  print s

sources = {
    ('131.103.20.165', 1) : bitbucket,
    ('131.103.20.166', 1) : bitbucket,
    ('204.232.175.64', 27) : github,
    ('192.30.252.0', 22) : github,
  }

app = Flask(__name__)
state = {}

logfile = open('integralgit.log', 'a')

log('Starting up...')

@app.route("/")
def hello():
  return "IntegralGit: continuous integration via GitHub"

@app.route("/<repo>")
def latest(repo):
  return str(state.get(repo, "I don't recognize that repo name. Try committing something to it?"))

@app.route("/update", methods=["POST"])
def update():
  # Prevent requests from hosts we don't recognize
  source = request.remote_addr
  log('source: ' + str(source))
  decoder = None
  for n, d in sources.iteritems():
    if network.isAddressInNetwork(source, *n):
      decoder = d
      break
  else:
    log('Update request from illegal ip ' + str(source))
    return "Unrecognized source IP"

  jd = json.JSONDecoder()
  payload = jd.decode(request.form['payload'])
  info = decoder(payload)
  log(info)
  state[repo] = info

  try:
    getConfigs(info)
    gitPull(info)
  except Exception as e:
    # Skip running host script...lessens chance of RCE
    return str(e)

  runHostScript(info)

  return "Good job"

# Get host configuration file from the integralgit branch
def getConfigs(info):
  config_data = None
  log('Host config location: ' + str(info['config']))
  try:
    page = urllib2.urlopen(info['config'])
    config_data = page.read()
    page.close()
  except:
    log("Host Config not found, quitting.")
    raise Exception("Could not load host config")

  jd = json.JSONDecoder()
  info['config'] = jd.decode(config_data)
  info['hostconfig'] = getHostConfig(info)

# Get specific host configuration
# by applying a base config (if it exists),
# applying configs for hostgroups in alphabetical order,
# then applying host-specific configs.
def getHostConfig(info):
  hostname = socket.gethostname()

  # get base config
  config = info['config'].get('configs',{}).get('base',{})

  # get hostgroup configs
  for group, hosts in iter(sorted(info['config'].get('groups', {}).iteritems())):
    if hostname in hosts:
      config.update(info['config'].get('configs', {}).get(group, {}))

  # get host specific config
  config.update(info['config'].get('configs', {}).get(hostname, {}))

  return config

def gitPull(info):
# Build repo folder
  repoFolder = info['hostconfig']['location']
  if repoFolder is None:
    log("No location found for repository!")
    raise Exception("No location found!")

  log("Checking if " + repoFolder + " is a git repository...")

  # Check for folder
  if(os.path.isdir(repoFolder)):
    # Check for git repo
    result = subprocess.call(['git', 'rev-parse'], cwd=repoFolder)
    if(result != 0):
      log("Folder exists but is not a git repository. Fix your shit.")
      raise Exception("Not a git repository")

    branch = info['hostconfig'].get('branch', 'master')
    remote = info['hostconfig'].get('remote', 'origin')

    # If local branch exists, checkout and pull
    result = subprocess.call(['git', 'show-branch', branch], cwd=repoFolder)
    if result == 0:
      log("Checking out branch...")
      result = subprocess.call(['git', 'checkout', branch], cwd=repoFolder)
      log("Checkout result: " + str(result))
      log("Doing git pull...")
      result = subprocess.call(['git', 'pull'], cwd=repoFolder)
      log("Pull result: " + str(result))

    # Local branch does not exist, fetch and track remote branch
    else:
      log("Local branch does not exist...")
      log("Doing git fetch...")
      result = subprocess.call(['git', 'fetch'], cwd=repoFolder)
      log("Fetch result: " + str(result))
      log("Checking out branch...")
      result = suprocess.call(['git', 'checkout', '--track', remote + '/' + branch], cwd=repoFolder)
      log("Checkout result: " + str(result))

  # Repo does not exist at all, clone and checkout
  else:
    log("Folder does not exist; doing git clone...")
    result = subprocess.call(['git', 'clone', info['clone']], cwd=os.path.basename(repoFolder))
    log("Clone result: " + str(result))
    log("Checking out local branch...")
    result = subprocess.call(['git', 'checkout', '-b', branch, remote + '/' + branch], cwd=repoFolder)
    log("Checkout result: " + str(result))

def runHostScript(info):
  script_name = info['hostconfig']['script']
  repo_folder = info['hostconfig']['location']

  if(script_name is not None):
    script_path = os.path.join(repo_folder, script_name)
    log("Got script file for host: " + str(script_path))

    log("Running script...")
    subprocess.call(['chmod', '+x', script_path])
    result = subprocess.call([script_path], cwd = repo_folder)
    log("Script result: " + str(result))

#TODO: fix
def parseConfig(filename):
  config = ConfigParser.SafeConfigParser()
  config.read(filename)

  for section in config.sections():
    lastCommit[section] = "No recorded commits!"

if __name__=="__main__":
  app.run(host="0.0.0.0", debug=True)

<|endoftext|>


<commit_before>"""
Docker Compose UI, flask based application
"""

from flask import Flask, jsonify, request
from scripts.bridge import ps_, get_project, get_container_from_id, get_yml_path
from scripts.find_yml import find_yml_files
from scripts.requires_auth import requires_auth, authentication_enabled, \
  disable_authentication, set_authentication
from json import loads
import logging
import requests
import docker
import os
import traceback

# Flask Application
API_V1 = '/api/v1/'
YML_PATH = '/opt/docker-compose-projects'
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__, static_url_path='')

# load project definitions
projects = find_yml_files(YML_PATH)

logging.debug(projects)

def get_project_with_name(name):
    """
    get docker compose project given a project name
    """
    path = projects[name]
    return get_project(path)

# REST endpoints

@app.route(API_V1 + "projects", methods=['GET'])
def list_projects():
    """
    List docker compose projects
    """
    global projects
    projects = find_yml_files(YML_PATH)
    return jsonify(projects=projects)

@app.route(API_V1 + "projects/<name>", methods=['GET'])
def project_containers(name):
    """
    get project details
    """
    project = get_project_with_name(name)
    containers = ps_(project)
    return jsonify(containers=containers)

@app.route(API_V1 + "projects/yml/<name>", methods=['GET'])
def project_yml(name):
    """
    get yml content
    """
    path = get_yml_path(projects[name])
    with open(path) as data_file:
        return jsonify(yml=data_file.read())

@app.route(API_V1 + "projects/<name>/<container_id>", methods=['GET'])
def project_container(name, container_id):
    """
    get container details
    """
    project = get_project_with_name(name)
    container = get_container_from_id(project.client, container_id)
    return jsonify(
        id=container.id,
        short_id=container.short_id,
        human_readable_command=container.human_readable_command,
        name=container.name,
        name_without_project=container.name_without_project,
        number=container.number,
        ports=container.ports,
        ip=container.get('NetworkSettings.IPAddress'),
        labels=container.labels,
        log_config=container.log_config,
        image=container.image,
        links=container.links(),
        environment=container.environment
        )

@app.route(API_V1 + "projects/<name>", methods=['DELETE'])
@requires_auth
def kill(name):
    """
    docker-compose kill
    """
    get_project_with_name(name).kill()
    return jsonify(command='kill')

@app.route(API_V1 + "projects", methods=['PUT'])
@requires_auth
def pull():
    """
    docker-compose pull
    """
    name = loads(request.data)["id"]
    get_project_with_name(name).pull()
    return jsonify(command='pull')

@app.route(API_V1 + "services", methods=['PUT'])
@requires_auth
def scale():
    """
    docker-compose scale
    """
    req = loads(request.data)
    name = req['project']
    service_name = req['service']
    num = req['num']

    project = get_project_with_name(name)
    project.get_service(service_name).scale(desired_num=int(num))
    return jsonify(command='scale')

@app.route(API_V1 + "projects", methods=['POST'])
@requires_auth
def up_():
    """
    docker-compose up
    """
    name = loads(request.data)["id"]
    containers = get_project_with_name(name).up()
    logging.debug(containers)
    return jsonify(
        {
            'command': 'up',
            'containers': map(lambda container: container.name, containers)
        })

@app.route(API_V1 + "build", methods=['POST'])
@requires_auth
def build():
    """
    docker-compose build
    """
    name = loads(request.data)["id"]
    get_project_with_name(name).build()
    return jsonify(command='build')

@app.route(API_V1 + "create", methods=['POST'])
@requires_auth
def create():
    """
    create new project
    """
    data = loads(request.data)

    directory = YML_PATH + '/' + data["name"]
    os.makedirs(directory)

    file_path = directory + "/docker-compose.yml"
    out_file = open(file_path, "w")
    out_file.write(data["yml"])
    out_file.close()

    return jsonify(path=file_path)

@app.route(API_V1 + "search", methods=['POST'])
def search():
    """
    search for a project on www.composeregistry.com
    """
    query = loads(request.data)['query']
    response = requests.get('http://www.composeregistry.com/api/v1/search', \
        params={'query': query}, headers={'x-key': 'default'})
    if response.status_code == 200:
        return jsonify(response.json())
    else:
        result = jsonify(response.json())
        result.status_code = response.status_code
        return result

@app.route(API_V1 + "yml", methods=['POST'])
def yml():
    """
    get yml content from www.composeregistry.com
    """
    item_id = loads(request.data)['id']
    response = requests.get('http://www.composeregistry.com/api/v1/yml', \
        params={'id': item_id}, headers={'x-key': 'default'})
    return jsonify(response.json())

@app.route(API_V1 + "start", methods=['POST'])
@requires_auth
def start():
    """
    docker-compose start
    """
    name = loads(request.data)["id"]
    get_project_with_name(name).start()
    return jsonify(command='start')

@app.route(API_V1 + "stop", methods=['POST'])
@requires_auth
def stop():
    """
    docker-compose stop
    """
    name = loads(request.data)["id"]
    get_project_with_name(name).stop()
    return jsonify(command='stop')

@app.route(API_V1 + "logs/<name>", defaults={'limit': "all"}, methods=['GET'])
@app.route(API_V1 + "logs/<name>/<int:limit>", methods=['GET'])
def logs(name, limit):
    """
    docker-compose logs
    """
    lines = {}
    for k in get_project_with_name(name).containers(stopped=True):
        lines[k.name] = k.logs(timestamps=True, tail=limit).split('\n')

    return jsonify(logs=lines)

@app.route(API_V1 + "logs/<name>/<container_id>", defaults={'limit': "all"}, methods=['GET'])
@app.route(API_V1 + "logs/<name>/<container_id>/<int:limit>", methods=['GET'])
def container_logs(name, container_id, limit):
    """
    docker-compose logs of a specific container
    """
    project = get_project_with_name(name)
    container = get_container_from_id(project.client, container_id)
    lines = container.logs(timestamps=True, tail=limit).split('\n')
    return jsonify(logs=lines)

@app.route(API_V1 + "host", methods=['GET'])
def host():
    """
    docker host info
    """
    host_value = os.getenv('DOCKER_HOST')

    return jsonify(host=host_value)

@app.route(API_V1 + "host", methods=['POST'])
@requires_auth
def set_host():
    """
    set docker host
    """
    new_host = loads(request.data)["id"]
    if new_host is None:
        if os.environ.has_key('DOCKER_HOST'):
            del os.environ['DOCKER_HOST']
        return jsonify()
    else:
        os.environ['DOCKER_HOST'] = new_host
        return jsonify(host=new_host)

@app.route(API_V1 + "authentication", methods=['GET'])
def authentication():
    """
    check if basic authentication is enabled
    """
    return jsonify(enabled=authentication_enabled())

@app.route(API_V1 + "authentication", methods=['DELETE'])
@requires_auth
def disable_basic_authentication():
    """
    disable basic authentication
    """
    disable_authentication()
    return jsonify(enabled=False)

@app.route(API_V1 + "authentication", methods=['POST'])
@requires_auth
def enable_basic_authentication():
    """
    set up basic authentication
    """
    data = loads(request.data)
    set_authentication(data["username"], data["password"])
    return jsonify(enabled=True)

# static resources
@app.route("/")
def index():
    """
    index.html
    """
    return app.send_static_file('index.html')

## basic exception handling

@app.errorhandler(requests.exceptions.ConnectionError)
def handle_connection_error(err):
    """
    connection exception handler
    """
    return 'docker host not found: ' + str(err), 500

@app.errorhandler(docker.errors.DockerException)
def handle_docker_error(err):
    """
    docker exception handler
    """
    return 'docker exception: ' + str(err), 500

@app.errorhandler(Exception)
def handle_generic_error(err):
    """
    default exception handler
    """
    traceback.print_exc()
    return 'error: ' + str(err), 500

# run app
if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, threaded=True)
<commit_msg>fix Docker compose run command #8<commit_after>"""
Docker Compose UI, flask based application
"""

from flask import Flask, jsonify, request
from scripts.bridge import ps_, get_project, get_container_from_id, get_yml_path
from scripts.find_yml import find_yml_files
from scripts.requires_auth import requires_auth, authentication_enabled, \
  disable_authentication, set_authentication
from json import loads
import logging
import requests
import docker
import os
import traceback

# Flask Application
API_V1 = '/api/v1/'
YML_PATH = '/opt/docker-compose-projects'
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__, static_url_path='')

# load project definitions
projects = find_yml_files(YML_PATH)

logging.debug(projects)

def get_project_with_name(name):
    """
    get docker compose project given a project name
    """
    path = projects[name]
    return get_project(path)

# REST endpoints

@app.route(API_V1 + "projects", methods=['GET'])
def list_projects():
    """
    List docker compose projects
    """
    global projects
    projects = find_yml_files(YML_PATH)
    return jsonify(projects=projects)

@app.route(API_V1 + "projects/<name>", methods=['GET'])
def project_containers(name):
    """
    get project details
    """
    project = get_project_with_name(name)
    containers = ps_(project)
    return jsonify(containers=containers)

@app.route(API_V1 + "projects/<project>/<service_id>", methods=['POST'])
@requires_auth
def run_service(project, service_id):
    """
    docker-compose run service
    """
    json = loads(request.data)
    command = json["command"] if 'command' in json else None
    service = get_project_with_name(project).get_service(service_id)

    container_options = {
        'command': command if command else service.options.get('command')
    }

    service \
        .create_container(one_off=True, **container_options) \
        .start()

    return jsonify(command='run %s/%s' % (project, service_id))

@app.route(API_V1 + "projects/yml/<name>", methods=['GET'])
def project_yml(name):
    """
    get yml content
    """
    path = get_yml_path(projects[name])
    with open(path) as data_file:
        return jsonify(yml=data_file.read())

@app.route(API_V1 + "projects/<name>/<container_id>", methods=['GET'])
def project_container(name, container_id):
    """
    get container details
    """
    project = get_project_with_name(name)
    container = get_container_from_id(project.client, container_id)
    return jsonify(
        id=container.id,
        short_id=container.short_id,
        human_readable_command=container.human_readable_command,
        name=container.name,
        name_without_project=container.name_without_project,
        number=container.number,
        ports=container.ports,
        ip=container.get('NetworkSettings.IPAddress'),
        labels=container.labels,
        log_config=container.log_config,
        image=container.image,
        links=container.links(),
        environment=container.environment
        )

@app.route(API_V1 + "projects/<name>", methods=['DELETE'])
@requires_auth
def kill(name):
    """
    docker-compose kill
    """
    get_project_with_name(name).kill()
    return jsonify(command='kill')

@app.route(API_V1 + "projects", methods=['PUT'])
@requires_auth
def pull():
    """
    docker-compose pull
    """
    name = loads(request.data)["id"]
    get_project_with_name(name).pull()
    return jsonify(command='pull')

@app.route(API_V1 + "services", methods=['PUT'])
@requires_auth
def scale():
    """
    docker-compose scale
    """
    req = loads(request.data)
    name = req['project']
    service_name = req['service']
    num = req['num']

    project = get_project_with_name(name)
    project.get_service(service_name).scale(desired_num=int(num))
    return jsonify(command='scale')

@app.route(API_V1 + "projects", methods=['POST'])
@requires_auth
def up_():
    """
    docker-compose up
    """
    name = loads(request.data)["id"]
    containers = get_project_with_name(name).up()
    logging.debug(containers)
    return jsonify(
        {
            'command': 'up',
            'containers': map(lambda container: container.name, containers)
        })

@app.route(API_V1 + "build", methods=['POST'])
@requires_auth
def build():
    """
    docker-compose build
    """
    name = loads(request.data)["id"]
    get_project_with_name(name).build()
    return jsonify(command='build')

@app.route(API_V1 + "create", methods=['POST'])
@requires_auth
def create():
    """
    create new project
    """
    data = loads(request.data)

    directory = YML_PATH + '/' + data["name"]
    os.makedirs(directory)

    file_path = directory + "/docker-compose.yml"
    out_file = open(file_path, "w")
    out_file.write(data["yml"])
    out_file.close()

    return jsonify(path=file_path)

@app.route(API_V1 + "search", methods=['POST'])
def search():
    """
    search for a project on www.composeregistry.com
    """
    query = loads(request.data)['query']
    response = requests.get('http://www.composeregistry.com/api/v1/search', \
        params={'query': query}, headers={'x-key': 'default'})
    if response.status_code == 200:
        return jsonify(response.json())
    else:
        result = jsonify(response.json())
        result.status_code = response.status_code
        return result

@app.route(API_V1 + "yml", methods=['POST'])
def yml():
    """
    get yml content from www.composeregistry.com
    """
    item_id = loads(request.data)['id']
    response = requests.get('http://www.composeregistry.com/api/v1/yml', \
        params={'id': item_id}, headers={'x-key': 'default'})
    return jsonify(response.json())

@app.route(API_V1 + "start", methods=['POST'])
@requires_auth
def start():
    """
    docker-compose start
    """
    name = loads(request.data)["id"]
    get_project_with_name(name).start()
    return jsonify(command='start')

@app.route(API_V1 + "stop", methods=['POST'])
@requires_auth
def stop():
    """
    docker-compose stop
    """
    name = loads(request.data)["id"]
    get_project_with_name(name).stop()
    return jsonify(command='stop')

@app.route(API_V1 + "logs/<name>", defaults={'limit': "all"}, methods=['GET'])
@app.route(API_V1 + "logs/<name>/<int:limit>", methods=['GET'])
def logs(name, limit):
    """
    docker-compose logs
    """
    lines = {}
    for k in get_project_with_name(name).containers(stopped=True):
        lines[k.name] = k.logs(timestamps=True, tail=limit).split('\n')

    return jsonify(logs=lines)

@app.route(API_V1 + "logs/<name>/<container_id>", defaults={'limit': "all"}, methods=['GET'])
@app.route(API_V1 + "logs/<name>/<container_id>/<int:limit>", methods=['GET'])
def container_logs(name, container_id, limit):
    """
    docker-compose logs of a specific container
    """
    project = get_project_with_name(name)
    container = get_container_from_id(project.client, container_id)
    lines = container.logs(timestamps=True, tail=limit).split('\n')
    return jsonify(logs=lines)

@app.route(API_V1 + "host", methods=['GET'])
def host():
    """
    docker host info
    """
    host_value = os.getenv('DOCKER_HOST')

    return jsonify(host=host_value)

@app.route(API_V1 + "host", methods=['POST'])
@requires_auth
def set_host():
    """
    set docker host
    """
    new_host = loads(request.data)["id"]
    if new_host is None:
        if os.environ.has_key('DOCKER_HOST'):
            del os.environ['DOCKER_HOST']
        return jsonify()
    else:
        os.environ['DOCKER_HOST'] = new_host
        return jsonify(host=new_host)

@app.route(API_V1 + "authentication", methods=['GET'])
def authentication():
    """
    check if basic authentication is enabled
    """
    return jsonify(enabled=authentication_enabled())

@app.route(API_V1 + "authentication", methods=['DELETE'])
@requires_auth
def disable_basic_authentication():
    """
    disable basic authentication
    """
    disable_authentication()
    return jsonify(enabled=False)

@app.route(API_V1 + "authentication", methods=['POST'])
@requires_auth
def enable_basic_authentication():
    """
    set up basic authentication
    """
    data = loads(request.data)
    set_authentication(data["username"], data["password"])
    return jsonify(enabled=True)

# static resources
@app.route("/")
def index():
    """
    index.html
    """
    return app.send_static_file('index.html')

## basic exception handling

@app.errorhandler(requests.exceptions.ConnectionError)
def handle_connection_error(err):
    """
    connection exception handler
    """
    return 'docker host not found: ' + str(err), 500

@app.errorhandler(docker.errors.DockerException)
def handle_docker_error(err):
    """
    docker exception handler
    """
    return 'docker exception: ' + str(err), 500

@app.errorhandler(Exception)
def handle_generic_error(err):
    """
    default exception handler
    """
    traceback.print_exc()
    return 'error: ' + str(err), 500

# run app
if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, threaded=True)
<|endoftext|>


<commit_before>#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
#  file, You can obtain one at http://mozilla.org/MPL/2.0/.

# Version: 0.0.1

# TODO: Change to accept three and only three precepts per student

def inp(question):
	return input(question + " ")

def sort_preceptorials():
	print('Instructions: Follow the prompts. When prompted for single letter answers, "y" is "yes", "n" is "no", "c" is "cancel" (cancel the current operation rather than just the current iteration), and "v" is view, as in view all responses to the current operation. Type ^d (control + d) at any time to exit the program.')
	student_preferences = {} # Key: Student name, value: list of tuples of preceptorials and favorite status.
	PRECEPT_MAX = 12;
	PRECEPT_MIN = 3;
	students = [] # Student name
	""" TODO: do this
	# Fill out students
	preceptorials = []
	# Fill out preceptorials
	"""
	# Fill out student_preferences.
	while True:
		curr_student = inp("Enter a student name.")
		curr_reqs = []
		for i in range(3):
			curr_req = inp("Enter a requested preceptorial.")
			for req in curr_reqs.keys() if curr_reqs else range(1):
				try:
					if(curr_reqs[req][1]):
						req_preferred = False
						break;
					else:
						req_preferred = inp("Is this request preferred? (y/n)") == "y" # This will be True or False
				except IndexError:
					req_preferred = inp("Is this request preferred? (y/n)") == "y"
			print("You entered a {:s}preferred preceptorial \"{:s}\".".format("non-" if not req_preferred else "", curr_req))
			correct = inp("Is this correct? (y/n)")
			if(correct == "n"):
				continue
			curr_reqs.append((curr_req, req_preferred))
		view_reqs = curr_student + ":\n"
		view_reqs += "*" * 20 + "\n"
		for value in curr_reqs:
			view_reqs += value[0] + "- " + ("non-" if not value[1] else "") + "preferred\n"
		view_reqs += "*" * 20
		print(view_reqs)
		correct = inp("Is this correct? (y/n)")
		if(not correct == "y"):
			confirm = inp("Are you sure you want to cancel " + curr_student + "? (y/n)")
			if(confirm == y):
				print("Student canceled.")
		# students.append(curr_student) # deprecated
		student_preferences[curr_student] = curr_reqs
		more_students = inp("You currently have entered {:d} students. Would you like to enter more? (y/n/c/v)".format(len(student_preferences)))
		if(more_students == "v"):
			view_students = ("*" * 20 + "\n") * 2 + "\n"
			for key, values in student_preferences.items():
				view_students += key + ":\n"
				for value in values:
					view_students += value[0] + "- " + ("non-" if value[1] == 0 else "") + "preferred\n"
				view_students += "\n" + "*" * 20 + "\n" + ("\n" if value != values[-1] else "")
			view_students += ("*" * 20 + "\n") + "\n"
			print(view_students)
			more_students = inp("You currently have entered {:d} students. Would you like to enter more? (y/n/c)".format(len(student_preferences)))
		if(more_students == "c"):
			confirm = inp("Just to confirm, you want to clear all students? (y/n)")
			if(confirm == "y"):
				student_preferences = {}
				# students = []
				print("Students cleared.")
				continue
			more_students = inp("You currently have entered {:d} students. Would you like to enter more? (y/n)".format(len(student_preferences)))
		if(more_students == "n"):
			break
	preceptorial_students = {} # Key: preceptorials, value: list of students.
	# Step 1: Put all students into their preferred preceptorials.
<commit_msg>All code not needed. Using database not input<commit_after>#  This Source Code Form is subject to the terms of the Mozilla Public
#  License, v. 2.0. If a copy of the MPL was not distributed with this
#  file, You can obtain one at http://mozilla.org/MPL/2.0/.

# Version: 0.0.1

# TODO: Change to accept three and only three precepts per student

"""def inp(question):
	return input(question + " ")

def sort_preceptorials():
	print('Instructions: Follow the prompts. When prompted for single letter answers, "y" is "yes", "n" is "no", "c" is "cancel" (cancel the current operation rather than just the current iteration), and "v" is view, as in view all responses to the current operation. Type ^d (control + d) at any time to exit the program.')
	student_preferences = {} # Key: Student name, value: list of tuples of preceptorials and favorite status.
	PRECEPT_MAX = 12;
	PRECEPT_MIN = 3;
	students = [] # Student name
	""TODO: do this
	# Fill out students
	preceptorials = []
	# Fill out preceptorials
	""
	# Fill out student_preferences.
	while True:
		curr_student = inp("Enter a student name.")
		curr_reqs = []
		for i in range(3):
			curr_req = inp("Enter a requested preceptorial.")
			for req in curr_reqs.keys() if curr_reqs else range(1):
				try:
					if(curr_reqs[req][1]):
						req_preferred = False
						break;
					else:
						req_preferred = inp("Is this request preferred? (y/n)") == "y" # This will be True or False
				except IndexError:
					req_preferred = inp("Is this request preferred? (y/n)") == "y"
			print("You entered a {:s}preferred preceptorial \"{:s}\".".format("non-" if not req_preferred else "", curr_req))
			correct = inp("Is this correct? (y/n)")
			if(correct == "n"):
				continue
			curr_reqs.append((curr_req, req_preferred))
		view_reqs = curr_student + ":\n"
		view_reqs += "*" * 20 + "\n"
		for value in curr_reqs:
			view_reqs += value[0] + "- " + ("non-" if not value[1] else "") + "preferred\n"
		view_reqs += "*" * 20
		print(view_reqs)
		correct = inp("Is this correct? (y/n)")
		if(not correct == "y"):
			confirm = inp("Are you sure you want to cancel " + curr_student + "? (y/n)")
			if(confirm == y):
				print("Student canceled.")
		# students.append(curr_student) # deprecated
		student_preferences[curr_student] = curr_reqs
		more_students = inp("You currently have entered {:d} students. Would you like to enter more? (y/n/c/v)".format(len(student_preferences)))
		if(more_students == "v"):
			view_students = ("*" * 20 + "\n") * 2 + "\n"
			for key, values in student_preferences.items():
				view_students += key + ":\n"
				for value in values:
					view_students += value[0] + "- " + ("non-" if value[1] == 0 else "") + "preferred\n"
				view_students += "\n" + "*" * 20 + "\n" + ("\n" if value != values[-1] else "")
			view_students += ("*" * 20 + "\n") + "\n"
			print(view_students)
			more_students = inp("You currently have entered {:d} students. Would you like to enter more? (y/n/c)".format(len(student_preferences)))
		if(more_students == "c"):
			confirm = inp("Just to confirm, you want to clear all students? (y/n)")
			if(confirm == "y"):
				student_preferences = {}
				# students = []
				print("Students cleared.")
				continue
			more_students = inp("You currently have entered {:d} students. Would you like to enter more? (y/n)".format(len(student_preferences)))
		if(more_students == "n"):
			break
	preceptorial_students = {} # Key: preceptorials, value: list of students.
	# Step 1: Put all students into their preferred preceptorials."""

<|endoftext|>


<commit_before>from collections import namedtuple
from math import copysign
import cwiid
import time

import board
import wiimote

def speed_calculator(x0, x1, x2, y0, y1, y2):
    """Function is a ramp between x0 and x1, then continuous plateau between x1 and x2.
    Ramp goes from y1 to y2, plateau at y2.
    Else is y0.
    """
    a = (y2 - y1) * 1. / (x1 - x0)
    b = y2 - a * x1

    def _angle_to_speed(x):
        if x1 <= x <= x2:
            return y2
        elif x0 < x < x1:
            return a * x + b
        else:
            return y0
    return _angle_to_speed

acc_to_speed = speed_calculator(
    97,
    117,
    125,
    0,
    20,
    50
)
acc_to_rotation_left = speed_calculator(
    100,
    120,
    160,
    0,
    -1,
    1
)
acc_to_rotation_right = speed_calculator(
    -151,
    -130,
    -100,
    0,
    -1,
    1
)

class Controller(object):

    def __init__(self):
        self.pwm = board.L298N()
        self.wiimote = wiimote.WiimoteController()

    def run(self):
        self.wiimote.connect()
        self.pwm.setup()

        try:
            while True:
                if self.wiimote.is_btn_a_pressed():
                    acc_x, acc_y, acc_z = self.wiimote.read_acc()
                    forward = acc_to_speed(acc_y)
                    left_fact = acc_to_rotation_left(acc_x)
                    right_fact = acc_to_rotation_right(-acc_x)
                    left = int(left_fact * forward)
                    right = int(right_fact * forward)
                    self.pwm.set_duty_a(left)
                    self.pwm.set_duty_b(right)
                time.sleep(0.05)
        except Exception:
            self.pwm.cleanup()
            print "Interrupted. Good bye."

if __name__ == "__main__":
    controller = Controller()
    controller.run()
<commit_msg>except Exception became finally<commit_after>from collections import namedtuple
from math import copysign
import cwiid
import time

import board
import wiimote

def speed_calculator(x0, x1, x2, y0, y1, y2):
    """Function is a ramp between x0 and x1, then continuous plateau between x1 and x2.
    Ramp goes from y1 to y2, plateau at y2.
    Else is y0.
    """
    a = (y2 - y1) * 1. / (x1 - x0)
    b = y2 - a * x1

    def _angle_to_speed(x):
        if x1 <= x <= x2:
            return y2
        elif x0 < x < x1:
            return a * x + b
        else:
            return y0
    return _angle_to_speed

acc_to_speed = speed_calculator(
    97,
    117,
    125,
    0,
    20,
    50
)
acc_to_rotation_left = speed_calculator(
    100,
    120,
    160,
    0,
    -1,
    1
)
acc_to_rotation_right = speed_calculator(
    -151,
    -130,
    -100,
    0,
    -1,
    1
)

class Controller(object):

    def __init__(self):
        self.pwm = board.L298N()
        self.wiimote = wiimote.WiimoteController()

    def run(self):
        self.wiimote.connect()
        self.pwm.setup()

        try:
            while True:
                if self.wiimote.is_btn_a_pressed():
                    acc_x, acc_y, acc_z = self.wiimote.read_acc()
                    forward = acc_to_speed(acc_y)
                    left_fact = acc_to_rotation_left(acc_x)
                    right_fact = acc_to_rotation_right(-acc_x)
                    left = int(left_fact * forward)
                    right = int(right_fact * forward)
                    self.pwm.set_duty_a(left)
                    self.pwm.set_duty_b(right)
                time.sleep(0.05)
        finally:
            self.pwm.cleanup()
            print "Interrupted. Good bye."

if __name__ == "__main__":
    controller = Controller()
    controller.run()
<|endoftext|>


<commit_before>import math
currentX = eval(input("Please enter your current, or starting X coordinate: "))
currentZ = eval(input("Please enter your current, or starting Z coordinate: "))

#above gets current location, bellow finds out where you are trying to get to

targetX = eval(input("Please enter your target, or final X coordinate: "))
targetZ = eval(input("Please enter your target, or final Z coordinate: "))

#your bending type, used for finding if /capital is closer.

while (true):
	bendingInput = input("What type of bending do you use? Valid choices are air, water, fire, earth, or none: ")
	bendingInput.upper()

	if bending == "FIRE":
		capitalX = 3950
		capitalZ = 9760
		break;
	elif bending == "AIR":
		capitalX = 10820
		capitalZ = 15010
		break;
	elif bending == "WATER":
		capitalX = 13300
		capitalZ = 2030
		break;
	elif bending == "EARTH":
		capitalX = 19780
		capitalZ = 5730
		break;
	elif bending == "NONE":
		capitalX = 0
		capitalZ = 0
		break;
	else:
		print("\nYou didn't give a valid input. \n")

#well, now for the hardest part. the distance formula.
#current position to target.
targetXDistance = (targetX - currentX)
targetZDistance = (targetZ - currentZ)
capitalXDistance = (targetX - capitalX)
capitalZDistance = (targetZ - capitalZ)

targetDistance = math.sqrt(math.pow(targetXDistance,2)+math.pow(targetZDistance,2))
targetDistance = math.floor(targetDistance)
print ("Distance from starting point to the target: " + repr(targetDistance))

#capital to target. now we check if capitalX is 0, and do not execute this portion.
if capitalX != 0:
    capitalDistance = math.sqrt(math.pow(capitalXDistance,2)+math.pow(capitalZDistance,2))
    capitaltotarget = math.floor(capitalDistance)
    print ("Distance from your capital to the target: " + repr(capitalDistance))
<commit_msg>fixed some errors.<commit_after>import math
currentX = eval(input("Please enter your current, or starting X coordinate: "))
currentZ = eval(input("Please enter your current, or starting Z coordinate: "))

#above gets current location, bellow finds out where you are trying to get to

targetX = eval(input("Please enter your target, or final X coordinate: "))
targetZ = eval(input("Please enter your target, or final Z coordinate: "))

#your bending type, used for finding if /capital is closer.

while (True):
	bending = input("What type of bending do you use? Valid choices are air, water, fire, earth, or none: ")
	bending = bending.upper()

	if bending == "FIRE":
		capitalX = 3950
		capitalZ = 9760
		break;
	elif bending == "AIR":
		capitalX = 10820
		capitalZ = 15010
		break;
	elif bending == "WATER":
		capitalX = 13300
		capitalZ = 2030
		break;
	elif bending == "EARTH":
		capitalX = 19780
		capitalZ = 5730
		break;
	elif bending == "NONE":
		capitalX = 0
		capitalZ = 0
		break;
	else:
		print("\nYou didn't give a valid input. \n")

#well, now for the hardest part. the distance formula.
#current position to target.
targetXDistance = (targetX - currentX)
targetZDistance = (targetZ - currentZ)
capitalXDistance = (targetX - capitalX)
capitalZDistance = (targetZ - capitalZ)

targetDistance = math.sqrt(math.pow(targetXDistance,2)+math.pow(targetZDistance,2))
targetDistance = math.floor(targetDistance)
print ("Distance from starting point to the target: " + repr(targetDistance))

#capital to target. now we check if capitalX is 0, and do not execute this portion.
if capitalX != 0:
    capitalDistance = math.sqrt(math.pow(capitalXDistance,2)+math.pow(capitalZDistance,2))
    capitalDistance = math.floor(capitalDistance)
    print ("Distance from your capital to the target: " + repr(capitalDistance))
<|endoftext|>


<commit_before>from Tkinter import *
from ttk import Style
from PIL import ImageTk, Image
from db import *

class Api(object):

    """docstring for api"""

    def __init__(self):
        fo = open("api.txt", "r")
        self.api = StringVar()
        fo.seek(0)
        if fo.read(1):
            fo.seek(0)
            s = fo.read()
            self.api.set(s)
        fo.close()

    def set_api(self, value):
        fo = open("api.txt", "w")
        fo.write(value)
        fo.close()
        self.api.set(value)

    def get_api(self):
        return self.api.get()

class Task(Frame):

    """docstring for Task"""

    def __init__(self, parent, id, title, message, task_type, datetime, window):
        Frame.__init__(self, parent, bg="white")
        #self.f1.grid(row=self.row, columnspan=4, sticky=W + E, pady=(0, 2))
        delete_img = ImageTk.PhotoImage(Image.open("del.png"))
        edit_img = ImageTk.PhotoImage(Image.open("edit.png"))

        self.id = id
        self.title = title
        self.message = message
        self.datetime = datetime
        self.task_type = task_type

        self.window = window

        self.title1 = Label(
            self, text=title, bg='white', justify=LEFT, wraplength=300, font="Arial 14")
        self.datetime1 = Label(
            self, text=datetime, bg='white', font="Arial 10")
        self.message1 = Label(
            self, text=message + task_type, bg="white", justify=LEFT, wraplength=300, font="Arial 10")
        self.delete = Label(
            self, image=delete_img, bg='#e74c3c', justify=LEFT)
        self.delete.image = delete_img
        self.edit = Label(
            self, image=edit_img, bg='#2ecc71', justify=LEFT)
        self.edit.image = edit_img

        self.delete.bind('<Button-1>', self.delete_task)
        self.edit.bind('<Button-1>', self.edit_task)

        self.delete.pack(in_=self, anchor=NE, side=RIGHT)
        self.edit.pack(in_=self, anchor=NE, side=RIGHT)
        self.title1.pack(in_=self, anchor=W, fill=Y)
        self.message1.pack(in_=self, anchor=SW, fill=Y)
        self.datetime1.pack(in_=self, anchor=SE)

    def delete_task(self, e):
        mysql = MySQL()
        sqlite = SQLite()
        if self.datetime == '':
            sqlite.delete_task(self.id)
        else:
            remote_id = sqlite.get_remote_id(self.id)
            mysql.delete_task(remote_id)
            sqlite.delete_task(self.id)
        self.destroy()

    def edit_task(self, e):
        data = {
            'title': StringVar(),
            'message': StringVar(),
            'date': StringVar(),
            'time': StringVar()
        }

        data['title'].set(self.title)
        data['message'].set(self.message)
        data['date'].set(self.datetime.split()[0])
        data['time'].set(self.datetime.split()[1][:-3])
        self.delete_task(e)
        self.window.newtext(self.task_type, data, 'Edit')

class App(Frame):

    """docstring for App"""

    def paste(self):
        self.entry.event_generate('<Control-v>')

    def cut(self):
        self.entry.event_generate('<Control-x>')

    def copy(self):
        self.entry.event_generate('<Control-c>')

    def save(self):
        api = Api()
        api.set_api(self.api_entry.get())
        self.s.destroy()
        self.clearFrame()

    def setting(self):
        api = Api()
        self.s = Toplevel(self, padx=10, pady=10)
        self.s.title("Update API Key")
        self.s.resizable(0, 0)
        val = StringVar()
        val.set(api.get_api())
        self.api_label = Label(self.s, text="API Key")
        self.api_label.grid(row=0, column=0, sticky=W, ipady=10)
        self.api_entry = Entry(self.s, textvariable=val, width=30)
        self.api_entry.grid(row=0, column=1, columnspan=2, sticky=W + E, ipady=3)
        self.save_btn = Button(self.s, text="Save", padx=10, pady=5, command=self.save)
        self.save_btn.grid(row=1, column=0, columnspan=3, sticky=W + E, pady=5)

    def newtext(self, task_type, values=dict(), btn='Add Task'):
        if values == {}:
            values['title'] = StringVar().set('')
            values['message'] = StringVar().set('')
            values['date'] = StringVar()
            values['date'].set('2014-10-11')
            values['time'] = StringVar()
            values['time'].set('13:37')
        self.task_type = task_type
        self.t = Toplevel(self, padx=10, pady=10)
        self.t.title("Add a task")
        self.t.resizable(0, 0)
        # self.t.geometry("300x200+120+120")

        self.title_label = Label(self.t, text="Title")
        self.title_label.grid(row=0, column=0, sticky=W, ipady=10)
        self.title = Entry(self.t, textvariable=values['title'])
        self.title.grid(row=0, column=1, columnspan=2, sticky=W + E, ipady=3)

        self.message_label = Label(self.t, text="Message")
        self.message_label.grid(row=1, column=0, sticky=W, ipady=10)
        self.message = Entry(self.t, textvariable=values['message'])
        self.message.grid(row=1, column=1, columnspan=2, sticky=W + E, ipady=3)

        self.datetime_label = Label(self.t, text="Datetime")
        self.datetime_label.grid(row=2, column=0, sticky=W, ipady=10)

        self.datetime_date = Entry(
            self.t, textvariable=values['date'])
        self.datetime_date.grid(row=2, column=1, sticky=W, ipady=3)

        self.datetime_time = Entry(
            self.t, textvariable=values['time'])
        self.datetime_time.grid(row=2, column=2, sticky=W, ipady=3)

        self.l = Button(self.t, padx=10, pady=5)
        self.l["text"] = btn
        self.l["command"] = self.get_newtext
        self.l.grid(row=3, columnspan=3, sticky=N + E + W + S, pady=5)

    def get_newtext(self):
        title = self.title.get()
        message = self.message.get()
        task_type = self.task_type
        date = self.datetime_date.get()
        time = self.datetime_time.get()
        self.addTask(title, message, task_type, date, time)
        self.t.destroy()

    def crateWidgets(self):
        self.row = 0

        self.columnconfigure(0, pad=0)
        self.columnconfigure(1, pad=0)
        self.columnconfigure(2, pad=0)
        self.columnconfigure(3, pad=0)

        self.new_text = Button(self.frame, padx=25, pady=10)
        self.new_text["text"] = "Text"
        self.new_text["command"] = lambda: self.newtext("text")

        self.new_text.grid(row=0, sticky=N + S + E + W, column=0)

        self.new_list = Button(self.frame, padx=25, pady=10)
        self.new_list["text"] = "List"
        self.new_list["command"] = lambda: self.newtext("list")

        self.new_list.grid(row=0, sticky=N + S + E + W, column=1)

        self.new_link = Button(self.frame, padx=25, pady=10)
        self.new_link["text"] = "Link"
        self.new_link["command"] = lambda: self.newtext("link")

        self.new_link.grid(row=0, sticky=N + S + E + W, column=2)

        self.new_file = Button(self.frame, padx=25, pady=10)
        self.new_file["text"] = "File"
        self.new_file["command"] = lambda: self.newtext("file")

        self.new_file.grid(row=0, sticky=N + S + E + W, column=3)

        #self.QUIT = Button(self.frame, text="Quit", command=quit, padx=25, pady=10, bg="#fafafa")
        #self.QUIT.grid(row=1, columnspan=4, sticky=W + E)

        self.pack()

        self.getTask()

    def clearFrame(self):
        for child in self.frame.winfo_children():
            child.destroy()
        self.crateWidgets()

    def createFrame(self, title, message, task_type, datetime, id=''):
        self.row += 1
        # self.f1 = Frame(self.frame, bg="white")
        # self.f1.grid(row=self.row, columnspan=4, sticky=W + E, pady=(0, 2))

        # self.title1 = Label(
        #     self.frame, text=title, bg='white', justify=LEFT, font='serif 14', wraplengt=300)
        # self.datetime1 = Label(
        #     self.frame, text=datetime, bg='white', font='serif 10')
        # self.message1 = Label(
        # self.frame, text=message+link, bg="white", justify=LEFT, font='serif
        # 10', wraplengt=300)

        # self.title1.pack(in_=self.f1, ancho=W, fill=Y)
        # self.message1.pack(in_=self.f1, anchor=SW, fill=Y)
        # self.datetime1.pack(in_=self.f1, anchor=SE)
        Task(self.frame, id, title, message, task_type, datetime, self).grid(row=self.row, columnspan=4, sticky=W + E, pady=(0, 2))

    def getTask(self):
        api = Api()
        self.api = api.get_api()
        for row in self.sqlite.get_task(self.api):
            print row
            self.createFrame(row[1], row[2], row[3], row[4], id=row[0])

    def addTask(self, title, message, task_type, date, time):
        print title, message, task_type, date, time
        self.data = {
            'api': self.api,
            'title': title,
            'message': message,
            'task_type': task_type,
        }
        if date == "" and time == "":
            self.data['time'] = ""
            self.data['remote_id'] = 0
        else:
            self.data['time'] = date + ' ' + time + ':00'
            self.data['remote_id'] = self.mysql.insert_task(self.data)
        task_id = self.sqlite.insert_task(self.data)
        print task_id

        self.createFrame(title, message, task_type, date + " " + time + ":00", task_id)
        #self.clearFrame()

    def OnFrameConfigure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def __init__(self, master=None):

        self.mysql = MySQL()
        self.sqlite = SQLite('db.db')

        api = Api()
        self.api = api.get_api()
        #self.api = ''

        Frame.__init__(self, master)

        Style().configure('.', font=('Arial', 10))
        #Style().configure("TButton", padding=(0, 3, 0, 3))

        self.canvas = Canvas(master, borderwidth=0, background="#e5e5e5")
        self.frame = Frame(self.canvas, background="#b4b4b4")
        self.vsb = Scrollbar(
            master, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both")
        self.canvas.create_window((0, 0), window=self.frame, anchor=NW)

        self.frame.bind("<Configure>", self.OnFrameConfigure)

        self.menubar = Menu(self.master)
        self.master.config(menu=self.menubar)

        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Setting", command=self.setting)
        filemenu.add_command(label="Quit", command=quit)
        self.menubar.add_cascade(label="File", menu=filemenu)

        self.crateWidgets()

def main():
    root = Tk()
    root.resizable(width=FALSE, height=FALSE)
    root.geometry("335x600+150+150")
    root.title('To-do Bullet (Dev.)')

    # menubar = Menu(root)
    # menu = Menu(menubar, tearoff=0)
    # menu.add_command(label="Setting", command=run_setting)
    # menu.add_command(label="Exit", command=root.quit)

    # menubar.add_cascade(label="File", menu=menu)

    # root.config(menu=menubar)
    app = App(master=None)
    app.mainloop()
    root.destroy()

main()
<commit_msg>PIL import for mac<commit_after>from Tkinter import *
from ttk import Style
try:
    from PIL import ImageTK, Image
except ImportError:
    import ImageTk, Image
from db import *

class Api(object):

    """docstring for api"""

    def __init__(self):
        fo = open("api.txt", "r")
        self.api = StringVar()
        fo.seek(0)
        if fo.read(1):
            fo.seek(0)
            s = fo.read()
            self.api.set(s)
        fo.close()

    def set_api(self, value):
        fo = open("api.txt", "w")
        fo.write(value)
        fo.close()
        self.api.set(value)

    def get_api(self):
        return self.api.get()

class Task(Frame):

    """docstring for Task"""

    def __init__(self, parent, id, title, message, task_type, datetime, window):
        Frame.__init__(self, parent, bg="white")
        #self.f1.grid(row=self.row, columnspan=4, sticky=W + E, pady=(0, 2))
        delete_img = ImageTk.PhotoImage(Image.open("del.png"))
        edit_img = ImageTk.PhotoImage(Image.open("edit.png"))

        self.id = id
        self.title = title
        self.message = message
        self.datetime = datetime
        self.task_type = task_type

        self.window = window

        self.title1 = Label(
            self, text=title, bg='white', justify=LEFT, wraplength=300, font="Arial 14")
        self.datetime1 = Label(
            self, text=datetime, bg='white', font="Arial 10")
        self.message1 = Label(
            self, text=message + task_type, bg="white", justify=LEFT, wraplength=300, font="Arial 10")
        self.delete = Label(
            self, image=delete_img, bg='#e74c3c', justify=LEFT)
        self.delete.image = delete_img
        self.edit = Label(
            self, image=edit_img, bg='#2ecc71', justify=LEFT)
        self.edit.image = edit_img

        self.delete.bind('<Button-1>', self.delete_task)
        self.edit.bind('<Button-1>', self.edit_task)

        self.delete.pack(in_=self, anchor=NE, side=RIGHT)
        self.edit.pack(in_=self, anchor=NE, side=RIGHT)
        self.title1.pack(in_=self, anchor=W, fill=Y)
        self.message1.pack(in_=self, anchor=SW, fill=Y)
        self.datetime1.pack(in_=self, anchor=SE)

    def delete_task(self, e):
        mysql = MySQL()
        sqlite = SQLite()
        if self.datetime == '':
            sqlite.delete_task(self.id)
        else:
            remote_id = sqlite.get_remote_id(self.id)
            mysql.delete_task(remote_id)
            sqlite.delete_task(self.id)
        self.destroy()

    def edit_task(self, e):
        data = {
            'title': StringVar(),
            'message': StringVar(),
            'date': StringVar(),
            'time': StringVar()
        }

        data['title'].set(self.title)
        data['message'].set(self.message)
        data['date'].set(self.datetime.split()[0])
        data['time'].set(self.datetime.split()[1][:-3])
        self.delete_task(e)
        self.window.newtext(self.task_type, data, 'Edit')

class App(Frame):

    """docstring for App"""

    def paste(self):
        self.entry.event_generate('<Control-v>')

    def cut(self):
        self.entry.event_generate('<Control-x>')

    def copy(self):
        self.entry.event_generate('<Control-c>')

    def save(self):
        api = Api()
        api.set_api(self.api_entry.get())
        self.s.destroy()
        self.clearFrame()

    def setting(self):
        api = Api()
        self.s = Toplevel(self, padx=10, pady=10)
        self.s.title("Update API Key")
        self.s.resizable(0, 0)
        val = StringVar()
        val.set(api.get_api())
        self.api_label = Label(self.s, text="API Key")
        self.api_label.grid(row=0, column=0, sticky=W, ipady=10)
        self.api_entry = Entry(self.s, textvariable=val, width=30)
        self.api_entry.grid(row=0, column=1, columnspan=2, sticky=W + E, ipady=3)
        self.save_btn = Button(self.s, text="Save", padx=10, pady=5, command=self.save)
        self.save_btn.grid(row=1, column=0, columnspan=3, sticky=W + E, pady=5)

    def newtext(self, task_type, values=dict(), btn='Add Task'):
        if values == {}:
            values['title'] = StringVar().set('')
            values['message'] = StringVar().set('')
            values['date'] = StringVar()
            values['date'].set('2014-10-11')
            values['time'] = StringVar()
            values['time'].set('13:37')
        self.task_type = task_type
        self.t = Toplevel(self, padx=10, pady=10)
        self.t.title("Add a task")
        self.t.resizable(0, 0)
        # self.t.geometry("300x200+120+120")

        self.title_label = Label(self.t, text="Title")
        self.title_label.grid(row=0, column=0, sticky=W, ipady=10)
        self.title = Entry(self.t, textvariable=values['title'])
        self.title.grid(row=0, column=1, columnspan=2, sticky=W + E, ipady=3)

        self.message_label = Label(self.t, text="Message")
        self.message_label.grid(row=1, column=0, sticky=W, ipady=10)
        self.message = Entry(self.t, textvariable=values['message'])
        self.message.grid(row=1, column=1, columnspan=2, sticky=W + E, ipady=3)

        self.datetime_label = Label(self.t, text="Datetime")
        self.datetime_label.grid(row=2, column=0, sticky=W, ipady=10)

        self.datetime_date = Entry(
            self.t, textvariable=values['date'])
        self.datetime_date.grid(row=2, column=1, sticky=W, ipady=3)

        self.datetime_time = Entry(
            self.t, textvariable=values['time'])
        self.datetime_time.grid(row=2, column=2, sticky=W, ipady=3)

        self.l = Button(self.t, padx=10, pady=5)
        self.l["text"] = btn
        self.l["command"] = self.get_newtext
        self.l.grid(row=3, columnspan=3, sticky=N + E + W + S, pady=5)

    def get_newtext(self):
        title = self.title.get()
        message = self.message.get()
        task_type = self.task_type
        date = self.datetime_date.get()
        time = self.datetime_time.get()
        self.addTask(title, message, task_type, date, time)
        self.t.destroy()

    def crateWidgets(self):
        self.row = 0

        self.columnconfigure(0, pad=0)
        self.columnconfigure(1, pad=0)
        self.columnconfigure(2, pad=0)
        self.columnconfigure(3, pad=0)

        self.new_text = Button(self.frame, padx=25, pady=10)
        self.new_text["text"] = "Text"
        self.new_text["command"] = lambda: self.newtext("text")

        self.new_text.grid(row=0, sticky=N + S + E + W, column=0)

        self.new_list = Button(self.frame, padx=25, pady=10)
        self.new_list["text"] = "List"
        self.new_list["command"] = lambda: self.newtext("list")

        self.new_list.grid(row=0, sticky=N + S + E + W, column=1)

        self.new_link = Button(self.frame, padx=25, pady=10)
        self.new_link["text"] = "Link"
        self.new_link["command"] = lambda: self.newtext("link")

        self.new_link.grid(row=0, sticky=N + S + E + W, column=2)

        self.new_file = Button(self.frame, padx=25, pady=10)
        self.new_file["text"] = "File"
        self.new_file["command"] = lambda: self.newtext("file")

        self.new_file.grid(row=0, sticky=N + S + E + W, column=3)

        #self.QUIT = Button(self.frame, text="Quit", command=quit, padx=25, pady=10, bg="#fafafa")
        #self.QUIT.grid(row=1, columnspan=4, sticky=W + E)

        self.pack()

        self.getTask()

    def clearFrame(self):
        for child in self.frame.winfo_children():
            child.destroy()
        self.crateWidgets()

    def createFrame(self, title, message, task_type, datetime, id=''):
        self.row += 1
        # self.f1 = Frame(self.frame, bg="white")
        # self.f1.grid(row=self.row, columnspan=4, sticky=W + E, pady=(0, 2))

        # self.title1 = Label(
        #     self.frame, text=title, bg='white', justify=LEFT, font='serif 14', wraplengt=300)
        # self.datetime1 = Label(
        #     self.frame, text=datetime, bg='white', font='serif 10')
        # self.message1 = Label(
        # self.frame, text=message+link, bg="white", justify=LEFT, font='serif
        # 10', wraplengt=300)

        # self.title1.pack(in_=self.f1, ancho=W, fill=Y)
        # self.message1.pack(in_=self.f1, anchor=SW, fill=Y)
        # self.datetime1.pack(in_=self.f1, anchor=SE)
        Task(self.frame, id, title, message, task_type, datetime, self).grid(row=self.row, columnspan=4, sticky=W + E, pady=(0, 2))

    def getTask(self):
        api = Api()
        self.api = api.get_api()
        for row in self.sqlite.get_task(self.api):
            print row
            self.createFrame(row[1], row[2], row[3], row[4], id=row[0])

    def addTask(self, title, message, task_type, date, time):
        print title, message, task_type, date, time
        self.data = {
            'api': self.api,
            'title': title,
            'message': message,
            'task_type': task_type,
        }
        if date == "" and time == "":
            self.data['time'] = ""
            self.data['remote_id'] = 0
        else:
            self.data['time'] = date + ' ' + time + ':00'
            self.data['remote_id'] = self.mysql.insert_task(self.data)
        task_id = self.sqlite.insert_task(self.data)
        print task_id

        self.createFrame(title, message, task_type, date + " " + time + ":00", task_id)
        #self.clearFrame()

    def OnFrameConfigure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    def __init__(self, master=None):

        self.mysql = MySQL()
        self.sqlite = SQLite('db.db')

        api = Api()
        self.api = api.get_api()
        #self.api = ''

        Frame.__init__(self, master)

        Style().configure('.', font=('Arial', 10))
        #Style().configure("TButton", padding=(0, 3, 0, 3))

        self.canvas = Canvas(master, borderwidth=0, background="#e5e5e5")
        self.frame = Frame(self.canvas, background="#b4b4b4")
        self.vsb = Scrollbar(
            master, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both")
        self.canvas.create_window((0, 0), window=self.frame, anchor=NW)

        self.frame.bind("<Configure>", self.OnFrameConfigure)

        self.menubar = Menu(self.master)
        self.master.config(menu=self.menubar)

        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="Setting", command=self.setting)
        filemenu.add_command(label="Quit", command=quit)
        self.menubar.add_cascade(label="File", menu=filemenu)

        self.crateWidgets()

def main():
    root = Tk()
    root.resizable(width=FALSE, height=FALSE)
    root.geometry("335x600+150+150")
    root.title('To-do Bullet (Dev.)')

    # menubar = Menu(root)
    # menu = Menu(menubar, tearoff=0)
    # menu.add_command(label="Setting", command=run_setting)
    # menu.add_command(label="Exit", command=root.quit)

    # menubar.add_cascade(label="File", menu=menu)

    # root.config(menu=menubar)
    app = App(master=None)
    app.mainloop()
    root.destroy()

main()
<|endoftext|>


<commit_before>import cv2
import numpy as np
from os import listdir
from os.path import isfile, join
from controls import Controls

def PreprocessingOCR(image, ctrl, resImg):
    resImg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    mask = cv2.adaptiveThreshold(resImg, ctrl.t[1], cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                         cv2.THRESH_BINARY, 19,3)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    mask= cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel,1)
    mask = cv2.erode(mask,kernel,3)
    return mask
def SegmentWords(mask, ctrl):
    tmp = cv2.bitwise_not(mask)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
    tmp = cv2.dilate(tmp, kernel,iterations=15)
    im2,contours,hierarchy = cv2.findContours(tmp, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    return mask, contours
def DrawContours(image, cnts):
    # loop over the contours
    image = cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)
    #image = cv2.drawContours(image, cnts, -1, (0, 255,0),3)
    for contour in cnts:
        # get rectangle bounding contour
        [x,y,w,h] = cv2.boundingRect(contour)
        if h < 80 or w < 80:
            continue
        cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)
    return image
#get list of source images in images folder
imageList = [join("./images/",f) for f in listdir("./images/") if isfile(join("./images/",f))]
if len(imageList) == 0:
    raise StandardError("No files in images/ directory")
#initialize window and control panel positions with stock trackbars
cv2.namedWindow('display', cv2.WINDOW_NORMAL)
controlsList = [(0,150,255), (0,255,255), (3,3,10), (0,0,len(imageList) - 1)]
ctrl = Controls(controlsList)
cv2.resizeWindow('display', 800,600)
cv2.moveWindow('display', 100,0)
image = cv2.imread(imageList[ctrl.t[3]])
currentImageNo = ctrl.t[3]

#initialize variables
resImg = np.ones((image.shape[0], image.shape[1], 3), np.uint8)

cv2.imshow('display',image)
while True:
    key = cv2.waitKey(100)#100ms wait in event loop
    if currentImageNo != ctrl.t[3]:
        image = cv2.imread(imageList[ctrl.t[3]])
        currentImageNo = ctrl.t[3]
    resImg = PreprocessingOCR(image, ctrl,resImg)
    resImg, contours = SegmentWords(resImg,ctrl)
    resImg = DrawContours(resImg, contours)
    cv2.imshow('display',resImg)
    if key == 27: #escape key
        break
    #here all vision processing should be performed
cv2.destroyAllWindows()

<commit_msg>Added basic OCR routines for segmenting words into letters<commit_after>import cv2
import numpy as np
from os import listdir
from os.path import isfile, join
from controls import Controls

def PreprocessingOCR(image, ctrl, resImg):
    resImg = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    #5 for median blur seems to be a good denoising strategy
    resImg = cv2.medianBlur(resImg,ctrl.t[2] - (ctrl.t[2] + 1) %2 + 2)
    mask = cv2.adaptiveThreshold(resImg, ctrl.t[1], cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                         cv2.THRESH_BINARY, 19,3)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    mask= cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel,1)
    mask = cv2.erode(mask,kernel,3)
    return mask
def SegmentWords(mask, ctrl):
    tmp = cv2.bitwise_not(mask)
    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5))
    tmp = cv2.dilate(tmp, kernel,iterations=15)
    im2,contours,hierarchy = cv2.findContours(tmp, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    return mask, contours
def DrawContours(image, cnts):
    # loop over the contours
    image_color = cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)
    for contour in cnts:
        # get rectangle bounding contour
        [x,y,w,h] = cv2.boundingRect(contour)
        if h < 80 or w < 80:
            continue
        cv2.rectangle(image_color,(x,y),(x+w,y+h),(255,0,255),2)
    return image_color
def CutoutWords(image, cnts):
    cutouts = []
    # todo merge words if split like ko character
    for contour in cnts:
        # get rectangle bounding contour
        [x,y,w,h] = cv2.boundingRect(contour)
        if h < 80 or w < 80:
            continue
        cutouts.append(image[y:(y+h),x:(x+w)])
    return cutouts

def consecutive(data, stepsize=1):
    return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)
def Split(image):
    print image.shape
    chars = []
    #analyze columns for splits
    invImg = np.invert(image)
    imgCols = invImg.sum(0)
    #The idea is that this split will show free spaces between chars as length of zeros
    #we find all values that are zero
    zerosX = np.asarray(np.where(imgCols == 0))
    #and create a list of consecutive sequences
    zerosX = consecutive(zerosX[0])
    #now just convert to list split lines
    spaces = []
    spaceLen = []
    for z in zerosX:
        spaces.append((z[-1] + z[0]) / 2)
        spaceLen.append(z[-1] - z[0])
    #create an array of indices sorted by space length excluding first and last space
    print [i[0] for i in sorted(enumerate(spaceLen), key=lambda x:x[1])\
           if i[0] != 0 and i[0] != len(spaces)-1]

    #to create boundingbox we can do the same to 2nd dimension [x,x,y,y]
    imgCols = invImg.sum(1)
    zerosY = np.asarray(np.where(imgCols == 0))
    zerosY = consecutive(zerosY[0])
    boundingBox = [zerosX[0][-1], zerosX[-1][0],zerosY[0][-1], zerosY[-1][0]]

    h = float(boundingBox[3] - boundingBox[2])
    w = float(boundingBox[1] - boundingBox[0])
    cuts = len(spaces)
    print round(w/h)
    #if disparity between spaces and shape factor - try to join two spaces

    start = spaces[0]
    print("CUTS - ", cuts)
    for s in spaces:
        if start == s:
            continue
        letter = image[:,start:s]
        chars.append(letter)
        cv2.imshow('display',letter)
        cv2.waitKey(10000)
        start = s
    return chars

def SplitWords(cutouts):
    shapeMargin = 0.3
    retCnt = []
    #Only horizontal text is recognized
    for c in cutouts:
        h = float(c.shape[0])
        w = float(c.shape[1])
        if (w/h - 1.0) < shapeMargin:
            retCnt.append(c)
            continue
        words = Split(c)
        retCnt += words

#MAIN
#get list of source images in images folder
imageList = [join("./images/",f) for f in listdir("./images/") if isfile(join("./images/",f)) and f[0] != '.']
if len(imageList) == 0:
    raise StandardError("No files in images/ directory")
#initialize window and control panel positions with stock trackbars
cv2.namedWindow('display', cv2.WINDOW_NORMAL)
controlsList = [(0,150,255), (0,255,255), (3,3,10), (0,0,len(imageList) - 1)]
ctrl = Controls(controlsList)
cv2.resizeWindow('display', 800,600)
cv2.moveWindow('display', 100,0)
image = cv2.imread(imageList[ctrl.t[3]])
currentImageNo = ctrl.t[3]

#initialize variables
resImg = np.ones((image.shape[0], image.shape[1], 3), np.uint8)

cv2.imshow('display',image)
while True:
    key = cv2.waitKey(4000)#100ms wait in event loop
    if currentImageNo != ctrl.t[3]:
        image = cv2.imread(imageList[ctrl.t[3]])
        currentImageNo = ctrl.t[3]
    resImg = PreprocessingOCR(image, ctrl,resImg)
    resImg, contours = SegmentWords(resImg,ctrl)
    rectImg = DrawContours(resImg, contours)
    cutouts = CutoutWords(resImg, contours)
    cutouts = SplitWords(cutouts)
    cv2.imshow('display',rectImg)
    if key == 27: #escape key
        break
    #here all vision processing should be performed
cv2.destroyAllWindows()

<|endoftext|>


<commit_before>from createCollection import createCollection
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime
import json

def main():
        #createCollection('agarner','books')
        now = datetime.datetime.now()
        items = []
        for i in range(0,10):
            item = ItemFactory.factory('item', [i, 'item' + str(i), now, now])
            print(item.name)
            items.append(item)
        itemCollection = Collection('Items', 'agarner', items)
        print itemCollection.toJSON()

if __name__ == '__main__':
    main()
<commit_msg>Implement ability to save json data to collection file<commit_after>from createCollection import createCollection
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path

CONST_COLLECTIONS_NAME = 'collections'
CONST_USERNAME = 'agarner'
CONST_COLLECTION = 'Items'

def generateItemsCollection():
    items = []
    now = datetime.datetime.now()
    for i in range(0,10):
        item = ItemFactory.factory('item', [i, 'item' + str(i), now, now])
        print(item.name)
        items.append(item)
    return Collection(CONST_COLLECTION, CONST_USERNAME, items)

def main():
        createCollection(CONST_USERNAME,CONST_COLLECTION)
        itemCollection = generateItemsCollection()

        collectionsFilePath = CONST_COLLECTIONS_NAME+'/'+CONST_USERNAME+'_'+CONST_COLLECTIONS_NAME+'/'+CONST_USERNAME+'_'+CONST_COLLECTION+'_'+'collection.dat'
        if os.path.isfile(collectionsFilePath):
            collectionFile = open(collectionsFilePath, 'w')
            collectionFile.write(itemCollection.toJSON())
            collectionFile.close()

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>#!/usr/bin/env

print "Started"

answeryet = False
nextline = False
pos = []
small = 0
answerb = 0
answers = open('/home/penagwin/.config/sublime-text-3/Packages/User/Question.txt', 'r')
questions = open('/home/penagwin/.config/sublime-text-3/Packages/User/Answers.txt', 'r')
for question in questions:
	while True:
		pos.append(answers.tell())
		currentquestion = question.replace("\n", "")
		answer = answers.readline()
		if answer == "END OF FILE":
			break
		if answer.find("Question") != -1:
			answerb = 1
		elif answer.find("Correct Answer:") != -1:
			answerb = 2

		if answer.find(currentquestion) != -1 and answerb == 1:
			print answer
			answer = answers.readline()
			answer = answers.readline()
			print answer

		if answer.find(currentquestion) != -1 and answerb == 2:
			print answer
			while answer.lower().find("answer") == -1 or answer.lower().find("answer:") != -1:
				small = small +1
				#print " "+str(len(pos)-small)+ "        " + str(len(pos)) + '                '+ answers.readline()
				answers.seek(pos[len(pos)-small])
				answer = answers.readline()
				answers.seek(pos[len(pos)-small-1])
			print answers.readline()
			answers.seek(pos[len(pos)-1])
			small=0
			answerb = 0
	answers.seek(0)
	answerb = 0

answers.close()
questions.close()<commit_msg>deployment<commit_after>#!/usr/bin/env

print "Started"

answeryet = False
nextline = False
pos = []
small = 0
answerb = 0
answers = open('/home/penagwin/.config/sublime-text-3/Packages/User/Question.txt', 'r')
questions = open('/home/penagwin/.config/sublime-text-3/Packages/User/Answers.txt', 'r')
for question in questions:
	while True:
		pos.append(answers.tell())
		currentquestion = question.replace("\n", "")
		answer = answers.readline()
		if answer == "END OF FILE":
			break
		if answer.find("Question") != -1:
			answerb = 1
		elif answer.find("Correct Answer:") != -1:
			answerb = 2

		if answer.find(currentquestion) != -1 and answerb == 1:
			print answer

		if answer.find(currentquestion) != -1 and answerb == 2:
			print answer
			while answer.lower().find("answer") == -1 or answer.lower().find("answer:") != -1:
				small = small +1
				#print " "+str(len(pos)-small)+ "        " + str(len(pos)) + '                '+ answers.readline()
				answers.seek(pos[len(pos)-small])
				answer = answers.readline()
				answers.seek(pos[len(pos)-small-1])
			print answers.readline()
			answers.seek(pos[len(pos)-1])
			small=0
			answerb = 0
	answers.seek(0)
	answerb = 0

answers.close()
questions.close()<|endoftext|>