import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

"""
Return the distance from node1 to node2
"""
def dist(node1, node2):
    return (((node1.position[0] - node2.position[0]) ** 2) + ((node1.position[1] - node2.position[1]) ** 2)) **0.5

def InspectReefData3D():
    def StandardReefFunction(x, y):
        x = (x-0.5 *100)/15
        y = (y-0.5 *100)/15
        return (1.0 - x / 2.0 + x ** 5.0 + y ** 3.0) * np.exp(-x ** 2.0 - y ** 2.0) - 10.0

    fig = plt.figure()
    ax = fig.gca(projection='3d')

    # Make data.
    X = np.arange(0, 100, 0.25)
    Y = np.arange(0, 100, 0.25)
    X, Y = np.meshgrid(X, Y)
    Z1 = StandardReefFunction(X, Y)

    # Plot the surface.
    surf = ax.plot_surface(X, Y, Z1, cmap='gray',alpha=1)
    ax.set_aspect('equal', 'box')
    ax.grid(False)

    plt.show()

def InspectReefData2D():
    def StandardReefFunction(x, y):
        x = (x-0.5 *100)/15
        y = (y-0.5 *100)/15
        return (1.0 - x / 2.0 + x ** 5.0 + y ** 3.0) * np.exp(-x ** 2.0 - y ** 2.0) - 10.0

    fig, ax = plt.subplots()

    # Make data.
    X = np.arange(0, 100, 0.25)
    Y = np.arange(0, 100, 0.25)
    X, Y = np.meshgrid(X, Y)

    # reef levels
    plt.contourf(X, Y, StandardReefFunction(X, Y), 8, alpha=.75, cmap='gray')

    # contour lines
    ax.contourf(X, Y, StandardReefFunction(X, Y),levels = [-9.5, 10], colors = 'red', linestyles = 'solid',zorder=10)

    # some formatting
    ax.set_aspect('equal', 'box')
    ax.set_xlim([0, 100])
    ax.set_ylim([0, 100])
    plt.title('2-D Cut at Depth z = -9.5')

    plt.show()

def InspectReefData2DComplete():
    UnknownRegions = { \
                                   0.8: [(50, 15), (43, 25), (80, 25), (88, 19), (90,18)], \
                                   0.4: [(80, 84), (95, 80), (95, 92), (76, 95)], \
                                   0.1: [(11, 8), (40, 0), (40, 17), (11, 11)] \
                                   }

    def StandardReefFunction(x, y):
        x = (x-0.5 *100)/15
        y = (y-0.5 *100)/15
        return (1.0 - x / 2.0 + x ** 5.0 + y ** 3.0) * np.exp(-x ** 2.0 - y ** 2.0) - 10.0

    fig, ax = plt.subplots()

    # Make data.
    X = np.arange(0, 100, 0.25)
    Y = np.arange(0, 100, 0.25)
    X, Y = np.meshgrid(X, Y)

    # reef levels
    plt.contourf(X, Y, StandardReefFunction(X, Y), 8, alpha=.75, cmap='gray')

    # contour lines
    ax.contourf(X, Y, StandardReefFunction(X, Y),levels = [-9.5, 10], colors = 'red', linestyles = 'solid',zorder=10)

    # unknown regions
    from matplotlib import path as mpath
    import matplotlib.patches as patches

    for risk_key in UnknownRegions:
        unknown_region = patches.PathPatch(mpath.Path(UnknownRegions[risk_key]), facecolor='red', lw=0.0001, alpha = risk_key)
        ax.add_patch(unknown_region)

    # some formatting
    ax.set_aspect('equal', 'box')
    ax.set_xlim([0, 100])
    ax.set_ylim([0, 100])
    plt.title('2-D Cut at Depth z = -9.5')

    plt.show()


from setuptools import setup, find_packages
import os

version = '0.1dev'

setup(
    name='uu.staticmap',
    version=version,
    description="Plone add-on; includes view for Google Static Map.",
    long_description=(
        open("README.txt").read() + "\n" +
        open(os.path.join("doc", "HISTORY.txt")).read()
        ),
    # Get more strings from
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        "Programming Language :: Python",
        "Framework :: Plone",
        ],
    keywords='',
    author='Sean Upton',
    author_email='sean.upton@hsc.utah.edu',
    url='http://bazaar.launchpad.net/~seanupton/+junk/uu.staticmap',
    license='GPL',
    packages=find_packages(exclude=['ez_setup']),
    namespace_packages=['uu'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'setuptools',
        'Products.CMFPlone',
        # -*- Extra requirements: -*-
    ],
    extras_require = {
        'test': ['plone.app.testing'],
    },
    entry_points="""
    # -*- Entry points: -*-
    [z3c.autoinclude.plugin]
    target = plone
    """,
    )


import json
import logging
import urllib
import urllib.request as urllib2
import feedparser
from flask import Flask
from flask import render_template
from flask import request
from config import CURRENCY_TOKEN, WEATHER_TOKEN

app = Flask(__name__)

def setup_logger(name):
    """ Setup logger
    """
    logger = logging.getLogger(name)
    if not logger.handlers:
        # Prevent logging from propagating to the root loggger
        logger.propagate = 0
        console = logging.StreamHandler()
        logger.addHandler(console)
        formatter = logging.Formatter('%(asctime)s \t%(levelname)s \t%(processName)s \t%(message)s')
        console.setFormatter
    return logger

WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid={}"

CURRENCY_URL = "https://openexchangerates.org//api/latest.json?app_id={}"

RSS_FEEDS = {'simplecast': 'https://feeds.simplecast.com/54nAGcIl',
             'cnn': 'http://rss.cnn.com/rss/edition.rss',
             'fox': 'http://feeds.foxnews.com/foxnews/latest',
             'iol': 'http://www.iol.co.za/cmlink/1.640',
             }

DEFAULT = {'publication': 'fox',
           'city': 'London,UK',
           'currency_from': 'GBP',
           'currency_to': 'USD'}

@app.route("/")
def home():
    # get customized headlines, based on user input or default
    publication = request.args.get('publication')
    if not publication:
        publication = DEFAULT['publication']
    articles = get_news(publication)
    # get customized weather based on user input or default
    city = request.args.get('city')
    if not city:
        city = DEFAULT['city']
    weather = get_weather(city)
    # get customized currency based on user input or default
    currency_from = request.args.get('currency_from')
    if not currency_from:
        currency_from = DEFAULT['currency_from']
    currency_to = request.args.get('currency_to')
    if not currency_to:
        currency_to = DEFAULT['currency_to']
    rate = get_rate(currency_from, currency_to)
    logger.info(f"{rate}")
    return render_template("home.html",
                           articles=articles,
                           weather=weather,
                           currency_from=currency_from,
                           currency_to=currency_to,
                           rate=rate,
                           )

def get_news(query):
    if not query or query.lower() not in RSS_FEEDS:
        publication = DEFAULT["publication"]
    else:
        publication = query.lower()
    feed = feedparser.parse(RSS_FEEDS[publication])
    # logger.info(f"{feed['entries']}")
    return feed['entries']

def get_weather(query):
    query = urllib.parse.quote(query)
    url = WEATHER_URL.format(query, WEATHER_TOKEN)
    data = urllib2.urlopen(url).read()
    parsed = json.loads(data)
    weather = None
    if parsed.get("weather"):
        weather = {"description": parsed["weather"][0]["description"],
                   "temperature": parsed["main"]["temp"],
                   "city": parsed["name"],
                   'country': parsed['sys']['country'],
                   }
    return weather

def get_rate(frm, to):
    url = CURRENCY_URL.format(CURRENCY_TOKEN)
    all_currency = urllib2.urlopen(url).read()

    parsed = json.loads(all_currency).get('rates')
    frm_rate = parsed.get(frm.upper())
    to_rate = parsed.get(to.upper())
    return to_rate/frm_rate

if __name__ == '__main__':
    logger = setup_logger("flask_news")
    logger.setLevel(logging.INFO)
    app.run(port=5000, debug=True)


import argparse
import os
import logging
from train import train
from self_train_pf import self_train_pf, reshape_text, calculate_score
os.environ["TOKENIZERS_PARALLELISM"] = "false"

import torch
import numpy as np
import random
from LoadData import load_ce_data, load_self_train_data, my_data_set, self_train_my_data_set
from torch.utils.data import Dataset, DataLoader, random_split
from models.main_model import Multimodel
from tqdm import  tqdm
import opts
os.environ["CUDA_VISIBLE_DEVICES"] = '0'

def eval(opt):
    device = opt.device
    model_s = Multimodel(device, opt).to(device)
    model_s.load_state_dict(torch.load(opt.trained_model_path))
    model_s.eval()

    _, _, test_data = load_ce_data(opt.img_feature_path, opt.text_comment_file, opt.com_num_use)
    test_set = my_data_set(test_data, opt)
    test_loader = DataLoader(test_set, batch_size=opt.ce_batch_size, shuffle=False, num_workers=4, )

    with torch.no_grad():
        predict_all = []
        label_all = []
        for val_text, val_image_feature, val_attribute, val_ret_coms, val_ret_texts, val_group, val_id in tqdm(
                test_loader):
            val_ret_coms_new = reshape_text(val_ret_coms, opt.com_num_use)

            val_group = val_group.view(-1).to(torch.int64).to(device)
            val_pred = model_s(val_text, val_image_feature.to(device),
                               val_attribute, val_ret_coms_new)

            # calculate the score
            predict_all.extend(val_pred.argmax(dim=1).detach().cpu().numpy())
            label_all.extend(val_group.detach().cpu().numpy())
    predict_all = np.vstack(predict_all)
    label_all = np.stack(label_all)
    precision, recall, fscore, acc = calculate_score(predict_all, label_all)

    print("test results: test_f1=%.4f test_pre=%.4f test_rec=%.4f test_acc=%.4f" % (
        fscore, precision, recall, acc))

if __name__=="__main__":
    opt = opts.parse_opt()
    opt.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    modes = ['ce', 'self']

    for mode in modes:
        print('mode: {}'.format(mode))
        if mode == 'ce':
            opt.trained_model_path = './save/ce_save/model_best.pth'
        if mode == 'self':
            opt.trained_model_path = './save/selftrain_save/model_best_0.pth'
        eval(opt)


#!/usr/bin/env python3
from flask import Flask
import json

app = Flask(__name__)

@app.route('/<variable>')
def ret_coords(variable):
    with open("json_updated.json") as f:
        json_data = f.read()
    json_data = json.loads(json_data)

    lat, lon = variable.split(",")
    lat = "{0:.4f}".format(float(lat))
    lon = "{0:.4f}".format(float(lon))

    j = lat+lon

    if j in json_data:
        new_json = json.dumps(json_data[j])

    return new_json


# -*- coding: UTF-8
#特定の文字列の出現数を調べてみる
#複数のキーワードの出現数の合計を求められるようにする

from pathlib import Path
terms = { 'for':0, 'if':0, 'else':0 }
path = Path()
for filepath in path.glob( '*.py' ):
    rfile = open( filepath,encoding='utf-8' )
    text = rfile.read()
    rfile.close()
    for term in terms:
        cnt = text.count( term )
        terms[term] += cnt
print( terms )


import pathos

import dotdot
from neuromodel import Offers, Model, ReplicatedModel, run_model

ΔA, ΔB, n = (0, 20), (0, 20), 4000
offers = Offers(ΔA=ΔA, ΔB=ΔB, n=n, random_seed=0)

def compute_fig6_data(w_p, model_class=Model):
    """

    If the result filename already exists, the computation will be skipped.
    :param model_class:  set to ReplicatedModel if you want to replicate the published figures.
                         set to Model to use the 'corrected' model, as described in the article.
    """
    model = model_class(n=n, ΔA=ΔA, ΔB=ΔB, random_seed=1, w_p=w_p)

    filename='data/fig6_{}[{}]{}.pickle'.format(w_p, n, model.desc)
    return run_model(model, offers, history_keys=('r_2', 'r_I'), filename=filename)

if __name__ == '__main__':
        def aux(args):
            compute_fig6_data(args['w_p'], model_class=args['model_class'])

        runs=[{'model_class': model, 'w_p': w_p} for w_p in [1.55, 1.70, 1.85]
                                                 for model in [Model, ReplicatedModel]]
        pool = pathos.multiprocessing.Pool()
        pool.map(aux, runs)


from flask import Flask, jsonify

app = Flask(__name__)

people_data = [
    {
    "id":"1",
    "first_name":"Amanda",
    "last_name":"Leech",
    "eye_color":"Hazel",
    "hair_color":"Brown"
    },
    {
    "id":"2",
    "first_name":"Jasmine",
    "last_name":"Leech",
    "eye_color":"Brown",
    "hair_color":"Brown"
    },
    {
    "id":"3",
    "first_name":"Hailey",
    "last_name":"Leech",
    "eye_color":"Blue",
    "hair_color":"Brown"
    },
    {
    "id":"4",
    "first_name":"Amelia",
    "last_name":"Leech",
    "eye_color":"Brown",
    "hair_color":"Blonde"
    },
    {
    "id":"5",
    "first_name":"Bobby",
    "last_name":"Brown",
    "eye_color":"Brown",
    "hair_color":"Brown"
    },
    {
    "id":"6",
    "first_name":"Aspen",
    "last_name":"Leech",
    "eye_color":"Blue",
    "hair_color":"Blonde"
    }
]

@app.route('/')
def say_hello():
    return('Hello World!')

@app.route('/thisisapost', methods=['GET','POST','DELETE'])
def this_is_a_post():
    request_method = request.method
    request_user_agent = request.user_agent
    return "thanks for returning POST
Method:{request_method}
{request_user_agent}", 200

@app.route('/people')
def people():
    return(people_data)

@app.route('/people/<id>', methods=['GET'])
def get_by_id(id):
    for char in people_data:
        if char['id'] == id:
            return(jsonify(char)), 200
    return"Character not found", 404

@app.route('/people/<id>/<field>', methods=['GET'])
def get_field_by_id(id, field):
    try:
        for char in people_data:
            if char['id'] == id:
                if field in char.keys():
                    return(jsonify(char[field])), 200 # ok
                else:
                    return "Field not found in character", 404 # not found
        return "Character not found", 404
    except:
        return "There was an error finding your data", 400 # bad request

if __name__ =='__main__':
    app.run(host='0.0.0.0', port=8086)


from openerp import models, fields, api, _
from openerp.exceptions import UserError
from openerp.osv.fields import related
import math
import calendar
import datetime
from datetime import date, timedelta as td, datetime

class kts_leave_holidays(models.Model):
    _inherit = "hr.holidays"
    request_type=fields.Selection([
        ('leave_request', 'Leave Request'),
        ('encashment_request', 'Encashment Request'),
        ], string='Request Type')

    @api.onchange('request_type')
    def request_type_on_change(self):
        leave_types=[]
        if self.request_type=='encashment_request':
            leave_types=self.env['hr.holidays.status'].search([('leave_encashment','=',True)])
            self.update({'holiday_status_id':leave_types.ids})
        else:
            leave_types=self.env['hr.holidays.status'].search([])
            self.update({'holiday_status_id':leave_types.ids})
        return {'domain':{'holiday_status_id':[('id','in',leave_types.ids)]}}

    @api.onchange('holiday_status_id','date_from','date_to')
    def holiday_status_on_change(self):
        calc_days=1
        no_of_days=0
        total_week_off=0
        total_holiday=0

        if self.holiday_status_id and self.date_from and self.date_to:
            d_from=datetime.strptime(self.date_from,"%Y-%m-%d %H:%M:%S")
            d_to=datetime.strptime(self.date_to,"%Y-%m-%d %H:%M:%S")
            d1=date(d_from.year,d_from.month,d_from.day)
            d2=date(d_to.year,d_to.month,d_to.day)
            delta=d2-d1
            total_week_off=0
            total_holiday=0
            if self.holiday_status_id.weekoff_exclude:
                for i in range(delta.days+1):
                    date_str=d1 + td(days=i)
                    cmp=str(date_str.weekday())
                    #print date_str.weekday()
                    weekoff=self.env['kts.week.off'].search([('name','=',cmp)])
                    if weekoff:
                        total_week_off+=1;

            if self.holiday_status_id.holiday_exclude:
                holidays=self.env['kts.holidays.creation'].search([])
                for holiday in holidays:
                    d_holiday=datetime.strptime(holiday.holiday_date,"%Y-%m-%d %H:%M:%S")
                    d3=date(d_holiday.year,d_holiday.month,d_holiday.day)

                    if (d3>=d1) and (d2>=d3):
                        total_holiday+=1
            if (self.date_to and self.date_from) and (self.date_from <= self.date_to):
                diff_day = self._get_number_of_days(self.date_from, self.date_to)
                no_of_days = round(math.floor(diff_day))+1
                self.number_of_days_temp=no_of_days-total_holiday-total_week_off
                if self.holiday_status_id.double_validation:
                    if self.employee_id and self.employee_id.parent_id:
                        self.state='validate1'
                    else:
                        raise UserError(_('You need to confirm from your manager and manager not assigned.'))
            else:
                self.number_of_days_temp = 0
        else:
            self.number_of_days_temp = 0
        return {'value':{'number_of_days_temp':self.number_of_days_temp}}

    def holidays_validate(self, cr, uid, ids, context=None):
        obj_emp = self.pool.get('hr.employee')
        ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)])
        manager = ids2 and ids2[0] or False
        self.write(cr, uid, ids, {'state': 'validate'}, context=context)
        data_holiday = self.browse(cr, uid, ids)
        for record in data_holiday:
            if record.double_validation:
                self.write(cr, uid, [record.id], {'manager_id2': manager})
            else:
                self.write(cr, uid, [record.id], {'manager_id': manager})
            if record.holiday_type == 'employee' and record.type == 'remove' and record.request_type != 'encashment_request':
                meeting_obj = self.pool.get('calendar.event')
                meeting_vals = {
                    'name': record.display_name,
                    'categ_ids': record.holiday_status_id.categ_id and [(6,0,[record.holiday_status_id.categ_id.id])] or [],
                    'duration': record.number_of_days_temp * 8,
                    'description': record.notes,
                    'user_id': record.user_id.id,
                    'start': record.date_from,
                    'stop': record.date_to,
                    'allday': False,
                    'state': 'open',            # to block that meeting date in the calendar
                    'class': 'confidential'
                }
                #Add the partner_id (if exist) as an attendee
                if record.user_id and record.user_id.partner_id:
                    meeting_vals['partner_ids'] = [(4,record.user_id.partner_id.id)]

                ctx_no_email = dict(context or {}, no_email=True)
                meeting_id = meeting_obj.create(cr, uid, meeting_vals, context=ctx_no_email)
                self._create_resource_leave(cr, uid, [record], context=context)
                self.write(cr, uid, ids, {'meeting_id': meeting_id})
            elif record.holiday_type == 'category':
                emp_ids = record.category_id.employee_ids.ids
                leave_ids = []
                batch_context = dict(context, mail_notify_force_send=False)
                for emp in obj_emp.browse(cr, uid, emp_ids, context=context):
                    vals = {
                        'name': record.name,
                        'type': record.type,
                        'holiday_type': 'employee',
                        'holiday_status_id': record.holiday_status_id.id,
                        'date_from': record.date_from,
                        'date_to': record.date_to,
                        'notes': record.notes,
                        'number_of_days_temp': record.number_of_days_temp,
                        'parent_id': record.id,
                        'employee_id': emp.id
                    }
                    leave_ids.append(self.create(cr, uid, vals, context=batch_context))
                for leave_id in leave_ids:
                    # TODO is it necessary to interleave the calls?
                    for sig in ('confirm', 'validate', 'second_validate'):
                        self.signal_workflow(cr, uid, [leave_id], sig)
        return True

class kts_leave(models.Model):
    _inherit = "hr.holidays.status"
    _description = "Kts Leave"
    holiday_exclude = fields.Boolean('Holiday Exclude')
    weekoff_exclude = fields.Boolean('Weekoff Exclude')
    leave_encashment = fields.Boolean('Leave Encashment')

class kts_holiday_creation(models.Model):
    _name = 'kts.holidays.creation'
    _description = "Kts Holiday"
    name= fields.Char('Reason', size=56)
    holiday_date=fields.Datetime('Holiday Date')

class kts_week_off(models.Model):
    _name = 'kts.week.off'
    _description = "Kts week off"
    name=fields.Selection([
        ('6', 'Sunday'),
        ('0', 'Monday'),
        ('1', 'Tuesday'),
        ('2','Wendsday'),
        ('3','Thursday'),
        ('4','Friday'),
        ('5','Saturday'),
        ], string='Week off day')

class kts_leave_period(models.Model):
    _name = 'kts.leave.period'
    _description = "Kts Leave Period"
    name= fields.Char('Leave Period Name', size=56)
    start_date=fields.Date('Start Date')
    end_date=fields.Date('End Date')
    leave_quarter = fields.Boolean('Quarter ')
    leave_semi = fields.Boolean('Semi Year')
    leave_year = fields.Boolean('Year')
    leave_generate = fields.Boolean('Leave Generate')

    @api.multi
    def unlink(self):
        if self.leave_generate:
            raise UserError(_('You cannot delete a period which is in Generated state.'))
        return super(kts_leave_period, self).unlink()

class kts_allocation_rules(models.Model):
    _name = 'kts.allocation.rules'
    _description = "Kts Allocation Rues"
    designatione= fields.Many2one('hr.job','Designation')
    hr_holiday_status=fields.Many2one('hr.holidays.status','Type')
    no_of_days=fields.Integer(string='No. of Days',)
    assignment_frequency = fields.Selection([('quarter','Quarter'),('semi','Semi quarter'),('year','Yearly')],'Assign Frequency')

class kts_generate_leave_allocation(models.Model):
    _name = 'kts.generate.leave.allocation'
    _description = "Kts Generate Leave Allocation "
    name= fields.Char('Name', size=56)
    period_type= fields.Many2one('kts.leave.period','Period')
    state=fields.Selection([
        ('draft', 'New'),
        ('generated', 'Generated'),
        ], string='Status', default="draft")

    @api.multi
    def unlink(self):
        if self.state=='generated':
            raise UserError(_('You cannot delete a leave allocation which is in Generated state.'))
        return super(kts_generate_leave_allocation, self).unlink()

    @api.multi
    def generate_allocation(self):
        self.ensure_one()
        if self.period_type.leave_generate:
            raise UserError(_('Leave generation process already done for this leave Period.'))
        if self.period_type:
            if self.period_type.leave_quarter:
                allocation_rules=self.env['kts.allocation.rules'].search([('assignment_frequency','=','quarter')],order='id asc')
                for allocation_id in allocation_rules:
                    hr_employee_ids=self.env['hr.employee'].search([('job_id','=',allocation_id.designatione.id)],order='id asc')
                    values={}
                    for emp_id in hr_employee_ids:
                        values={
                                'name':'%s allocated to %s for period %s'%(allocation_id.hr_holiday_status.name,emp_id.name,self.period_type.name),
                                'holiday_type':'employee',
                                'holiday_status_id':allocation_id.hr_holiday_status.id,
                                'employee_id':emp_id.id,
                                'type':'add',
                                'number_of_days_temp':allocation_id.no_of_days,
                                'state':'validate',
                                }
                        obj= self.env['hr.holidays'].create(values)

            if self.period_type.leave_semi:
                allocation_rules=self.env['kts.allocation.rules'].search([('assignment_frequency','=','semi')],order='id asc')
                for allocation_id in allocation_rules:
                    hr_employee_ids=self.env['hr.employee'].search([('job_id','=',allocation_id.designatione.id)],order='id asc')
                    values={}
                    for emp_id in hr_employee_ids:
                        values={
                                'name':'%s for %s'%(allocation_id.hr_holiday_status.name,emp_id.name),
                                'holiday_type':'employee',
                                'holiday_status_id':allocation_id.hr_holiday_status.id,
                                'employee_id':emp_id.id,
                                'type':'add',
                                'number_of_days_temp':allocation_id.no_of_days,
                                'state':'validate',
                                }
                        obj= self.env['hr.holidays'].create(values)

            if self.period_type.leave_year:
                allocation_rules=self.env['kts.allocation.rules'].search([('assignment_frequency','=','year')],order='id asc')
                for allocation_id in allocation_rules:
                    hr_employee_ids=self.env['hr.employee'].search([('job_id','=',allocation_id.designatione.id)],order='id asc')
                    values={}
                    for emp_id in hr_employee_ids:
                        values={
                                'name':'%s for %s'%(allocation_id.hr_holiday_status.name,emp_id.name),
                                'holiday_type':'employee',
                                'holiday_status_id':allocation_id.hr_holiday_status.id,
                                'employee_id':emp_id.id,
                                'type':'add',
                                'number_of_days_temp':allocation_id.no_of_days,
                                'state':'validate',
                                }
                        obj= self.env['hr.holidays'].create(values)
            self.period_type.leave_generate=True
            self.state='generated'


# month calendar for hellokey

from datetime import datetime, date, timedelta
from calendar import monthrange

def caldays(year, month):
    weekslist = []
    first = date(year, month, 1)
    last = date(year, month, monthrange(year, month)[1])
    firstextras = (first.weekday() + 1) % 7
    lastextras = 6 - ((last.weekday() + 1) % 7)

    firstcalday = first - timedelta(days=firstextras)
    lastcalday = last + timedelta(days=lastextras)

    days = (lastcalday - firstcalday).days + 1
    weeks = days // 7

    assert firstcalday.weekday() == 6
    assert lastcalday.weekday() == 5

    for i in range(weeks):
        week = []
        for d in range(7):
            week.append({'ymd': datetime.strftime(firstcalday, "%Y-%m-%d"),
                         'label': datetime.strftime(firstcalday, "%d")})
            firstcalday += timedelta(days=1)
        weekslist.append(week[:])
    return weekslist

    # s m t w t f s
    # 6 0 1 2 3 4 5
    # 1 = 6 = 0
    #   1 = 1
    #     1 = 2
    #       1

    # 0 1 2 3 4 5 6
    #     1

ans=caldays(2019, 10)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import datetime
import logging.config

import cherrypy
from config import log_conf, conf

from modules import Rule
from modules import TinkerforgeConnection
from modules import BVG

log = logging.getLogger()  # the logger

##########################################################################################
# Data class to store global information
##########################################################################################

class Data(object):
    bvg = None
    active_rules = []
    tinkerforge_connection = None
    wakeup_time = "0:0"

##########################################################################################
# Rule logic
##########################################################################################

def watering_rule():
    now = datetime.datetime.now()
    if (now.hour == 9 and now.minute == 0) or (now.hour == 19 and now.minute == 0):
        log.info("It is {0!s}:{1!s}, started watering.".format(now.hour, now.minute))
        Data.tinkerforge_connection.switch_socket("nXN", 50, 1, 1)
        time.sleep(60)
        log.info("It is {0!s}:{1!s}, stopped watering.".format(now.hour, now.minute))
        Data.tinkerforge_connection.switch_socket("nXN", 50, 1, 0)

def balkony_rule():
    now = datetime.datetime.now()
    if now.hour == 17 and now.minute == 0:
        log.info("It is {0!s}:{1!s}, activated Balkonbeleuchtung.".format(now.hour, now.minute))
        Data.tinkerforge_connection.switch_socket("nXN", 50, 1, 1)
    if now.hour == 22 and now.minute == 0:
        log.info("It is {0!s}:{1!s}, deactivated Balkonbeleuchtung.".format(now.hour, now.minute))
        Data.tinkerforge_connection.switch_socket("nXN", 50, 1, 0)

def wakeup_rule():
    wakup = datetime.datetime.strptime(Data.wakeup_time, "%H:%M")
    now = datetime.datetime.now()
    if wakup.minute >= 10:
        time_until_wakup = wakup.minute - now.minute
        if wakup.hour == now.hour and time_until_wakup == 10:
            log.info("Beginning to light up the bedroom, wake up!")
            for i in range(15):
                Data.tinkerforge_connection.dim_socket("nXN", 25, 1, i)
                time.sleep(30)
    else:
        log.warn("We don't support wakup times with minute <10 currently.")

##########################################################################################
# The Webserver
##########################################################################################

class Webserver(object):
    """Every api the webserver provides should be in its own class. The webserver shall
    initialize these classes. Then, cherrypy mounts the webserver and the subclasses at
    the desired endpoints."""

    # initialize subclasses
    def __init__(self):
        self.socket = self.Socket()
        self.rule = self.Rule()
        self.additional_information = self.AdditionalInformation()

    # entrypoint to webpage
    @cherrypy.expose
    def index(self):
            raise cherrypy.HTTPRedirect("/static")

    class Socket:
        """Webserver class to control sockets and dimmer."""

        @cherrypy.expose
        def list(self):
            sockets = self.create_socket_entry("Schreibtischlampe", 30, 3)
            sockets += self.create_socket_entry("Hintergrundbeleuchtung", 30, 2)
            sockets += self.create_socket_entry("Laterne", 31, 2)
            sockets += self.create_dim_entry("Nachtlicht", 25, 1)
            sockets += self.create_socket_entry("Balkonbewässerung", 50, 1)
            return sockets

        @cherrypy.expose
        def switch(self, address=-1, unit=-1, state=-1):
            if address == -1 or unit == -1 or state == -1:
                return "Invalid information: {0!s}, {1!s}, {2!s}.".format(address, unit, state)
            Data.tinkerforge_connection.switch_socket("nXN", int(address), int(unit), int(state))
            log.info("Sending signal to switch socket {0!s}-{1!s} to {2!s}.".format(address, unit, state))

        @cherrypy.expose
        def dim(self, address=-1, unit=-1, dim_value=-1):
            if address == -1 or unit == -1 or dim_value == -1:
                return "Invalid information: {0!s}, {1!s}, {2!s}.".format(address, unit, dim_value)
            Data.tinkerforge_connection.dim_socket("nXN", int(address), int(unit), int(dim_value))
            log.info("Tried to dim socket {0!s}-{1!s} to {2!s}.".format(address, unit, dim_value))

        @staticmethod
        def create_socket_entry(name, address, unit):
            return """

{n} ({a}_{u}, nXN)

                            <button class='alert button' onclick='$.ajax(
                                "/socket/switch?address={a}&unit={u}&state=0");'>Aus
                            </button>
                            <button class='success button' onclick='$.ajax(
                                "/socket/switch?address={a}&unit={u}&state=1");'>An
                            </button>

            """.format(n=name, a=str(address), u=str(unit))

        @staticmethod
        def create_dim_entry(name, address, unit):
            item_id = str(address) + "_" + str(unit)
            return """

{n} ({a}_{u}, nXN)

                        <input id='{i}' type='hidden'>

                        <button class='alert expanded button' onclick='$.ajax(
                          "/socket/switch?address={a}&unit={u}&state=0");'>Aus
                        </button>

            """.format(n=name, a=str(address), u=str(unit), i=item_id)

    class Rule:
        """Webserver class to control rules."""

        @cherrypy.expose
        def list(self):
            rules = ""
            for index in range(0, len(Data.active_rules)):
                rules += self.create_rule_entry(index)
            return rules

        @cherrypy.expose
        def toggle_rule_keep_alive(self, position, keep_alive):
            position = int(position)
            if 0 <= position < len(Data.active_rules):
                if keep_alive == "false":
                    Data.active_rules[position].deactivate_rule()
                else:
                    Data.active_rules[position].activate_rule()
            else:
                log.warn("No rule at position " + str(position))

        @staticmethod
        def create_rule_entry(position):
            name = Data.active_rules[position].tname
            if Data.active_rules[position].keep_alive:
                checked = "checked "
            else:
                checked = ""
            return """

                {n}

                        <input class='switch-input' id='{n}' type='checkbox' {c} onclick=
                          '$.ajax("/rule/toggle_rule_keep_alive?position={p}&keep_alive="
                          + event.target.checked);'>

            """.format(n=name, p=str(position), c=checked)

    class AdditionalInformation:
        """Webserver class to provide additional information."""

        @cherrypy.expose
        def connected_devices(self):
            if len(Data.tinkerforge_connection.current_entries) == 0:
                return "
Keine Geräte angeschlossen
"
            string = ""
            for key in Data.tinkerforge_connection.current_entries:
                string += ("
{0} ({1})
"
                           .format(key, Data.tinkerforge_connection.current_entries[key]))
            return string

        @cherrypy.expose
        def amm_illuminance(self):
            return (
                "
Aktuelle Helligkeit (amm): " +
                str(Data.tinkerforge_connection.get_illuminance("amm")) + " Lux
"
            )

        @cherrypy.expose
        def bvg(self):
            array = Data.bvg.call()
            if array is None:
                return "
Keine Abfahrtzeiten verfügbar
"
            string = ""
            for entry in array:
                string += "
{0} -> {1} ({2})
".format(entry[3], entry[1], entry[2])
            return string

        @cherrypy.expose
        def set_wakeup_time(self, wakeup_time):
            Data.wakeup_time = wakeup_time
            # TODO make sure that is has the right format
            log.info("Set wakeup time to {0}.".format(wakeup_time))

        @cherrypy.expose
        def get_wakeup_time(self):
            return Data.wakeup_time

##########################################################################################
# The Entrypoint of the Application
##########################################################################################

if __name__ == '__main__':
    # start all needed modules
    Data.tinkerforge_connection = TinkerforgeConnection("192.168.0.248")
    Data.bvg = BVG("Seesener Str. (Berlin)", limit=4)

    # load all rules
    Data.active_rules.append(Rule(tname="Bewässerungsregel (9 und 19 Uhr)", rule_logic=watering_rule, sleep_time=50))

    # start the webserver and configure logging
    cherrypy.engine.unsubscribe('graceful', cherrypy.log.reopen_files)
    logging.config.dictConfig(log_conf)
    webserver = Webserver()
    cherrypy.tree.mount(webserver.socket, '/socket', conf)
    cherrypy.tree.mount(webserver.rule, '/rule', conf)
    cherrypy.tree.mount(webserver.additional_information, '/additional_information', conf)
    cherrypy.quickstart(webserver, '/', conf)


#!/usr/bin/env python

# Dependencies:
# opencv, do (pip install opencv-python)
# skimage, do (sudo)
# termcolor, do (pip install termcolor)
# tqdm, do (pip install tqdm)

# TODO:
# Clean print statements
# Global step only loss/epoch on tensorboard
# Print Num parameters in model as a function
# Clean comments
# Confusion Matrix

import tensorflow as tf
import cv2
import sys
import os
import glob
import Misc.ImageUtils as iu
import random
from skimage import data, exposure, img_as_float
import matplotlib.pyplot as plt
from Network.NetworkIdentity import CIFAR10Identity
from Misc.MiscUtils import *
import numpy as np
import time
import argparse
import shutil
from StringIO import StringIO
import string
from termcolor import colored, cprint
import math as m
from tqdm import tqdm

# Don't generate pyc codes
sys.dont_write_bytecode = True

OutSize = [65, 65, 2]

def SetupAll(BasePath):
    """
    Inputs:
    BasePath is the base path where Images are saved without "/" at the end
    Outputs:
    DirNames - Full path to all image files without extension
    Train/Val/Test - Idxs of all the images to be used for training/validation (held-out testing in this case)/testing
    Ratios - Ratios is a list of fraction of data used for [Train, Val, Test]
    CheckPointPath - Path to save checkpoints/model
    OptimizerParams - List of all OptimizerParams: depends on Optimizer
    SaveCheckPoint - Save checkpoint every SaveCheckPoint iteration in every epoch, checkpoint saved automatically after every epoch
    ImageSize - Size of the image
    NumTrain/Val/TestSamples - length(Train/Val/Test)
    NumTestRunsPerEpoch - Number of passes of Val data with MiniBatchSize
    Train/Val/TestLabels - Labels corresponding to Train/Val/Test
    """
    # Setup DirNames
    DirNamesTrain, DirNamesTest =  SetupDirNames(BasePath)

    # Read and Setup Labels
    LabelsPathTrain = './TxtFiles/LabelsTrain.txt'
    LabelsPathTest = './TxtFiles/LabelsTest.txt'
    TrainLabels, TestLabels = ReadLabels(LabelsPathTrain, LabelsPathTest)

    # Setup Neural Net Params
    CheckPointPath = '../Checkpoints/' # Path to save checkpoints
    # If CheckPointPath doesn't exist make the path
    if(not (os.path.isdir(CheckPointPath))):
       os.makedirs(CheckPointPath)

    # List of all OptimizerParams: depends on Optimizer
    # For ADAM Optimizer: [LearningRate, Beta1, Beta2, Epsilion]
    UseDefaultFlag = 0 # Set to 0 to use your own params, do not change default parameters
    if UseDefaultFlag:
        # Default Parameters
        OptimizerParams = [1e-3, 0.9, 0.999, 1e-8]
    else:
        # Custom Parameters
        OptimizerParams = [1e-4, 0.9, 0.999, 1e-8]

    # Save checkpoint every SaveCheckPoint iteration in every epoch, checkpoint saved automatically after every epoch
    SaveCheckPoint = 100
    # Number of passes of Val data with MiniBatchSize
    NumTestRunsPerEpoch = 5

    # Image Input Shape
    ImageSize = [32, 32]
    NumTrainSamples = len(DirNamesTrain)
    NumTestSamples = len(DirNamesTest)
    return DirNamesTrain, DirNamesTest, CheckPointPath, OptimizerParams,\
        SaveCheckPoint, ImageSize, NumTrainSamples, NumTestSamples,\
        NumTestRunsPerEpoch, TrainLabels, TestLabels

def ReadLabels(LabelsPathTrain, LabelsPathTest):
    if(not (os.path.isfile(LabelsPathTrain))):
        print('ERROR: Train Labels do not exist in '+LabelsPathTrain)
        sys.exit()
    else:
        TrainLabels = open(LabelsPathTrain, 'r')
        TrainLabels = TrainLabels.read()
        TrainLabels = map(float, TrainLabels.split())
        # TrainLabels = tf.cast(TrainLabels, tf.int32)

    if(not (os.path.isfile(LabelsPathTest))):
        print('ERROR: Test Labels do not exist in '+LabelsPathTest)
        sys.exit()
    else:
        TestLabels = open(LabelsPathTest, 'r')
        TestLabels = TestLabels.read()
        TestLabels = map(float, TestLabels.split())
        # TestLabels = tf.cast(TestLabels, tf.int32)

    return TrainLabels, TestLabels

def SetupDirNames(BasePath):
    """
    Inputs:
    BasePath is the base path where Images are saved without "/" at the end
    Outputs:
    Writes a file ./TxtFiles/DirNames.txt with full path to all image files without extension
    """
    # Don't execute if file exists
    if(not (os.path.isfile('./TxtFiles/DirNamesTrain.txt'))):
        DirNamesTrain = open('./TxtFiles/DirNamesTrain.txt', 'w')

        CurrPath = BasePath + '/Train/'
        NumImagesTrain = len(glob.glob(CurrPath+'*.png'))
        for ImageNum in range(1, NumImagesTrain+1):
            DirNamesTrain.write(CurrPath+str(ImageNum)+'\n')

        DirNamesTrain.close()

    else:
        print('WARNING: DirNamesTrain.txt File exists')
        # Read DirNames once processed
        DirNamesTrain = ReadDirNames('./TxtFiles/DirNamesTrain.txt')

    if(not (os.path.isfile('./TxtFiles/DirNamesTest.txt'))):
        DirNamesTest = open('./TxtFiles/DirNamesTest.txt', 'w')

        CurrPath = BasePath + '/Test/'
        NumImagesTest = len(glob.glob(CurrPath+'*.png'))
        for ImageNum in range(1, NumImagesTest+1):
            DirNamesTest.write(CurrPath+str(ImageNum)+'\n')

        DirNamesTest.close()

    else:
        print('WARNING: DirNamesTest.txt File exists')
        # Read DirNames once processed
        DirNamesTest = ReadDirNames('./TxtFiles/DirNamesTest.txt')

    return DirNamesTrain, DirNamesTest

def PerturbImage(I1, PerturbNum):
    """
    Data Augmentation
    Inputs:
    I1 is the input image
    PerturbNum choses type of Perturbation where it ranges from 0 to 5
    0 - No perturbation
    1 - Random gaussian Noise
    2 - Random hue shift
    3 - Random saturation shift
    4 - Random gamma shift
    Outputs:
    Perturbed Image I1
    """
    if(PerturbNum == 0):
        pass
    elif(PerturbNum == 1):
        I1 = iu.GaussianNoise(I1)
    elif(PerturbNum == 2):
        I1 = iu.ShiftHue(I1)
    elif(PerturbNum == 3):
        I1 = iu.ShiftSat(I1)
    elif(PerturbNum == 4):
        I1 = iu.Gamma(I1)

    return I1

def ReadDirNames(Path):
    """
    Inputs:
    Path is the path of the file you want to read
    Outputs:
    DirNames is the data loaded from ./TxtFiles/DirNames.txt which has full path to all image files without extension
    """
    # Read text files
    DirNames = open(Path, 'r')
    DirNames = DirNames.read()
    DirNames = DirNames.split()
    return DirNames

def GenerateBatch(DirNamesTrain, TrainLabels, ImageSize, MiniBatchSize, PerEpochCounter):
    """
    Inputs:
    DirNames - Full path to all image files without extension
    NOTE that Train can be replaced by Val/Test for generating batch corresponding to validation (held-out testing in this case)/testing
    TrainLabels - Labels corresponding to Train
    NOTE that TrainLabels can be replaced by Val/TestLabels for generating batch corresponding to validation (held-out testing in this case)/testing
    ImageSize - Size of the Image
    MiniBatchSize is the size of the MiniBatch
    Outputs:
    I1Batch - Batch of I1 images after standardization and cropping/resizing to ImageSize
    HomeVecBatch - Batch of Homing Vector labels
    """
    I1Batch = []
    LabelBatch = []

    ImageNum = 0
    # RandIdxAll = range(PerEpochCounter*MiniBatchSize,(PerEpochCounter+1)*MiniBatchSize)
    # count = 0
    while ImageNum < MiniBatchSize:
        # Generate random image
        RandIdx = random.randint(0, len(DirNamesTrain)-1)
        # RandIdx = RandIdxAll[count]

        RandImageName = DirNamesTrain[RandIdx]+'.png'
        RandImageNameWithoutExt = DirNamesTrain[RandIdx]
        RandImageNum = RandImageNameWithoutExt.split('/')
        CurrPath = '/'.join(map(str, RandImageNum[0:-1]))+'/'
        RandImageNum = int(RandImageNum[-1])
        ImageNum += 1

        I1 = cv2.imread(RandImageName)

        # Always get a random crop to fit the size of the network
        # I1 = iu.RandomCrop(I1, ImageSize)

        # Apply a random perturbation
        # PerturbNum = random.randint(0, 5)
        # I1 = PerturbImage(I1, PerturbNum)

        # Standardize Inputs as given by Inception v3 paper
        # MAYBE: Find Mean of Dataset or use from ImageNet
        # MAYBE: Normalize Dataset
        # https://stackoverflow.com/questions/42275815/should-i-substract-imagenet-pretrained-inception-v3-model-mean-value-at-inceptio
        I1S = iu.StandardizeInputs(np.float32(I1))
        Label = np.ones(OutSize)#[0:8,0:8#convertToOneHot(TrainLabels[RandIdx], 10)

        # Append All Images and Mask
        I1Batch.append(I1S)
        LabelBatch.append(Label)
        # count += 1

        # print(np.shape(LabelBatch))
        # z = input('z')

    return I1Batch, LabelBatch

def PrettyPrint(NumEpochs, DivTrain, MiniBatchSize, NumTrainSamples, NumTestSamples, LatestFile):
    """
    Prints all stats with all arguments
    """
    print('Number of Epochs Training will run for ' + str(NumEpochs))
    print('Factor of reduction in training data is ' + str(DivTrain))
    print('Mini Batch Size ' + str(MiniBatchSize))
    print('Number of Training Images ' + str(NumTrainSamples))
    print('Number of Testing Images ' + str(NumTestSamples))
    if LatestFile is not None:
        print('Loading latest checkpoint with the name ' + LatestFile)

def Accuracy(Pred, GT):
    """
    Inputs:
    HomingVecPred is the output of the neural network
    HomingVecReal is the ground truth homing vector
    Outputs:
    NOT IMPLEMENTED YET!
    """
    return (np.sum(Pred==GT)*100.0)

def TrainOperation(ImgPH, LabelPH, DirNamesTrain, DirNamesTest, TrainLabels, TestLabels, NumTrainSamples, ImageSize,
                   NumEpochs, MiniBatchSize, OptimizerParams, SaveCheckPoint, CheckPointPath, NumTestRunsPerEpoch, DivTrain, LatestFile):
    """
    Inputs:
    ImgPH is the Input Image placeholder
    HomingVecPH is the ground truth  homing vector placeholder
    DirNames - Full path to all image files without extension
    Train/Val - Idxs of all the images to be used for training/validation (held-out testing in this case)
    Train/ValLabels - Labels corresponding to Train/Val
    NumTrain/ValSamples - length(Train/Val)
    ImageSize - Size of the image
    NumEpochs - Number of passes through the Train data
    MiniBatchSize is the size of the MiniBatch
    OptimizerParams - List of all OptimizerParams: depends on Optimizer
    SaveCheckPoint - Save checkpoint every SaveCheckPoint iteration in every epoch, checkpoint saved automatically after every epoch
    CheckPointPath - Path to save checkpoints/model
    NumTestRunsPerEpoch - Number of passes of Val data with MiniBatchSize
    DivTrain - Divide the data by this number for Epoch calculation, use if you have a lot of data
    LatestFile - Latest checkpointfile to continue training
    Outputs:
    Saves Trained network in CheckPointPath
    """
    # Predict output with forward pass
    prImg = CIFAR10Identity(ImgPH, ImageSize, MiniBatchSize)

    with tf.name_scope('Loss'):
        # Cross-Entropy Loss
        # 10 is used because of 10 classes
        loss = tf.reduce_mean(prImg-LabelPH)

    with tf.name_scope('Adam'):
        Optimizer = tf.train.AdamOptimizer(learning_rate=OptimizerParams[0], beta1=OptimizerParams[1],
                                           beta2=OptimizerParams[2], epsilon=OptimizerParams[3]).minimize(loss)
        #Optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-8).minimize(loss)
        #Optimizer = tf.train.MomentumOptimizer(learning_rate=1e-3, momentum=0.9, use_nesterov=True).minimize(loss)

    # Tensorboard
    LogsPath = 'Logs/'
    # Create a summary to monitor loss tensor
    tf.summary.scalar('LossEveryIter', loss)
    # Merge all summaries into a single operation
    MergedSummaryOP = tf.summary.merge_all()

    AllEpochLoss = [0.0]
    EachIterLoss = [0.0]
    # Setup Saver
    Saver = tf.train.Saver()

    # Open File
    EpochLossTxt = open('./TxtFiles/EpochLoss.txt', 'w')

    with tf.Session() as sess:
        if LatestFile is not None:
            Saver.restore(sess, CheckPointPath + LatestFile + '.ckpt')
            # Extract only numbers from the name
            StartEpoch = int(''.join(c for c in LatestFile.split('a')[0] if c.isdigit()))
            print('Loaded latest checkpoint with the name ' + LatestFile + '....')
        else:
            sess.run(tf.global_variables_initializer())
            StartEpoch = 0
            print('New model initialized....')

        # Tensorboard
        Writer = tf.summary.FileWriter(LogsPath, graph=tf.get_default_graph())

        TotalTimeElapsed = 0.0
        TimerOverall = tic()
        for Epochs in tqdm(range(StartEpoch, NumEpochs)):
            EpochLoss = 0.0
            Timer1 = tic()
            NumIterationsPerEpoch = int(NumTrainSamples/MiniBatchSize/DivTrain)
            for PerEpochCounter in tqdm(range(NumIterationsPerEpoch)):
                print('Epoch ' + str(Epochs) + ' PerEpochCounter ' + str(PerEpochCounter))
                Timer2 = tic()
                I1Batch, LabelBatch = GenerateBatch(DirNamesTrain, TrainLabels, ImageSize, MiniBatchSize, PerEpochCounter)
                FeedDict = {ImgPH: I1Batch, LabelPH: LabelBatch}
                _, LossThisBatch, Summary = sess.run([Optimizer, loss, MergedSummaryOP], feed_dict=FeedDict)

                # Tensorboard
                Writer.add_summary(Summary, Epochs*NumIterationsPerEpoch + PerEpochCounter)
                # If you don't flush the tensorboard doesn't update until a lot of iterations!
                Writer.flush()

                # Calculate and print Train accuracy (also called EpochLoss) every epoch
                EpochLoss += LossThisBatch

                # Save All losses
                EachIterLoss.append(LossThisBatch)

                TimeLastMiniBatch = toc(Timer2)

                # Print LossThisBatch
                print('LossThisBatch is  '+ str(LossThisBatch))

                # Save checkpoint every some SaveCheckPoint's iterations
                if PerEpochCounter % SaveCheckPoint == 0:
                    # Save the Model learnt in this epoch
                    SaveName =  CheckPointPath + str(Epochs) + 'a' + str(PerEpochCounter) + 'model.ckpt'
                    Saver.save(sess,  save_path=SaveName)
                    print(SaveName + ' Model Saved...')

                # Print timing information
                EstimatedTimeToCompletionThisEpoch = float(TimeLastMiniBatch)*float(NumIterationsPerEpoch-PerEpochCounter-1.0)
                EstimatedTimeToCompletionTotal = float(TimeLastMiniBatch)*float(NumIterationsPerEpoch-PerEpochCounter-1.0) +\
                                                 float(TimeLastMiniBatch)*float(NumIterationsPerEpoch-1.0)*float(NumEpochs-Epochs)
                TotalTimeElapsed = toc(TimerOverall)
                print('Percentage complete in total epochs ' + str(float(Epochs+1)/float(NumEpochs-StartEpoch+1)*100.0))
                print('Percentage complete in this Train epoch ' + str(float(PerEpochCounter)/float(NumIterationsPerEpoch)*100.0))
                print('Last MiniBatch took '+ str(TimeLastMiniBatch) + ' secs, time taken till now ' + str(TotalTimeElapsed) + \
                      ' estimated time to completion of this epoch is ' + str(EstimatedTimeToCompletionThisEpoch))
                print('Estimated Total time remaining is ' + str(EstimatedTimeToCompletionTotal))

            TimeLastEpoch = toc(Timer1)
            EstimatedTimeToCompletion = float(TotalTimeElapsed)/float(Epochs+1.0)*float(NumEpochs-Epochs-1.0)

            # Save Each Epoch loss
            AllEpochLoss.append(EpochLoss)

            # Save model every epoch
            SaveName = CheckPointPath + str(Epochs) + 'model.ckpt'
            Saver.save(sess, save_path=SaveName)
            print(SaveName + ' Model Saved...')

            # Calculate and print Test accuracy every epoch
            TestLoss = 0.0
            for PerTestEpochCounter in tqdm(range(NumTestRunsPerEpoch)):
                print('PerEpochCounter' + str(PerTestEpochCounter))
                I1Batch, LabelBatch = GenerateBatch(DirNamesTest, TestLabels, ImageSize, MiniBatchSize, PerEpochCounter)
                FeedDict = {ImgPH: I1Batch, LabelPH: LabelBatch}
                TestLossThisBatch = sess.run([loss], FeedDict)
                # Calculate and print Test accuracy (also called TestLoss) every epoch
                # TestLossThisBatch is a list so extract the value
                TestLoss += TestLossThisBatch[0]
                # Print LossThisBatch
                print('TestLossThisBatch is  ' + str(TestLossThisBatch[0]))
                # Print percentage complete in total epochs
                print('Percentage complete in Test epochs '+ str(float(PerTestEpochCounter)/float(NumTestRunsPerEpoch)*100.0))
            TestLoss /= (NumTestRunsPerEpoch)
            print('Test loss per Image ' + str(TestLoss))

            # Print timing information every epoch
            #print('Epoch ' + str(Epochs) + ' completed out of ' + str(NumEpochs) + ' loss:' + str(EpochLoss))
            PrintStatement = 'Epoch ' + str(Epochs) + ' completed out of ' + str(NumEpochs) + ' loss:' + str(EpochLoss)
            cprint(PrintStatement, 'yellow')
            print('Last Epoch took ' + str(TimeLastEpoch) +  ' secs, time taken till now, ' + str(TotalTimeElapsed) +\
                  ' estimated time to completion of this epoch is ' + str(EstimatedTimeToCompletion))
            # Save Epoch Loss to file
            # TODO: Make the filename a parameter
            # Create txt file if doesn't exist
            #if(not (os.path.isfile('./EpochLoss.txt'))):
            EpochLossTxt.write(str(EpochLoss)+'\n')
            print('------------------------------------------------')
    # Close txt file when done
    EpochLossTxt.close()

    # Tensorboard
            #tf.scalar_summary("EpochLoss", EpochLoss)

def main():
    """
    Inputs:
    None
    Outputs:
    Runs the Training and testing code based on the Flag
    """
    # TODO: Make LogDir
    # TODO: Make logging file a parameter
    # TODO: Time to complete print

    # Parse Command Line arguments
    Parser = argparse.ArgumentParser()
    Parser.add_argument('--BasePath', default='/home/ncs/Nitin/ncsdk/Nitin/SpectralCompression/CIFAR10', help='Base path of images, Default:/media/nitin/Research/Homing/DataMapping/AllFrames')
    Parser.add_argument('--NumEpochs', type=int, default=1, help='Number of Epochs to Train for, Default:200')
    Parser.add_argument('--DivTrain', type=int, default=5000, help='Factor to reduce Train data by per epoch, Default:1')
    Parser.add_argument('--MiniBatchSize', type=int, default=8, help='Size of the MiniBatch to use, Default:48')
    Parser.add_argument('--RemoveTxtFiles', type=int, default=0, help='Remove Text files and recreate them?, Default:0')
    Parser.add_argument('--LoadCheckPoint', type=int, default=0, help='Load Model from latest Checkpoint from CheckPointsPath?, Default:0')
    Args = Parser.parse_args()
    NumEpochs = Args.NumEpochs
    BasePath = Args.BasePath
    DivTrain = float(Args.DivTrain)
    MiniBatchSize = Args.MiniBatchSize
    RemoveTxtFiles = Args.RemoveTxtFiles
    LoadCheckPoint = Args.LoadCheckPoint

    if RemoveTxtFiles==1:
        shutil.copyfile('./TxtFiles/DirNamesTrain.txt', './TxtFiles/DirNamesTrainOLD.txt')
        shutil.copyfile('./TxtFiles/DirNamesTest.txt', './TxtFiles/DirNamesTestOLD.txt')
        shutil.copyfile('./TxtFiles/LabelsTrain.txt', './TxtFiles/LabelsTrainOLD.txt')
        shutil.copyfile('./TxtFiles/LabelsTest.txt', './TxtFiles/LabelsTestOLD.txt')
        os.remove('./TxtFiles/DirNamesTrain.txt')
        os.remove('./TxtFiles/DirNamesTest.txt')
        os.remove('./TxtFiles/LabelsTrain.txt')
        os.remove('./TxtFiles/LabelsTest.txt')
        print('Old DirNamesTrain, DirNamesTest, LabelsTrain, LabelsTest text files are saved as ./TxtFiles/DirNamesTrainOLD.txt, ./TxtFiles/DirNamesTestOLD.txt, ./TxtFiles/LabelsTrainOLD.txt and ./TxtFiles/LabelsTestOLD.txt')
        print('WARNING: DirNamesTrain, DirNamesTest, LabelsTrain and LabelsTest text files deleted')

    # Setup all needed parameters including file reading
    DirNamesTrain, DirNamesTest, CheckPointPath, OptimizerParams,\
    SaveCheckPoint, ImageSize, NumTrainSamples, NumTestSamples,\
    NumTestRunsPerEpoch, TrainLabels, TestLabels = SetupAll(BasePath)

    # Find Latest Checkpoint File
    if LoadCheckPoint==1:
        LatestFile = FindLatestModel(CheckPointPath)
    else:
        LatestFile = None

    # Pretty print stats
    PrettyPrint(NumEpochs, DivTrain, MiniBatchSize, NumTrainSamples, NumTestSamples, LatestFile)

    # Define PlaceHolder variables for Input and Predicted output
    ImgPH = tf.placeholder(tf.float32, shape=(MiniBatchSize, ImageSize[0], ImageSize[1], 3), name='Input')
    LabelPH = tf.placeholder(tf.float32, shape=(MiniBatchSize, OutSize[0], OutSize[1], OutSize[2]), name='Label')

    TrainOperation(ImgPH, LabelPH, DirNamesTrain, DirNamesTest, TrainLabels, TestLabels, NumTrainSamples, ImageSize,
                   NumEpochs, MiniBatchSize, OptimizerParams, SaveCheckPoint, CheckPointPath, NumTestRunsPerEpoch, DivTrain, LatestFile)

if __name__ == '__main__':
    main()


from django.http.response import HttpResponse
from django.shortcuts import render
from datetime import datetime
from django.utils.crypto import get_random_string
from urllib.parse import urlparse
from django.utils import timezone, dateparse
from .logger import log_pageview
from .models import LogEntry

COOKIE_NAME = 'visitor_id'
COOKIE_AGE = 3600 * 24 * 365

def create_visitor_id():
    return get_random_string(length=5, allowed_chars=u'abcdefghijklmnopqrstuvwxyz0123456789')

def get_page_from_url(url):
    parsed_url = urlparse(url)
    page = parsed_url.path

    if parsed_url.query:
        page += '?' + parsed_url.query

    return page

def contact(request):
    return render(request, "contact.html")

def track_get_image(request):
    image_data = open("images/transparent.gif", "rb").read()
    response = HttpResponse(image_data, content_type="image/gif")

    referer = request.META.get('HTTP_REFERER')

    if not referer:
        return response

    visitor_id = request.COOKIES.get(COOKIE_NAME)

    if not visitor_id:
        visitor_id = create_visitor_id()
        response.set_cookie(COOKIE_NAME, value=visitor_id, max_age=COOKIE_AGE)

    page = get_page_from_url(referer)

    log_pageview(page, visitor_id)

    return response

def report(request):
    from_datetime_string = request.GET.get("from_datetime")
    to_datetime_string = request.GET.get("to_datetime")

    log_entries = LogEntry.objects.all()
    if from_datetime_string:
        from_datetime = dateparse.parse_datetime(from_datetime_string)
        from_datetime = timezone.make_aware(from_datetime)
        log_entries = log_entries.filter(created_at__gte=from_datetime)

    if to_datetime_string:
        to_datetime = dateparse.parse_datetime(to_datetime_string)
        to_datetime = timezone.make_aware(to_datetime)
        log_entries = log_entries.filter(created_at__lte=to_datetime)

    context = {"log_entries": log_entries,
               "from_datetime": from_datetime_string, "to_datetime": to_datetime_string}
    return render(request, "report.html", context)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from urllib.parse import urlparse, urlunparse, ParseResult as URL

from casket import logger

from plantpot import Plantpot, bad_request, Redirect
from clients.kvstore import (
    insert as kv_insert,
    retrieve as kv_retrieve,
)
from clients.monstermac import sha256_monstermac
from schemas.oauth import NewLoginReq
from lib.tokens import build_login_token

URL_TIMEOUT = int(os.environ.get("PLANTPOT_OAUTH_URL_TIMEOUT", "120"))
LOGIN_TOKEN_SALT_PATH = os.environ.get('PLANTPOT_LOGIN_TOKEN_SALT_PATH',
                                       '/run/secrets/logintokensalt')
LOGIN_TOKEN_SALT = open(LOGIN_TOKEN_SALT_PATH, 'rb').read()

app = Plantpot('oauth')

@app.json(
    path="/login",
    methods=['POST'],
    pass_context=True,
    require_session_id=True,
    req_schema=NewLoginReq,
    resp_status="202 Created",
)
def new_login(ctx, body, session_id):
    url = urlparse(body['currentUrl'])
    kv_insert(ctx, 'oauth', {session_id: url}, URL_TIMEOUT)

@app.endpoint(
    path='/login',
    methods=['GET'],
    pass_context=True,
    require_session_id=True,
)
def login(ctx, session_id):
    url = kv_retrieve(ctx, 'oauth', session_id)[session_id].value
    if url is None:
        raise bad_request(
            "Missing Session Id",
            "no attempted oauth login for this session id found")

    login_id = sha256_monstermac(os.urandom(16))[:16]
    login_tk = build_login_token(LOGIN_TOKEN_SALT, login_id)

    if url.query:
        query = url.query + '&login_tk=' + login_tk
    else:
        query = 'login_tk=' + login_tk

    url = urlunparse(
        URL(
            url.scheme,
            url.netloc,
            url.path,
            url.params,
            query,
            url.fragment,
        ))

    return Redirect(url)


import pygame, json, math, socket

# Axes
ROLL_AXIS         = 0 # Xbox: left stick H
PITCH_AXIS        = 1 # Xbox: left stick V
HOVER_AXIS        = 2 # Xbox: left trigger
YAW_AXIS          = 3 # Xbox: right stick H
GAS_AXIS          = 4 # Xbox: right stick V

# Buttons
RESET_BUTTON      = 7 # Xbox: 'Start'
QUIT_BUTTON       = 6 # Xbox: 'Back'
TAKE_OFF_BUTTON   = 8 # Xbox: 'Xbox logo'

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

seq = 0
def send_state(state):
  global seq, sock
  seq += 1
  HOST, PORT = ('127.0.0.1', 5560)
  print('state is', json.dumps({'seq': seq, 'state': state}))
  sock.sendto(json.dumps({'seq': seq, 'state': state}), (HOST, PORT))

def main():
  pygame.init()

  n_joysticks = pygame.joystick.get_count()
  print('Joysticks: %i' % (n_joysticks,))

  if n_joysticks < 1:
    print('No joysticks found :(')
    return

  joystick = pygame.joystick.Joystick(0)
  joystick.init()

  print('Found: %s' % (joystick.get_name(),))

  print('Assuming an xbox controller. See top of file for details of change.')
  print('Use Back button to quit')

  state = {
      'roll': 0.0,
      'pitch': 0.0,
      'yaw': 0.0,
      'gas': 0.0,
      'take_off': False,
      'reset': False,
      'hover': True,
      };

  # Create a state timer
  STATE_TICK_EVENT = pygame.USEREVENT
  pygame.time.set_timer(STATE_TICK_EVENT, 50)

  while True:
    e = pygame.event.wait()
    if e.type == pygame.JOYBUTTONDOWN:
      if e.button == TAKE_OFF_BUTTON:
        state['take_off'] = True
      elif e.button == RESET_BUTTON:
        state['reset'] = True
      elif e.button == QUIT_BUTTON:
        print('Quitting')
        return
    elif e.type == pygame.JOYBUTTONUP:
      if e.button == TAKE_OFF_BUTTON:
        state['take_off'] = False
      elif e.button == RESET_BUTTON:
        state['reset'] = False
    elif e.type == pygame.JOYAXISMOTION:
      surface = None
      sign = 1.0

      if e.axis == ROLL_AXIS:
        surface = 'roll'
      elif e.axis == PITCH_AXIS:
        surface = 'pitch'
      elif e.axis == YAW_AXIS:
        surface = 'yaw'
      elif e.axis == GAS_AXIS:
        surface = 'gas'
        sign = -1.0
      elif e.axis == HOVER_AXIS:
        state['hover'] = e.value < -0.5

      if surface is not None:
        state[surface] = sign * e.value

    max_shift = 0.0
    for x in ('roll', 'pitch', 'yaw', 'gas'):
      max_shift = max(max_shift, abs(state[x]))

    state['hover'] = max_shift < 1e-1
    #if state['hover']:
    #  state['gas'] = 0.0

    send_state(state)

if __name__ == '__main__':
  main()


import cv2 as cv
import numpy as np
import sys
from math import acos, asin, cos, pi
from time import sleep
import serial
import time
import os

LOG_VIDEO = False
CAMERA_NUMBER = 0

# define thresholds
BALL = {
    'thresh': [np.array([0, 45, 15]), np.array([21, 255, 255])],
    'area': [30000, 39000],
    'loc_x': [750, 1100],
    }
BASKET = {
    'thresh': [np.array([0, 26, 81]), np.array([207, 255, 255])],
    'area': [2000, 3500],
    'loc_x': [0, 750],
    }

BLOB_DATA = [BALL, BASKET]

# crop bounds
CROP = [[385, 182], [1467, 867]]
DIMENSIONS = (CROP[1][0] - CROP[0][0], CROP[1][1] - CROP[0][1])

# blur kernel
GAUS_KERNEL = np.ones((3, 3), np.float32)/15

# robot home position
HOME = [0, 65]

# aim time for the shoot
SHOOT_DELAY = 0.2
INFER_DELAY = 1.44

# tick frequency (used for timing between frames to get velocities in px/sec)
FREQUENCY = cv.getTickFrequency()

# kernel for morphological operations performed on the binary images
MORPH_KERNEL = np.ones((4, 4),np.uint8)

# Port connection variables
COM_PORT = "COM3"
BAUD = 115200
TIMEOUT = 0.1

# Information about servos in the form,
# [rest_point, scaling_factor (for accurate angles)]
# Last one is for the pen servo in the form, [up, down]
SERVO_CALIB = [
    [93, 0.8556],
    [80, 0.8556],
    [80, 20],
]

# maximum pixel value the robot can safely reach to (higher is more restricted)
MAX_PIX = 470

# number of increments used for robot commands
# higher number means more lag/slower speed, lower number means higher movement fidelity
INCREMENTS = 20

BASE_LOG_DIRECTORY = "D:\\basketball_logs"
LOG_DATA_FILENAME = "log.csv"

# log variables in the form, (heading, value). The input for the lambda function is vars()
LOG_VARS = [
    lambda x: x["current_time"],
    lambda x: x["vel"][0],
    lambda x: x["vel"][1],
    lambda x: np.std(x["vel_ave"][0]),
    lambda x: np.std(x["vel_ave"][1]),
    lambda x: x["basket_coord"][0],
    lambda x: x["basket_coord"][1],
    lambda x: x["pred_loc"][0],
    lambda x: x["pred_loc"][1],
    lambda x: x["ball_coord"][0],
    lambda x: x["ball_coord"][1],
    lambda x: x["m"],
    lambda x: x["c"],
]
LOG_VAR_HEADINGS = [
    "time",
    "vel_x",
    "vel_y",
    "vel_x_std",
    "vel_y_std",
    "basket_x",
    "basket_y",
    "predict_x",
    "predict_y",
    "ball_x",
    "ball_y",
    "shot_grad",
    "shot_int",
]

VIDEO_ENCODER = cv.VideoWriter_fourcc(*'XVID')
VID_EXTENSION = ".avi"
VID_FPS = 25.0

def end():
    """ End the program """
    cam.release()
    if LOG_VIDEO:
        video_out.release()
        fd.close()
    cv.destroyAllWindows()
    ser.close()
    sys.exit()

def write_servo(ser_obj, pin, val):
    ser_obj.write(chr(pin))
    ser_obj.write(chr(val))

def send_move(pixel_coord, absolute=False):
    if not absolute:
        coord = [0, 0]
        coord[0] = 20.88 + 0.001015 * pixel_coord[0] - 0.07991 * pixel_coord[1]
        coord[1] = 169.3 - 0.09383 * pixel_coord[0] - 0.01384 * pixel_coord[1]
    else:
        coord = pixel_coord

    theta = [0, 0]

    theta[1] = asin(coord[0] / float(42))
    a = coord[1] - 50 * cos(theta[1])
    theta[0] = asin((50 - a) / 38)
    theta[1] *= -1

    theta = [x * 180 / pi for x in theta]

    for i, angle in enumerate(theta):
        calib = SERVO_CALIB[i]
        write_servo(ser, i, int(calib[0] + calib[1] * angle))
        sleep(0.001)

def pen(activate):
    if activate:
        write_servo(ser, 2, 34)
        pass
    else:
        write_servo(ser, 2, 110)
        pass
    sleep(0.001)

cam = cv.VideoCapture(CAMERA_NUMBER)

cam.set(3, 1920)
cam.set(4, 1080)

prev_pos = [0, 0]
prev_tick = cv.getTickCount()

# vector of previous velocities for running average
vel_ave = [np.zeros(40, np.float32), np.zeros(40, np.float32)]
# bounds of the basket movement
bounds_ave = [
    [np.zeros(3, np.float32), np.zeros(3, np.float32)],
    [np.zeros(3, np.float32), np.zeros(3, np.float32)]
    ]
bounds = [[0, 0], [0, 0]]

# open serial port to the Arduino
ser = serial.Serial(COM_PORT, BAUD, timeout=TIMEOUT)
# wait for port to settle
sleep(2)

# move to home position and deactivate pen
send_move(HOME, absolute=True)
pen(0)

# number of frames since the last shot. Allows for some settling since last shot
shot = 0

# current (and previous frame) sign of the velocity vector
sign = [0, 0]
prev_sign = [0, 0]

# predicted location of basket after shooting
pred_loc = [0, 0]

# true when frames are recorded
record = False
video_out = None

if LOG_VIDEO:
    # create a unique log directory
    log_directory = os.path.join(BASE_LOG_DIRECTORY, str(int(time.time())))
    os.mkdir(log_directory)

    # create data log file
    fd = open(os.path.join(log_directory, LOG_DATA_FILENAME), 'w')
    for heading in LOG_VAR_HEADINGS:
        fd.write(heading + ",")
    fd.write("\n")

while(True):
    # quit if q is pressed
    if cv.waitKey(1) & 0xFF == ord('q'):
        end()

    # get frame and crop
    ret, frame = cam.read()
    frame = frame[CROP[0][1]:CROP[1][1], CROP[0][0]:CROP[1][0]]

    # make copy for imshowing at the end
    original = frame.copy()

    # apply blur
    frame = cv.filter2D(frame, -1, GAUS_KERNEL)

    # convert to hsv
    hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)

    # make binary image of ball and basket
    ball_bin = cv.inRange(hsv, BALL['thresh'][0], BALL['thresh'][1])
    basket_bin = cv.inRange(hsv, BASKET['thresh'][0], BASKET['thresh'][1])

    # copy images to keep originals for imshowing at the end
    # ball_bin_original = ball_bin.copy()
    # basket_bin_original = basket_bin.copy()

    # process binary images to retrieve contours of points of interest
    binaries = [ball_bin, basket_bin]
    poi_coords = []
    # contours = []
    for i in range(len(binaries)):
        # filter noise
        binaries[i] = cv.erode(binaries[i], MORPH_KERNEL, iterations=2)
        binaries[i] = cv.dilate(binaries[i], MORPH_KERNEL, iterations=3)

        # find contours
        _, new_contours, heirarchy = cv.findContours(binaries[i].copy(),
            cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

        coords = []
        # filter contours
        # filtered_contours = []
        for contour in new_contours:
            area = cv.contourArea(contour)
            if BLOB_DATA[i]['area'][0] < area < BLOB_DATA[i]['area'][1]:
                # filtered_contours.append(contour)
                moments = cv.moments(contour)
                centroid_x = int(moments['m10']/moments['m00'])
                centroid_y = int(moments['m01']/moments['m00'])
                if BLOB_DATA[i]['loc_x'][0] < centroid_x < BLOB_DATA[i]['loc_x'][1]:
                    coords = [centroid_x, centroid_y]
        # contours.append(filtered_contours)
        if coords == []:
            continue
        poi_coords.append(coords)

    # make contours frame to display contours
    # contours_frame = original.copy()
    # _ = cv.drawContours(contours_frame, contours[0], -1, (255,0,0), 3)
    # _ = cv.drawContours(contours_frame, contours[1], -1, (0,255,0), 3)

    if len(poi_coords) != 2:
        cv.imshow('points', frame)
        if record and LOG_VIDEO:
            video_out.write(original)
        # cv.imshow('contour', contours_frame)
        continue

    # extract ball and basket coords
    ball_coord = poi_coords[0]
    basket_coord = poi_coords[1]

    # get delta time
    delta_time = (cv.getTickCount() - prev_tick) / FREQUENCY
    # calc instantaneous basket velocity vector
    vel = [(x - y) / float(delta_time) for x, y in zip(prev_pos, basket_coord)]

    # add the calculated velocities to the average list
    for i in range(len(vel_ave)):
        vel_ave[i] = np.concatenate(([abs(vel[i])], vel_ave[i][:-1]))

    # predict location of basket after throwing
    for i in range(len(pred_loc)):
        pred_loc[i] = basket_coord[i] - int(INFER_DELAY * sign[i] * np.average(vel_ave[i]))

    # detect and store movement bounds
    for i in range(len(vel)):
        if vel[i] != 0:
            prev_sign[i] = sign[i]
            sign[i] = cmp(vel[i], 0)

            if prev_sign[i] != sign[i] and shot > 20:
                j = 0
                if prev_sign[i] > 0:
                    j = 1
                bounds_ave[i][j] = np.concatenate(([basket_coord[i]], bounds_ave[i][j][:-1]))
                bounds[i][j] = np.average(bounds_ave[i][j])

    # detect if bounds have been reached
    if np.average(vel_ave[1]) > 9:
        for i in range(len(bounds)):
            if pred_loc[i] > bounds[i][0] and np.average(vel_ave[i]) > 5:
                pred_loc[i] = int(2 * bounds[i][0] - pred_loc[i])
            elif pred_loc[i] < bounds[i][1] and np.average(vel_ave[i]) > 5:
                pred_loc[i] = int(2 * bounds[i][1] - pred_loc[i])

    prev_tick = cv.getTickCount()
    prev_pos = basket_coord[:]

    points_frame = original.copy()
    points_frame = cv.circle(points_frame, tuple(poi_coords[0]), 20, (0,0,255), -1)
    points_frame = cv.circle(points_frame, tuple(poi_coords[1]), 20, (0,255,0), -1)
    points_frame = cv.circle(points_frame, tuple(pred_loc), 20, (255,0,0), -1)

    points_frame = cv.circle(points_frame, tuple(ball_coord), 20, (0,255,255), -1)

    shot += 1

    if (np.average(vel_ave[1]) < 9 or (np.std(vel_ave[0]) < 50 and np.std(vel_ave[1]) < 130 and ball_coord[1]-5 < pred_loc[1] < ball_coord[1]+5 and np.std(bounds_ave[0][0]) < 30 and np.std(bounds_ave[0][1]) < 30 and np.std(bounds_ave[1][0]) < 30 and np.std(bounds_ave[1][1]) < 30)) and shot > 20:
        print("shoot {0}, {1}".format(ball_coord, pred_loc))

        m = (pred_loc[1] - ball_coord[1]) / float(pred_loc[0] - ball_coord[0])
        c = ball_coord[1] - m * ball_coord[0]

        time_step = SHOOT_DELAY / float(INCREMENTS)
        x_step = (MAX_PIX - ball_coord[0]) / float(INCREMENTS)
        x = ball_coord[0]

        send_move(ball_coord)
        pen(1)
        sleep(0.5)
        for i in range(INCREMENTS):
            if i == int(INCREMENTS * 0.60):
                pen(0)
            send_move([x, m * x + c])
            x += x_step
            sleep(time_step)
        pen(0)
        send_move(HOME, absolute=True)

        if LOG_VIDEO:
            # record logs
            current_time = str(int(time.time()))
            if video_out:
                video_out.release()
            video_out = cv.VideoWriter(os.path.join(log_directory, current_time + VID_EXTENSION), VIDEO_ENCODER, VID_FPS, DIMENSIONS)
            record = True

            current_vars = vars()
            for log_var in LOG_VARS:
                fd.write(str(log_var(current_vars)) + ",")
            fd.write("\n")

        shot = 0

    # show images
    # cv.imshow('ball', ball_bin)
    cv.imshow('basket', basket_bin)
    # cv.imshow('frame', frame)
    cv.imshow('points', points_frame)
    # cv.imshow('contour', contours_frame)


import os
from slack_sdk import WebClient
from slack_bolt.adapter.flask import SlackRequestHandler
from slack_bolt import App
from dotenv import find_dotenv, load_dotenv
from flask import Flask, request, render_template

import pinecone
from query_llm import query_similarity_search_QA_w_sources_OpenAI_Model

from slack_sdk.errors import SlackApiError

load_dotenv()
slack_client = WebClient(token=os.getenv("SLACK_BOT_TOKEN"))
response = slack_client.auth_test()
print(response["user_id"])

pinecone.init(
    api_key=str(os.environ['PINECONE_API_KEY']),
    environment=str(os.environ['PINECONE_ENV'])
)

app = App(token=os.environ["SLACK_BOT_TOKEN"])
flask_app = Flask(__name__)
handler = SlackRequestHandler(app)

# Decorator for handling direct bot message events
@app.event("message")
def handle_direct_message(event, say):
    if event.get("subtype") is None and event.get("channel_type") == "im":
        user_input = event["text"]
        user_id = event["user"]

        try:
            result = slack_client.conversations_history(channel=event["channel"], limit=16)
            chat_history = result["messages"]
            #print(chat_history)
        except SlackApiError as e:
            print("Error creating conversation: {}".format(e))

        n = len(chat_history)
        i = 1
        formattedChatHistory = []
        questionAndAnswer = {}
        while i < n:
            msg = chat_history[i]
            if "type" in msg and msg["type"] == "message" and "text" in msg:
                if "bot_id" in msg:
                    # case 1: there is an existing answer
                    if "answer" in questionAndAnswer:
                        formattedChatHistory.append(("", questionAndAnswer["answer"]))
                        questionAndAnswer = {"answer": msg["text"]}
                    # case 2: there is an existing question
                    elif "question" in questionAndAnswer:
                        formattedChatHistory.append((questionAndAnswer["question"], msg["text"]))
                        questionAndAnswer = {}
                    else: # case 3: no existing question or answer
                        questionAndAnswer = {"answer": msg["text"]}
                elif "client_msg_id" in msg:
                    # case 1: there is an existing answer
                    if "answer" in questionAndAnswer:
                        formattedChatHistory.append((msg["text"], questionAndAnswer["answer"]))
                        questionAndAnswer = {}
                    # case 2: there is an existing question
                    elif "question" in questionAndAnswer:
                        formattedChatHistory.append((questionAndAnswer["question"], ""))
                        questionAndAnswer = {"question": msg["text"]}
                    else: # case 3: no existing question or answer
                        questionAndAnswer = {"question": msg["text"]}

            i+=1
        formattedChatHistory.reverse()
        print(formattedChatHistory)
        result, chat_history_new = query_similarity_search_QA_w_sources_OpenAI_Model(user_input, formattedChatHistory)
        say(result)

@flask_app.route("/slack/events", methods=["POST"])
def slack_events():
    """
    Route for handling Slack events.
    This function passes the incoming HTTP request to the SlackRequestHandler for processing.

    Returns:
        Response: The result of handling the request.
    """
    if "type" in request.json and request.json["type"] == "url_verification":
        return request.json["challenge"]
    return handler.handle(request)

@flask_app.route("/", methods=["GET"])
def home():
    return render_template("index.html")

if __name__ == "__main__":
    # initialize pinecone
    pinecone.init(
        api_key=str(os.environ['PINECONE_API_KEY']),
        environment=str(os.environ['PINECONE_ENV'])
    )
    #chat_histories={}
    flask_app.run(port=3000)
    print("flask app running")


#Actividad 4
import csv

import sqlite3
from sqlite3 import Error

def conexion(filename = ":memory:"):
    try:
        con = sqlite3.connect(filename)
        print("Conexion realizada a ", filename)
    except Error:
        print(Error)
        con = None
    finally:
        return con

def insertaremple(con, dic):
    try:
        cur = con.cursor()

        cur.execute("insert into empleados values (?,?,?,?,?,?)", dic)
        con.commit()

    except sqlite3.IntegrityError as err:
        print("Error --> ", err )
        print("No se aniadieron los registros")

def importarcsv(con):

    cur = con.cursor()
    emplecsv = open("empleados.csv","w")
    cur.execute("SELECT * from empleados")
    rows = cur.fetchall()

    datos = [["ID,Nombre,Salario anual,Departamento,Categoria,Fecha de contratacion"]]
    datos.append(rows)
    with emplecsv:
        writer = csv.writer(emplecsv)
        writer.writerows(datos)

    emplecsv.close()
    con.commit()

def importeencsv(con):

    cur = con.cursor()

    cur.execute("SELECT distinct(departamento) from empleados")
    dep = cur.fetchall()
    dato = []

    for i in dep:
        cur.execute("SELECT distinct(categoria) from empleados where departamento = (?)", i)
        cat = cur.fetchall()
        for y in cat:

            cur.execute("SELECT sum(salario) from empleados where categoria = (?)", y)
            suel = cur.fetchall()
            importecsv = open("Resumen.csv","w")
            dato.append(i)
            dato.append(cat)
            dato.append(suel)

            with importecsv:
                writer = csv.writer(importecsv, delimiter=",")
                writer.writerows(dato)

    importecsv.close()

    con.commit()

def borrar(con):

    cur = con.cursor()

    cur.execute("delete from empleados")
    con.commit()


import cv2
import random
#for reading image -1 for og 0 for gs 1 for alpha
image = cv2.imread('assets/coca-cola-logo.png',-1)
#prints numpy array of pixels
print(image)
#prints height,width,channels(RGB)
print(image.shape)
#for first 100 rows
for i in range(100):
    #for all columns,shape[1] returns column no
    for j in range(image.shape[1]):
        image[i][j]=[ random.randint(0,255),random.randint(0,255),random.randint(0,255) ]

cv2.imshow("Image",image)
#for waiting till key pressed o=infinte
cv2.waitKey(0)
cv2.destroyAllWindows()


from django.contrib import admin
from django.contrib.admin import ModelAdmin
from .models import File, Directory

class DirectoryAdmin(ModelAdmin):
    list_display = [
        'parent',
        'path',
    ]

class FileAdmin(ModelAdmin):
    list_display = [
        'filename',
        'directory',
        'meta_index_date',
        'meta_track',
        'meta_track_total',
        'meta_title',
        'meta_artist',
        'meta_album',
        'meta_year',
        'meta_genre',
        'meta_duration',
    ]

admin.site.register(File, FileAdmin)
admin.site.register(Directory, DirectoryAdmin)


import math
from typing import Tuple

import numpy as np
import torch

def frustum2planes(frustum):
    planes = {}
    # normal towards inside
    # near
    a = frustum[3] - frustum[0]
    b = frustum[1] - frustum[0]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[0])
    planes["near"] = np.array([normal[0], normal[1], normal[2], d])

    # far
    a = frustum[5] - frustum[4]
    b = frustum[7] - frustum[4]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[4])
    planes["far"] = np.array([normal[0], normal[1], normal[2], d])

    # left
    a = frustum[5] - frustum[1]
    b = frustum[0] - frustum[1]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[1])
    planes["left"] = np.array([normal[0], normal[1], normal[2], d])

    # right
    a = frustum[3] - frustum[2]
    b = frustum[6] - frustum[2]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[2])
    planes["right"] = np.array([normal[0], normal[1], normal[2], d])

    # top
    a = frustum[4] - frustum[0]
    b = frustum[3] - frustum[0]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[0])
    planes["top"] = np.array([normal[0], normal[1], normal[2], d])

    # bottom
    a = frustum[2] - frustum[1]
    b = frustum[5] - frustum[1]
    normal = np.cross(a, b)
    d = -np.dot(normal, frustum[1])
    planes["bottom"] = np.array([normal[0], normal[1], normal[2], d])

    return planes

def frustum_culling(points, frustum):
    frustum_planes = frustum2planes(frustum)
    points = np.concatenate([points, np.ones((len(points), 1))], 1)
    flags = np.ones(len(points))
    for key, plane in frustum_planes.items():
        flag = np.dot(points, plane) >= 0
        flags = np.logical_and(flags, flag)

    return points[flags][:, :3]

def frustum_transform(frustum, transform):
    eight_points = np.concatenate([frustum, np.ones((8, 1))], 1).transpose()
    frustum = np.dot(transform, eight_points).transpose()
    return frustum[:, :3]

def generate_frustum(image_size, intrinsic_inv, depth_min, depth_max, transform=None):
    x = image_size[0]
    y = image_size[1]

    eight_points = np.array([[0 * depth_min, 0 * depth_min, depth_min, 1.0],
                             [0 * depth_min, y * depth_min, depth_min, 1.0],
                             [x * depth_min, y * depth_min, depth_min, 1.0],
                             [x * depth_min, 0 * depth_min, depth_min, 1.0],
                             [0 * depth_max, 0 * depth_max, depth_max, 1.0],
                             [0 * depth_max, y * depth_max, depth_max, 1.0],
                             [x * depth_max, y * depth_max, depth_max, 1.0],
                             [x * depth_max, 0 * depth_max, depth_max, 1.0]]).transpose()

    frustum = np.dot(intrinsic_inv, eight_points)

    if transform is not None:
        frustum = np.dot(transform, frustum)

    frustum = frustum.transpose()

    return frustum[:, :3]

def generate_frustum_volume(frustum, voxel_size):
    max_x = np.max(frustum[:, 0]) / voxel_size
    max_y = np.max(frustum[:, 1]) / voxel_size
    max_z = np.max(frustum[:, 2]) / voxel_size
    min_x = np.min(frustum[:, 0]) / voxel_size
    min_y = np.min(frustum[:, 1]) / voxel_size
    min_z = np.min(frustum[:, 2]) / voxel_size

    dim_x = math.ceil(max_x - min_x)
    dim_y = math.ceil(max_y - min_y)
    dim_z = math.ceil(max_z - min_z)

    camera2frustum = np.array([[1.0 / voxel_size, 0, 0, -min_x],
                               [0, 1.0 / voxel_size, 0, -min_y],
                               [0, 0, 1.0 / voxel_size, -min_z],
                               [0, 0, 0, 1.0]])

    return (dim_x, dim_y, dim_z), camera2frustum

def compute_camera2frustum_transform(intrinsic: torch.Tensor, image_size: Tuple, depth_min: float, depth_max: float,
                                     voxel_size: float) -> torch.Tensor:
    frustum = generate_frustum(image_size, torch.inverse(intrinsic), depth_min, depth_max)
    _, camera2frustum = generate_frustum_volume(frustum, voxel_size)
    camera2frustum = torch.from_numpy(camera2frustum).float()

    return camera2frustum


"""
This module imports data from files to db.
"""

import os, glob
import traceback
from sqlalchemy import delete
from muddery.common.utils.exception import MudderyError, ERR
from muddery.common.utils import readers
from muddery.server.database.worlddata_db import WorldDataDB
from muddery.server.utils.logger import logger

def import_file(fullname, file_type=None, table_name=None, clear=True, except_errors=False, **kwargs):
    """
    Import data from a data file to the db model

    Args:
        fullname: (string) file's full name
        file_type: (string) set file's type. If it's None, get the file's type from filename.
        table_name: (string) the type of the file. If it's None, the function will get
                   the file type from the extension name of the file.
        clear: (boolean) clear old data.
        except_errors: (boolean) except error records and load other records.
    """
    def get_field_types(model_obj, field_names):
        """
        Get field types by field names.

        type = 0    means common field
        type = 1    means Boolean field
        type = 2    means Integer field
        type = 3    means Float field
        type = 4    means ForeignKey field, not support
        type = 5    means ManyToManyField field, not support
        type = -1   means field does not exist
        """
        field_types = []
        for field_name in field_names:
            field_type = -1

            try:
                # get field info
                field = model_obj.__table__.columns[field_name]

                if field.type.python_type == bool:
                    field_type = 1
                elif field.type.python_type == int:
                    field_type = 2
                elif field.type.python_type == float:
                    field_type = 3
                else:
                    field_type = 0
            except Exception as e:
                field_type = -1
                logger.log_err("Field %s error: %s" % (field_name, e))

            field_types.append(field_type)

        return field_types

    def parse_record(field_names, field_types, values):
        """
        Parse text values to field values.
        """
        record = {}
        for item in zip(field_names, field_types, values):
            field_name = item[0]
            # skip "id" field
            if field_name == "id":
                continue

            field_type = item[1]
            value = item[2]

            try:
                # set field values
                if field_type == -1:
                    # not support this field
                    continue
                elif field_type == 0:
                    # default
                    record[field_name] = value
                elif field_type == 1:
                    # boolean value
                    if value:
                        upper = value.upper()
                        if upper == 'TRUE' or upper == 'T':
                            record[field_name] = True
                        elif upper == 'FALSE' or upper == 'F':
                            record[field_name] = False
                        else:
                            record[field_name] = (int(value) != 0)
                elif field_type == 2:
                    # interger value
                    if value:
                        record[field_name] = int(value)
                elif field_type == 3:
                    # float value
                    if value:
                        record[field_name] = float(value)
            except Exception as e:
                raise Exception("%s '%s' error: %s" % (field_name, value, e))

        return record

    def import_data(session, model, data_iterator):
        """
        Import data to a table.

        Args:
            model_obj: (model) model object.
            data_iterator: (list) data list.

        Returns:
            None
        """
        try:
            # read title
            titles = next(data_iterator)
            field_types = get_field_types(model, titles)

            # import values
            with session.begin():
                for index, values in enumerate(data_iterator):
                    # skip blank lines
                    if not "".join(values):
                        continue

                    try:
                        data = parse_record(titles, field_types, values)
                        record = model(**data)
                        session.add(record)
                        session.flush()
                    except Exception as e:
                        msg = "Import %s line %s error: %s" % (model.__tablename__, index + 2, e)
                        if except_errors:
                            print(msg)
                            logger.log_warn(msg)
                        else:
                            logger.log_err(msg)
                            raise MudderyError(ERR.import_data_error, msg)
        except StopIteration:
            # reach the end of file, pass this exception
            pass

    # separate name and ext name
    try:
        filename, ext_name = os.path.splitext(fullname)
        if not table_name:
            table_name = filename
        if not file_type:
            if ext_name:
                file_type = ext_name[1:].lower()
    except:
        pass

    # get model
    session = WorldDataDB.inst().get_session()
    model = WorldDataDB.inst().get_model(table_name)

    if clear:
        stmt = delete(model)
        session.execute(stmt)

    reader_class = readers.get_reader(file_type)
    if not reader_class:
        # Does support this file type.
        raise(MudderyError(ERR.import_data_error, "Unknown file type."))

    reader = reader_class(fullname)
    if not reader:
        # Does support this file type.
        raise(MudderyError(ERR.import_data_error, "Does not support this file type."))

    logger.log_debug("Importing %s" % table_name)
    try:
        import_data(session, model, reader)
    finally:
        reader.close()

def import_data_path(path, clear=True, except_errors=False):
    """
    Import data from path.

    Args:
        path: (string) data path.
        clear: (boolean) clear old data.
        except_errors: (boolean) except error records and load other records.
    """
    # import tables one by one
    tables = WorldDataDB.inst().get_tables()
    for table_name in tables:
        file_names = glob.glob(os.path.join(path, table_name) + ".*")

        if file_names:
            print("Importing %s" % file_names[0])
            import_file(file_names[0], table_name=table_name, clear=clear, except_errors=except_errors)

def import_table_path(path, table_name, clear=True, except_errors=False):
    """
    Import a table's data from a path.

    Args:
        path: (string) data path.
        table_name: (string) table's name.
        clear: (boolean) clear old data.
    """
    if clear:
        WorldDataDB.inst().clear_table(table_name)

    if not os.path.isdir(path):
        return

    for file_name in os.listdir(path):
        file_name = os.path.join(path, file_name)
        if os.path.isdir(file_name):
            # if it is a folder
            continue

        print("Importing %s" % file_name)
        try:
            import_file(file_name, table_name=table_name, clear=False, except_errors=except_errors)
        except Exception as e:
            print("Import error: %s" % e)


#!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: 099_data-classification.py
@time: 2023/8/11 21:36
@project: huawei-od-python
@desc: 099 数据分类
"""
from collections import defaultdict

def solve_method(c, b, nums):
    result = defaultdict(int)

    for num in nums:
        # 转成16进制
        hex_num = str(hex(num))
        # 转成4字节，位数不够，填充0
        hex_num = hex_num[2:].zfill(8)
        sum_ = 0
        for i in range(0, 8, 2):
            sum_ += int(hex_num[i: i + 2], 16)

        if sum_ % b < c:
            # 统计有效类型的个数
            result[sum_ % b] += 1

    # 返回类型最多的个数
    return max(result.values())

if __name__ == '__main__':
    nums = [256, 257, 258, 259, 260, 261, 262, 263, 264, 265]
    assert solve_method(3, 4, nums) == 3

    nums = [256, 257, 258, 259, 260, 261, 262, 263, 264, 265]
    assert solve_method(1, 4, nums) == 2


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
"""
(c) 2017 Ronan Delacroix
Job Manager sub module
:author: Ronan Delacroix
"""
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)

# Default values (overriden)
DATABASE_HOST = 'localhost'
DATABASE_PORT = 27017
DATABASE_NAME = 'jobmanager'

LOG_FILE = None

WEB_HOST = '0.0.0.0'
WEB_PORT = 5000
WEB_DEBUG = False