from app import db
from flask import render_template, url_for, flash, redirect, request
from app.courses.forms import CourseCreationForm , EnrollmentKeyForm
from flask_login import current_user, login_required
from app.models import User, Lecture ,Tutor, Student, Course
from werkzeug.urls import url_parse
from app.courses import courses
import random
import string

def randStr(chars = string.ascii_uppercase + string.digits, N=10):
	return ''.join(random.choice(chars) for _ in range(N))

@courses.route('/create-course' ,methods = ['GET','POST'])
@login_required
def create_course():
    form = CourseCreationForm()
    if form.validate_on_submit():
        course = Course(course_code=form.course_code.data,name=form.name.data,venue=form.venue.data,start_time=form.start_time.data,end_time=form.end_time.data,\
            day=form.day.data, key=form.key.data, number_of_tutors=form.number_of_tutors.data, lecturer=current_user.lecture)
        course.lecturer = current_user.lecture
        db.session.add(course)
        db.session.commit()
        return redirect(url_for('courses.my_courses'))
    return render_template('courses/create_course.html',title='Create a course',form=form)

# This function should allow the lecturer to create a new session for any of the courses
# they are lecturing
@courses.route('/create_session', methods = ['GET', 'POST'])
@login_required
def create_session():
    form = SessionRegForm(current_user.lecture.course)
    if form.validate_on_submit():
        session = Session(course = form.course.data, session_start = form.start_time.data, session_end = form.end_time.data, session_date = form.date.data)
        db.session.add(session)
        db.session.commit()
        return redirect(url_for('courses.view_sessions'))
    return render_template('courses/create_session.html',title='Create a session', form=form)

A = ["Session1", "Session2"]
B = ["Session Course", "Date", "start_time", "end_time"]
# Lecturer side
# This function should display the sesions created by the current lecturer
# A nd B are mockup items to test the view
@courses.route('/view_sessions')
@login_required
def view_session():
    return render_template('courses/view_sessions.html',title='View sessions', A=A, B=B)

A = ["Session1", "Session2"]
B = ["Session Course", "Date", "start_time", "end_time", "OTP"]
# This fuunction should search if there are sessions for the current
# tutor by checking if the are not any sessions available for the courses
# the tutor is registered for. When the tutor has an OTP already just reload page.
#
@courses.route('/view_sessions_tutor')
@login_required
def view_sessions_tutor():
    form =  GenerateOTP()
    return render_template('courses/view_sessions_tutor.html',title='View sessions', A=A, B=B, form=form)

@courses.route('/my-courses')
@login_required
def my_courses():
    return render_template('courses/my_courses.html',title='My courses')

@courses.route('/explore')
@login_required
def explore():
    courses = Course.query.all()
    return render_template('courses/explore.html', title='explore courses', courses=courses)

@courses.route('/apply')
@login_required
def apply():
    courses = Course.query.all()
    return render_template('courses/apply.html', title='apply for a courses', courses=courses)

@courses.route('/<course_code>')
@login_required
def show_course_details(course_code):
    course = Course.query.filter_by(course_code=course_code).first_or_404()
    return render_template('courses/show_course_details.html',title='course details', course=course)

@courses.route('/enroll/<course_code>' , methods=['GET','POST'])
@login_required
def enroll_in_a_course(course_code):
    form = EnrollmentKeyForm()
    course = Course.query.filter_by(course_code=course_code).first_or_404()
    if form.validate_on_submit():
        if current_user.student:
            current_user.student.enrolled_courses.append(course)
            db.session.commit()
            return redirect(url_for('student.student_home'))
        elif current_user.tutor:
            current_user.tutor.enrolled_courses.append(course)
            db.session.commit()
            return redirect(url_for('tutor.tutor_courses'))
    if request.method == "GET":
        form.course_code.data = course_code
    return render_template('courses/enroll.html',title=f'enroll in {course_code}' , form=form , course_code=course_code)

@courses.route('/course/<course_code>' , methods=['POST', 'GET'])
@login_required
def edit_course_details(course_code):
    form = CourseCreationForm()
    course = Course.query.filter_by(course_code=course_code).first_or_404()
    if form.validate_on_submit():
        course.course_code = form.course_code.data
        course.name = form.name.data
        course.venue = form.venue.data
        course.start_time = form.start_time.data
        course.end_time = form.end_time.data
        course.day = form.day.data
        course.number_of_tutors = form.number_of_tutors.data
        course.key = form.key.data
        db.session.commit()
        return redirect(url_for('courses.show_course_details', course_code=course_code))
    elif request.method == "GET":
        form.course_code.data = course.course_code
        form.name.data = course.name
        form.venue.data = course.venue
        form.number_of_tutors.data = course.number_of_tutors
        form.key.data = course.key
        form.start_time.data = course.start_time
        form.end_time.data = course.end_time
        form.day.data = course.day
        form.key.data = course.key
    return render_template('courses/create_course.html', title = 'Edit course details', form = form)


import stds
from termcolor import colored

def recursive_selection(x):
    if x == 1:
        stds.tcp_scan()
    elif x == 2:
        stds.syn_scan()
    elif x == 3:
        stds.udp_scan()
    elif x == 4:
        stds.ack_scan()
    elif x == 5:
        stds.window_scan()
    elif x == 6:
        stds.fin_scan()
    elif x == 7:
        pass
    else:
        print('invalid choice')
        recursive_number()

def recursive_number():
    try:
        sel = int(input())
        recursive_selection(sel)
    except ValueError:
        print('wrong input')
        recursive_number()

print(colored('Just Another Port Scanner', 'magenta', attrs=['bold']))
print(colored('by a547b343', 'green', attrs=['bold']))
print()

scantypes = {
    'TCP scan' : 1,
    'SYN scan' : 2,
    'UDP scan': 3,
    'ACK scan': 4,
    'WINDOW scan': 5,
    'FIN scan': 6,
    'other' : 7,
}

other = {
    'XMAS scan' : 1,
    'NULL scan' : 2,
    'PROTOCOL scan': 3,
    'PROXY scan': 4,
    'IDLE scan': 5,
    'CAT scan': 6,
    'ICMP scan' : 7,
}

print('---------------------------')
print()

recursive_number()


# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import pymongo
from scrapy.conf import settings
from scrapy.exceptions import DropItem
from scrapy import log
import csv

'''
class QiushibaikePipeline(object):
    def process_item(self, item, spider):
        return item
'''
class MongoDBPipeline(object):
    def __init__(self):
        connection=pymongo.MongoClient(
            settings['MONGODB_SERVER'],
            settings['MONGODB_PORT']
        )
        db=connection[settings['MONGODB_DB']]
        self.collection=db[settings['MONGODB_COLLECTION']]
        out = open('res.csv','a', newline='')
        csv_write = csv.writer(out,dialect='excel')
        header = ['用户名','内容','赞数','评论数']
        csv_write.writerow(header)

    def process_item(self,item,spider):
        valid=True
        for data in item:
            if not data:
                valid=False
                raise DropItem('Missing{0}!'.format(data))
        if valid:
            self.collection.insert(dict(item))
            out = open('res.csv','a', newline='')
            csv_write = csv.writer(out,dialect='excel')
            res = [self.clear_data(str(item['username'])),self.clear_data(str(item['content'])),self.clear_data(str(item['vote'])),self.clear_data(str(item['comments']))]
            csv_write.writerow(res)
            log.msg('question added to mongodb database!',
                    level=log.DEBUG,spider=spider)
        return item

    def clear_data(self,str):
        temp = str
        temp = temp.replace('\\n', "")
        temp = temp.replace("(", "")
        temp = temp.replace(",)", "")
        temp = temp.replace("'", "")

        return temp


import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'core.views.index'),
    url(r'^search$', 'core.views.search'),
    url(r'^manager$', 'core.views.event_manager'),
    url(r'^mobile', include('mobile.urls')),

    #url(r'^', include('events.urls')),
    url(r'^', include('talks.urls')),

    url(r'^talks$', 'talks.views.talk_list'),
    url(r'^speakers$', 'core.views.speaker_list'),

    url(r'^', include('engagements.urls')),
    url(r'^', include('core.urls')),
    url(r'^', include('locations.urls')),
    url(r'^', include('blog.urls')),
    url(r'^feedback/', include('feedback.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    #url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^grappelli/', include('grappelli.urls')),
    url('^markdown/', include( 'django_markdown.urls')),
)

if settings.DEBUG:
    urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from PIL import Image
from bs4 import BeautifulSoup
import os
import requests

if not os.path.exists(os.path.abspath('pages/')):
    os.mkdir(os.path.abspath('pages/'))

if not os.path.exists(os.path.abspath('frames/')):
    os.mkdir(os.path.abspath('frames/'))

now_pages = 300

for i in range(2, now_pages + 1):
    url = 'http://skyboxcomic.com/'
    url_comics = 'http://skyboxcomic.com/comics/'

    path = os.path.abspath('pages/' + str(i) + '.jpg')

    print('Viewing:', i)

    if not os.path.exists(path):  # don't download if we have already page
        url_r = requests.get(url_comics + str(i))
        bs = BeautifulSoup(url_r.content)
        print('Downloading:', i, url + bs.find_all('img', {'id': 'comicimage'})[0]['src'])  # human readable
        r = requests.get(url + bs.find_all('img', {'id': 'comicimage'})[0]['src'], stream=True)  # get file stream
        with open(path, 'wb') as f:  # copy paste from stackoverflow, download file
            for chunk in r.iter_content(chunk_size=2048):
                if chunk:
                    f.write(chunk)
                else:
                    print(chunk)

num = 0

for j in range(2, now_pages + 1):
    image = '{}.jpg'.format(j)
    im = Image.open(os.path.abspath('pages/' + image))
    count = im.size[1] // 338

    # frames = []  # for gifs

    print('Working page:', image, 'Frames done:', num)

    for i in range(count):
        frame_path = os.path.abspath('frames/' + str(num) + '.jpg')
        if not os.path.exists(frame_path):
            box = (0, i * 338, im.size[0], (i + 1) * 338)
            region = im.crop(box)
            region = region.resize((region.size[0], region.size[1]))
            region.save(frame_path, quality=90)
        num += 1
        # region = region.convert(mode='P', palette=Image.ADAPTIVE)  # for gifs
        # frames.append(region)  # for gifs

    # frames[0].save('animation.gif', append_images=frames[1:], save_all=True, duration=250, loop=0)  # for gifs


from opengever.base.interfaces import IRoleAssignmentReportsStorage
from opengever.base.role_assignments import ASSIGNMENT_VIA_PROTECT_DOSSIER
from opengever.base.role_assignments import ASSIGNMENT_VIA_SHARING
from opengever.base.role_assignments import RoleAssignmentManager
from opengever.base.storage import STATE_IN_PROGRESS
from opengever.base.storage import STATE_READY
from opengever.nightlyjobs.provider import NightlyJobProviderBase
from plone import api
from zope.component.hooks import getSite
from zope.component.hooks import setSite
import gc

class NightlyRoleAssignmentReports(NightlyJobProviderBase):

    def __init__(self, context, request, logger):
        super(NightlyRoleAssignmentReports, self).__init__(context, request, logger)

        self.storage = IRoleAssignmentReportsStorage(self.context)
        self.catalog = api.portal.get_tool('portal_catalog')

    def __iter__(self):
        return iter([el for el in self.storage.list() if el['state'] == STATE_IN_PROGRESS])

    def __len__(self):
        return len([el for el in self.storage.list() if el['state'] == STATE_IN_PROGRESS])

    def collect_garbage(self, site):
        # In order to get rid of leaking references, the Plone site needs to be
        # re-set in regular intervals using the setSite() hook. This reassigns
        # it to the SiteInfo() module global in zope.component.hooks, and
        # therefore allows the Python garbage collector to cut loose references
        # it was previously holding on to.
        setSite(getSite())

        # Trigger garbage collection for the cPickleCache
        site._p_jar.cacheGC()

        # Also trigger Python garbage collection.
        gc.collect()

        # (These two don't seem to affect the memory high-water-mark a lot,
        # but result in a more stable / predictable growth over time.
        #
        # But should this cause problems at some point, it's safe
        # to remove these without affecting the max memory consumed too much.)

    def run_job(self, job, interrupt_if_necessary):
        principalid = job['principal_id']
        reportid = job['report_id']
        items = []

        # if Anonymous or Authenticated have View permission,
        # no other users are set in allowedRolesAndUsers
        brains = self.catalog.unrestrictedSearchResults(
            sort_on='path',
            portal_type=['opengever.dossier.businesscasedossier',
                         'opengever.repository.repositoryfolder',
                         'opengever.repository.repositoryroot'],
            allowedRolesAndUsers=[u'user:{}'.format(principalid), 'Authenticated', 'Anonymous'])

        self.logger.info("Complete report %r" % reportid)

        for i, brain in enumerate(brains):
            if i % 5000 == 0:
                self.collect_garbage(self.context)
            obj = brain.getObject()
            assignments = RoleAssignmentManager(obj).get_assignments_by_principal_id(principalid)
            manual_assignments = [
                assignment for assignment in assignments
                if assignment.cause in [ASSIGNMENT_VIA_SHARING,
                                        ASSIGNMENT_VIA_PROTECT_DOSSIER]]
            if manual_assignments:
                roles = filter(lambda r: r != 'Owner', manual_assignments[0].roles)
                if roles:
                    items.append({'UID': obj.UID(), 'roles': roles})

        report_data = {'state': STATE_READY, 'items': items}
        self.storage.update(reportid, report_data)


import asyncio
import random
from typing import Dict, List, Optional, Tuple, Union

import aiohttp

sources = [
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.A-B",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.C",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.D-F",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.G-K",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.L-O",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.P-R",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.S",
    "http://w3.usf.edu/FreeAssociation/AppendixA/Cue_Target_Pairs.T-Z"
]
"""
Details:
http://w3.usf.edu/FreeAssociation/AppendixA/index.html

0  CUE     Normed Word
1  TARGET  Response to Normed Word
2  NORMED? Is Response Normed?
3  #G      Group size
4  #P      Number of Participants Producing Response
5  FSG     Forward Cue-to-Target Strength
6  BSG     Backward Target-to-Cue Strength
7  MSG     Mediated Strength
8  OSG     Overlapping Associate Strength
9  #M      Number of Mediators
10 MMIA    Number of Non-Normed Potential Mediating Associates
11 #O      Number of Overlaping Associates
12 OMIA    Number of Non-Normed Overlapping Associates
13 QSS     Cue: Set Size
14 QFR     Cue: Frequency
15 QCO     Cue: Concreteness
16 QH      Cue is a Homograph?
17 QPS     Cue: Part of Speech
18 QMC     Cue: Mean Connectivity Among Its Associates
19 QPR     Cue: Probability of a Resonant Connection
20 QRSG    Cue: Resonant Strength
21 QUC     Cue: Use Code
22 TSS     Target: Set Size
23 TFR     Target: Frequency
24 TCON    Target: Concreteness
25 TH      Target is a Homograph?
26 TPS     Target: Part of Speech
27 TMC     Target: Mean Connectivity Among Its Associates
28 TPR     Target: Probability of a Resonant Connection
29 TRSG    Target: Resonant Strength
30 TUC     Target: Use Code

Parts of Speech
N   Noun
V   Verb
AJ  Adjective
AD  Adverb
P   Pronoun
PP  Preposition
I   Interjection
C   Conjunction
"""

class association:
    def __init__(self, data: List[str]):
        self.cue = data[0]
        self.target = data[1]
        self.FSG = float(data[5])
        self.QPS = data[17]
        self.TPS = data[26]

    def __str__(self):
        return f"{self.cue} ({self.QPS}) -> {self.target} ({self.TPS}): {self.FSG}"

    def __repr__(self):
        return f"association({self.__str__()})"

def _parseResponse(response: str, assocData: Dict[str, List[str]], posData: Dict[str, List[str]]):
    passedCSVHeader = False
    for _line in response.splitlines():
        if not _line.startswith("<") and _line.strip() != "":
            if not passedCSVHeader:
                passedCSVHeader = True
                continue
            # _line = _line.replace("¥", "0")
            linedata = _line.split(",")
            linedata = [i.strip() for i in linedata]
            assoc = association(linedata)
            if assoc.QPS not in posData:
                posData[assoc.QPS] = []

            if assoc.cue in assocData:
                assocData[assoc.cue].append(assoc)
            else:
                assocData[assoc.cue] = [assoc]
                # First time we've encountered this cue, so add it to the POS data as well
                posData[assoc.QPS].append(assoc.cue)

async def _loadURL(url: str, assocData: Dict[str, List[str]], posData: Dict[str, List[str]], session: aiohttp.ClientSession):
    print(f"{url}: Downloading")
    response = await session.get(url)
    print(f"{url}: Parsing")
    _parseResponse(await response.text(), assocData, posData)
    print(f"{url}: Done")

async def load() -> Tuple[Dict[str, List[association]], Dict[str, List[str]]]:
    """
    Does all the loading of data.
    Returns two dictionaries: (associations, pos)

    Associations contains the associations for every word.
    POS contains a dict of parts of speech and every cue found that matches.
    """
    _assocs: Dict[str, List[association]] = {}
    _pos: Dict[str, List[str]] = {}
    session = aiohttp.ClientSession()
    await asyncio.gather(*[_loadURL(url, _assocs, _pos, session) for url in sources])
    return (_assocs, _pos)

assocData, posData = asyncio.run(load())
print("Finished loading word associations")

def getAssociations(cue: str, pos: Optional[str] = None) -> List[association]:
    """
    Gets the associations for a given part of speech (see above).
    If pos is None, all parts of speech will be accepted.
    """
    if cue.upper() not in assocData:
        return []
    associations: List[association] = []
    for assoc in assocData[cue.upper()]:
        if pos is None or assoc.TPS == pos.upper():
            associations.append(assoc)
    return associations

class cumulativeAssociation:
    def __init__(self, target: str, TPS: str, cues: Dict[str, float] = {}):
        self.target = target
        self.TPS = TPS
        self.cues = cues

    @property
    def FSG(self) -> float:
        return sum(self.cues.values())

    def __str__(self):
        return f"{self.target} ({self.TPS}): {self.FSG} {self.cues}"

    def __repr__(self):
        return f"cumulativeAssociation({self.__str__()})"

def getCumulativeAssociations(cues: List[str], pos: Optional[str] = None) -> List[cumulativeAssociation]:
    associations: Dict[str, cumulativeAssociation] = {}
    for cue in cues:
        cAssocs = getAssociations(cue.upper(), pos)
        for cAssoc in cAssocs:
            if cAssoc.target in associations:
                associations[cAssoc.target].cues[cAssoc.cue] = cAssoc.FSG
            else:
                associations[cAssoc.target] = cumulativeAssociation(
                    cAssoc.target, cAssoc.TPS, {cAssoc.cue: cAssoc.FSG})
    return list(associations.values())

def randWeightedAssociation(cue: Union[str, List[str]], pos: Optional[str] = None) -> Union[association, cumulativeAssociation]:
    if isinstance(cue, str):
        associations = getAssociations(cue.upper(), pos)
    else:
        associations = getCumulativeAssociations(cue, pos)
    if len(associations) == 0:
        return None
    return random.choices(associations, [assoc.FSG for assoc in associations])[0]

def randUnweightedAssociation(cue: Union[str, List[str]], pos: Optional[str] = None) -> Union[association, cumulativeAssociation]:
    if isinstance(cue, str):
        associations = getAssociations(cue.upper(), pos)
    else:
        associations = getCumulativeAssociations(cue, pos)
    if len(associations) == 0:
        return None
    return random.choice(associations)

def randomWord(pos: Optional[str] = None) -> str:
    """
    Selects a random word of a given part of speech (see above).
    If pos is None, all parts of speech will be accepted.
    """
    if pos is None:
        return random.choice(random.choices(posData, [len(s) for s in posData.values()])[0])
    elif pos not in posData or len(posData[pos]) == 0:
        return None
    else:
        return random.choice(posData[pos])


import solc
from web3 import Web3, HTTPProvider
import json

source_file = './contracts/Coin.sol'
artifacts = solc.compile_files([source_file])

print(artifacts.keys())

coin_artifact = artifacts[source_file + ':' + 'Coin']

json.dump(
    coin_artifact['abi'],
    open('web/public/contract_interface.json', 'w'), indent=2)

web3 = Web3(HTTPProvider('http://localhost:8545'))

print('Owner:', web3.eth.accounts[0])

Coin = web3.eth.contract(abi=coin_artifact['abi'],
                         bytecode=coin_artifact['bin'])

tx_hash = Coin.deploy(transaction={'from': web3.eth.accounts[0] })
tx_receipt = web3.eth.getTransactionReceipt(tx_hash)

print('\nRECEIPT:')
for key, value in tx_receipt.items(): print('\t', key, value)

contract_address = tx_receipt['contractAddress']

json.dump(contract_address, open('web/public/contract_address.json', 'w'))


from django.urls import path

from . import views

app_name='blog'

urlpatterns=[
    path('',views.post_list,name='post_list'),
    path('<int:post_id>',views.post_detail,name='post_detail'),
    path('<int:post_id>/share/',views.post_share,name='post_share'),
    path('tag/<slug:tag_slug>/',views.post_list, name='post_list_by_tag'),
    path('search/', views.post_search, name='post_search'),
]


import re

from streamlink.plugin import Plugin, PluginError
from streamlink.stream import HLSStream
from streamlink.compat import unquote_plus, is_py3

QUALITY_WEIGHTS = {
    "src": 1080,
}

class DLive(Plugin):
    """
    Plugin for dlive.tv
    """

    _url_re = re.compile(r"https?://(?:www\.)?dlive\.tv/")
    _playback_re = re.compile(r"""(?<=playbackUrl":")(.+?)(?=")""")
    _livestream_re = re.compile(r""""livestream":null""")
    _username_re = re.compile(r"(?<=user:)(\w|-)+")

    @classmethod
    def can_handle_url(cls, url):
        return cls._url_re.match(url)

    @classmethod
    def stream_weight(cls, key):
        weight = QUALITY_WEIGHTS.get(key)
        if weight:
            return weight, "dlive"

        return Plugin.stream_weight(key)

    def _get_streams(self):
        res = self.session.http.get(self.url)

        m = self._playback_re.search(res.text)

        if m:
            hls_url = m.group(0)

            if is_py3:
                hls_url = bytes(unquote_plus(hls_url), "utf-8").decode(
                    "unicode_escape")
            else:
                hls_url = unquote_plus(hls_url).decode("unicode_escape")
        else:
            if self._livestream_re.search(res.text) is not None:
                raise PluginError('Stream is offline')

            m = self._username_re.search(res.text)
            if m:
                hls_url = "https://live.prd.dlive.tv/hls/live/{}.m3u8".format(
                    m.group(0))
            else:
                raise PluginError('Could not find username')

        return HLSStream.parse_variant_playlist(self.session, hls_url)

__plugin__ = DLive


#equipotential lines

import matplotlib.pyplot as plt
import numpy as np

#position of charges
pos = (-1.001, 0)
neg = (1.001, 0)
pos2 = (0, -1.001)
neg2 = (0, 1.001)
#magnitude of charge
Qneg = -1e-9
Qpos = 1e-9
#constant K
k = 9e9
#dimensions
min_neg = -2
max_pos = 2

#electric potential at point (x,y) due to a dipole
def E2(x, y):
    hyppos = np.hypot(x - pos[0], y - pos[1])
    hypneg = np.hypot(x - neg[0], y - neg[1])
    # E_potential = (k * Q / r)
    return k * Qneg / hypneg + k * Qpos / hyppos

#electric potential at point (x,y) due to 4 charges
def E4(x, y):
    hyppos = np.hypot(x - pos[0], y - pos[1])
    hypneg = np.hypot(x - neg[0], y - neg[1])
    hyppos2 = np.hypot(x - pos2[0], y - pos2[1])
    hypneg2 = np.hypot(x - neg2[0], y - neg2[1])
    # E_potential = (k * Q / r)
    return k * Qpos / hypneg + k * Qpos / hyppos + \
            k * Qneg / hypneg2 + k * Qneg / hyppos2

x = np.linspace(min_neg, max_pos, 1001)
y = np.linspace(min_neg, max_pos, 1001)
X, Y = np.meshgrid(x, y)
Z = E4(X, Y)

l = [1.8 ** x for x in range(-3, 9, 1)]
l = [-x for x in reversed(l)] + [0] + l
plt.contour(X, Y, Z, l, colors='black');
#plt.contour(X, Y, Z, l, cmap='RdGy');
plot = plt.contourf(X, Y, Z, l, cmap='BuPu')
plt.colorbar();
plt.show()


# -*- coding: utf-8 -*-

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('proso_user', '0004_userprofileproperty'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserQuestion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('identifier', models.SlugField()),
                ('lang', models.CharField(max_length=10)),
                ('content', models.TextField()),
                ('active', models.BooleanField(default=True)),
                ('answer_type', models.CharField(default='o', max_length=1, choices=[('c', 'closed'), ('m', 'mixed'), ('o', 'open')])),
                ('repeat', models.BooleanField(default=False)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserQuestionAnswer',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('open_answer', models.CharField(default=None, max_length=100, null=True, blank=True)),
                ('time', models.DateTimeField(auto_now_add=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserQuestionCondition',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('type', models.CharField(max_length=50)),
                ('value', models.CharField(max_length=50)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserQuestionEvent',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('type', models.CharField(max_length=50)),
                ('value', models.CharField(max_length=50)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserQuestionPossibleAnswer',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('identifier', models.SlugField()),
                ('active', models.BooleanField(default=True)),
                ('content', models.CharField(max_length=100)),
                ('question', models.ForeignKey(related_name='possible_answers', to='proso_user.UserQuestion')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='userquestionanswer',
            name='closed_answer',
            field=models.ForeignKey(default=True, blank=True, to='proso_user.UserQuestionPossibleAnswer', null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='userquestionanswer',
            name='question',
            field=models.ForeignKey(related_name='user_answers', to='proso_user.UserQuestion'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='userquestionanswer',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='userquestion',
            name='conditions',
            field=models.ManyToManyField(to='proso_user.UserQuestionCondition'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='userquestion',
            name='on_events',
            field=models.ManyToManyField(to='proso_user.UserQuestionEvent'),
            preserve_default=True,
        ),
    ]


#1 split the fasta files by genospecies
#2 run clonalframe (using the different species trees based on the concatenated genes)
#3 connect it to the rest of the pipeline
#4 code everything in the gwf manner
#5 update the github analysis
#6 write methodology in the draft
import pandas as pd
import numpy as np
import glob as glob
import os

def parse_pop_map(file_name = '/Users/PM/Desktop/PHD_incomplete/Bjarnicode/scripts/Rhizobium_soiltypes_new.txt'):
	from itertools import izip

	pop_map = {}
	t = pd.read_table(file_name)
	t = t.rename(columns=lambda x: x.strip())
	for strain_id, sara_id, origin, country in izip(t['Seq ID'], t['Strain ID'], t['Genospecies'], t['Origin2']):
		pop_map[str(strain_id)]={'sara_id': sara_id, 'genospecies':origin, 'country':country, 'origin2':origin}
	return pop_map

def parse_fasta(filename, stratify=True, genospecies=None, pop_dict=None):

	file = open(filename, 'r').read() #opening and reading the fasta file, putting it in a object called file
	file_separe = file.split('>') #spliting each entry by the >
	file_separe.remove('')
	parse_dict = {}
	header = []

	# Separating fasta files by genospecie
	if len(file_separe) == 196:

		for entry in file_separe:
			seq = entry.splitlines()
			header = seq[0] #these are the first elements of the list

			strain_name = header.split("|")[1]
			#print strain_name
			gene_name = header.split("|")[0]

			# Modifying header with sequence position
			header = strain_name

			genome_id = seq[0].split('|')[1]

			seq = ''.join(seq[1:]) #joining the sequences

			if stratify == True:
				if pop_dict[strain_name[0:4]]["genospecies"] == genospecies:
					parse_dict[header] = seq
			else:
				parse_dict[header] = seq
	return parse_dict

def write_fasta(tuple_fasta, directory):
	(fasta_name, dict_fasta) = tuple_fasta
	with open(directory+"{}".format(fasta_name), 'w') as f:
		for header, sequences in dict_fasta.items():
			f.write('>{}_{}\n'.format(fasta_name,header))
			chunks = [sequences[i:i+60] for i in range(0, len(sequences), 60)]
			for i in chunks:
				f.write('{}\n'.format(i))
		f.close()

pop_dict = parse_pop_map()

def split_fasta(genospecies, genospecies_dir, pop_dict=pop_dict):
	# Gene alignments:
	genes_path = [(f) for f in glob.glob("/Users/PM/Dropbox/Cavassim_et_al_2019_Rhizobium_data/group_alns/*.fna")]
	for i in genes_path:
		gene_name = os.path.basename(i)
		gene_dict = parse_fasta(i, genospecies=genospecies, pop_dict=pop_dict)
		if len(gene_dict.keys()) > 0:
			write_fasta((gene_name, gene_dict), directory=genospecies_dir)

split_fasta(pop_dict=pop_dict, genospecies="gsA", genospecies_dir="/Users/PM/Dropbox/Cavassim_et_al_2019_Rhizobium_data/")


from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView

from myapp import views

urlpatterns = [
	url(r'^$', 'myapp.views.index', name='home'),
	url(r'^contact/$',
			TemplateView.as_view(template_name='contact.html'),
			name='contact'),
	url(r'^about/$',
			TemplateView.as_view(template_name='about.html'),
			name='about'),
	url(r'^articles/(?P<slug>[-\w]+)/$',
        views.article_detail, name='article_detail'),
    url(r'^admin/', include(admin.site.urls)),
]


import numpy as np
import cv2
from skimage import filters

capL = cv2.VideoCapture('robotL.avi')
capR = cv2.VideoCapture('robotR.avi')
focal_lenght = 567.2  # in pixel
baseline = 92.226  # in mm
dim_kp = 30
h_stripe = 2
max_kp = []
# d4 = 2

# d3 = 2

# d2 = 2

# d1 = 2

# d0 = 2
dist = 3
dist_vect = np.ones((5,), dtype='int') * dim_kp
d_main = ((baseline * focal_lenght) / dist) * 0.001
d_main_object = d_main
d_main_foreground = d_main
dist_ob = dist
dist_fg = dist
print(d_main)
temp_dim = dim_kp
flag = False
n_square = 4
m_square = 4
min_disp = 0
max_disp = 64

if not capL.isOpened():
    print("Error opening video stream or file")

if not capR.isOpened():
    print("Error opening video stream or file")

sift = cv2.xfeatures2d.SIFT_create()

while capL.isOpened() and capR.isOpened():

    retL, frameL = capL.read()
    retR, frameR = capR.read()

    if retL is True and retR is True:
        # Capture frame-by-frame
        # Display the resulting frame
        cv2.rectangle(frameL, (int(frameL.shape[1] / 2) - dim_kp, int(frameL.shape[0] / 2) - dim_kp),
                      (int(frameL.shape[1] / 2) + dim_kp, int(frameL.shape[0] / 2) + dim_kp), 250, 1)
        cv2.rectangle(frameR, (int(frameR.shape[1] / 2) - dim_kp, int(frameR.shape[0] / 2) - dim_kp),
                      (int(frameR.shape[1] / 2) + dim_kp, int(frameR.shape[0] / 2) + dim_kp), 250, 1)
        centerL = frameL[int(frameL.shape[0] / 2) - dim_kp: int(frameL.shape[0] / 2) + dim_kp,
                  int(frameL.shape[1] / 2) - dim_kp:int(frameL.shape[1] / 2) + dim_kp]
        centerR = frameR[int(frameR.shape[0] / 2) - dim_kp: int(frameR.shape[0] / 2) + dim_kp,
                  int(frameR.shape[1] / 2) - dim_kp:int(frameR.shape[1] / 2) + dim_kp]
        total_grayL = cv2.cvtColor(frameL, cv2.COLOR_BGR2GRAY)
        total_intermediateL = cv2.equalizeHist(total_grayL)
        total_finalL = total_intermediateL
        grayL = cv2.cvtColor(centerL, cv2.COLOR_BGR2GRAY)
        intermediateL = cv2.equalizeHist(grayL)

        finalL = cv2.medianBlur(intermediateL, 5)
        # cv2.bilateralFilter(grayL, 5, 3, 3)

        # cv2.equalizeHist(intermediateL)

        # intermediateL

        # cv2.medianBlur(intermediateL, 5)

        # cv2.GaussianBlur(intermediateL, (3, 3), 3)
        grayR = cv2.cvtColor(centerR, cv2.COLOR_BGR2GRAY)
        intermediateR = cv2.equalizeHist(grayR)
        finalR = cv2.medianBlur(intermediateR, 5)
        # cv2.bilateralFilter(grayR, 5, 3, 3)

        # cv2.equalizeHist(intermediateR)

        # intermediateR

        # cv2.medianBlur(intermediateR, 5)
        info_frame = np.empty_like(finalL)
        H = frameL.shape[0]
        L = frameL.shape[1]
        #
        h = finalL.shape[0]
        l = finalL.shape[1]
        #
        off_x_L = (L / 2 - l / 2)
        # int(L/2)
        off_y_L = (H / 2 - h / 2)
        # int(H/2)
        off_x_R = off_x_L + frameL.shape[1]
        off_y_R = off_y_L
        # #     STATE OF ART FOUND OF CV2

        # stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)

        # disparity = stereo.compute(finalL, finalR)

        # d = disparity/255

        # #disparity = np.uint8(disparity)

        # cv2.imshow('title',disparity/255)

        # cv2.imshow('t1',finalL)

        # print('dentro')

        # center_tempL = frameL[int(frameL.shape[0] / 2) - dim: int(frameL.shape[0] / 2) + dim,

        #           int(frameL.shape[1] / 2) - dim:int(frameL.shape[1] / 2) + dim]

        # center_tempL = copy.deepcopy(centerL)

        # # center_tempR = frameR[int(frameR.shape[0] / 2) - dim: int(frameR.shape[0] / 2) + dim,

        # #           int(frameR.shape[1] / 2) - dim:int(frameR.shape[1] / 2) + dim]

        # center_tempR = copy.deepcopy(centerR)

        #

        # grayL = cv2.cvtColor(centerL, cv2.COLOR_BGR2GRAY)

        # intermediateL = cv2.equalizeHist(grayL)

        # finalL = cv2.medianBlur(intermediateL, 5)

        #

        # grayR = cv2.cvtColor(centerR, cv2.COLOR_BGR2GRAY)

        # intermediateR = cv2.equalizeHist(grayR)

        # finalR = cv2.medianBlur(intermediateR, 5)

        # #     DIVISION IN STRIPES BEFORE COMPUTING THE KEYPOINTS

        # image_stripesL = np.zeros((int(finalL.shape[1]/h_stripe), h_stripe, finalL.shape[0]), dtype='uint8')  # NxHxL where N = n of stripes, H = height of stripes, L = lenght of window

        # image_stripesR = np.zeros((int(finalR.shape[1] / h_stripe), h_stripe, finalR.shape[0]), dtype='uint8')

        # kpL = np.zeros((int(finalL.shape[1]/h_stripe)), dtype='object')

        # desL = np.zeros(int(finalL.shape[1]/h_stripe), dtype='object')

        # imgL = np.zeros((int(finalL.shape[1]/h_stripe), h_stripe, finalL.shape[0]), dtype='uint8')

        #

        # kpR = np.zeros((int(finalR.shape[1]/h_stripe)), dtype='object')

        # desR = np.zeros(int(finalR.shape[1]/h_stripe), dtype='object')

        # imgR = np.zeros((int(finalR.shape[1]/h_stripe), h_stripe, finalL.shape[0]), dtype='uint8')

        # distance = np.zeros((int(finalR.shape[1] / h_stripe), ), dtype='object')

        # maxL = 0

        # maxR = 0

        #

        # sift = cv2.xfeatures2d.SIFT_create()

        #

        # for i in range(int(finalL.shape[1]/h_stripe)):

        #     image_stripesL[i] = finalL[i*h_stripe:(i+1)*h_stripe, :]

        #     image_stripesR[i] = finalR[i * h_stripe:(i + 1) * h_stripe, :]

        #     kpL[i], desL[i] = sift.detectAndCompute(image_stripesL[i], None)

        #     kpR[i], desR[i] = sift.detectAndCompute(image_stripesR[i], None)

        #     try:

        #         distance[i] = np.zeros((desL[i].shape[0], desR[i].shape[0]))

        #         center_tempL[i*h_stripe:(i+1)*h_stripe,:,:] = cv2.drawKeypoints(image_stripesL[i], kpL[i], center_tempL[i], flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        #         center_tempR[i*h_stripe:(i+1)*h_stripe,:,:] = cv2.drawKeypoints(image_stripesR[i], kpR[i], center_tempR[i], flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        #         distance[i] = np.array(np.sqrt(np.sum((desL[i][:, np.newaxis, :] - desR[i][np.newaxis, :, :]) ** 2, axis=-1)))

        #     except(AttributeError):

        #         distance[i] = np.array([[1000000]])

        #     # if len(kpL[i]) > maxL:

        #     #     maxL = len(kpL[i])

        #     # if len(kpR[i]) > maxR:

        #     #     maxR = len(kpR[i])

        #

        # totalimageL = np.vstack([center_tempL[i*h_stripe:(i+1)*h_stripe,:,:] for i in range(int(finalL.shape[1]/h_stripe))])

        # totalimageR = np.vstack(

        #     [center_tempR[i * h_stripe:(i + 1) * h_stripe, :, :] for i in range(int(finalR.shape[1] / h_stripe))])

        # kptL = np.empty((sum([len([kpL[i] for i in range(int(finalL.shape[1]/h_stripe))])])), dtype='object')

        # kptR = np.empty((sum([len([kpR[i] for i in range(int(finalR.shape[1] / h_stripe))])])), dtype='object')

        # destL = []

        # destR = []

        # kptL = np.concatenate([kpL[i] for i in range(int(finalL.shape[1]/h_stripe))]).ravel()

        # kptR = np.concatenate([kpR[i] for i in range(int(finalR.shape[1] / h_stripe))]).ravel()

        #

        # destL.append([desL[i] for i in range(int(finalL.shape[1]/h_stripe))])

        # destR.append([desR[i] for i in range(int(finalR.shape[1] / h_stripe))])

        # # for i in range(int(finalL.shape[1] / h_stripe)):

        # distance[i,:,:] = np.array(np.sqrt(np.sum((desL[i][:, np.newaxis, :] - desR[i][np.newaxis, :, :]) ** 2, axis=-1)))

        # cv2.imshow('image_stripesL', totalimageL)

        # cv2.imshow('image_stripesR', totalimageR)

        # imgL = cv2.drawKeypoints(totalimageL, kptL[:], totalimageL, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # imgR = cv2.drawKeypoints(totalimageR, kptR[:], totalimageR, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # # cv2.imshow("skL", imgL)

        # # cv2.imshow("skR", imgR)

        # #     DETECT THE KPTS IN THE WHOLE IMAGES
        kpL, desL = sift.detectAndCompute(finalL, None)
        kpR, desR = sift.detectAndCompute(finalR, None)
        # draw key points detected

        # img2 = cv2.drawKeypoints(finalL, kp2, finalL, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # cv2.line(img2, (0, h_stripe), (img2.shape[1], h_stripe), (255,0,0))

        # cv2.imshow("grayframeL", img2)

        # img1 = cv2.drawKeypoints(finalR, kp1, finalR, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # cv2.imshow("grayframeR", img1)
        image_stripesL = np.zeros((int(finalL.shape[1] / h_stripe), h_stripe, finalL.shape[0]),
                                  dtype='uint8')  # NxHxL where N = n of stripes, H = height of stripes, L = lenght of window
        image_stripesR = np.zeros((int(finalR.shape[1] / h_stripe), h_stripe, finalR.shape[0]), dtype='uint8')
        kp_stripesL = []
        kp_stripesR = []
        des_stripesL = []
        des_stripesR = []
        # found, corners = cv2.findChessboardCorners(frameL, (6,8))

        # cv2.drawChessboardCorners(frameL, (6,8), corners, found)

        # if found == True:

        #     pt = (corners[0],corners[-1])

        #     cv2.circle(frameL,(pt[0][0][0],pt[0][0][1]),8,(0,255,0),1)

        #     cv2.circle(frameL,(pt[1][0][0],pt[1][0][1]),8,(0,255,0),1)

        #     l_chess = pt[1][0][0] - pt[0][0][0]

        #     h_chess = pt[1][0][1] - pt[0][0][1]

        #     l_chess_mm = (dist*l_chess)/focal_lenght

        #     h_chess_mm = (dist*h_chess)/focal_lenght

        #     print('ciao', l_chess_mm,h_chess_mm)

        #

        # cv2.imshow('f',frameL)

        # FLANN parameters

        # FLANN_INDEX_KDTREE = 0

        # index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)

        # search_params = dict(checks=50)

        # matches = np.zeros((int(finalL.shape[1] / h_stripe)), dtype='object')

        # good = []

        # ptsL = []

        # ptsR = []

        #

        # flann = cv2.FlannBasedMatcher(index_params, search_params)

        # for i in range(int(finalL.shape[1] / h_stripe)):

        #     if kp_stripesL[i] == 0:

        #         kp_stripesL[i] = []

        #     if kp_stripesR[i] == 0:

        #         kp_stripesR[i] = []

        #     for j in range(len(kp2)):

        #         if i*h_stripe <= kp2[j].pt[1] < (i+1)*h_stripe:

        #             kp_stripesL[i].append(kp2[j])

        #     for j in range(len(kp1)):

        #         if i * h_stripe <= kp1[j].pt[1] < (i + 1) * h_stripe:

        #             kp_stripesR[i].append(kp1[j])
        for i in range(int(finalL.shape[1] / h_stripe)):
            kp_stripesL.append([])
            kp_stripesR.append([])
            des_stripesL.append([])
            des_stripesR.append([])
            for j in range(len(kpL)):
                if i * h_stripe <= kpL[j].pt[1] < (i + 1) * h_stripe:
                    kp_stripesL[i].append(kpL[j])
                    des_stripesL[i].append(desL[j])
            for j in range(len(kpR)):
                if i * h_stripe <= kpR[j].pt[1] < (i + 1) * h_stripe:
                    kp_stripesR[i].append(kpR[j])
                    des_stripesR[i].append(desR[j])
        # print(len(des_stripesL))
        des_stripesL = np.array(des_stripesL)
        kp_stripesL = np.array(kp_stripesL)
        des_stripesR = np.array(des_stripesR)
        kp_stripesR = np.array(kp_stripesR)
        distance = []
        disparity_map = []
        kp_struct = []
        # distance = np.zeros((int(finalR.shape[1] / h_stripe),), dtype='object')

        # distance[i, :, :] = np.array(np.sqrt(np.sum((des_stripesL[i][:, np.newaxis, :] - des_stripesR[i][np.newaxis, :, :]) ** 2, axis=-1)))

        # distance = np.array(np.sqrt(np.sum((des1[:, np.newaxis, :] - des2[np.newaxis, :, :]) ** 2, axis=-1)))
        outimg = np.concatenate((frameL, frameR), axis=1)
        for j in range(len(des_stripesL)):
            des_stripesL[j] = np.array(des_stripesL[j])
            kp_stripesL[j] = np.array(kp_stripesL[j])
            des_stripesR[j] = np.array(des_stripesR[j])
            kp_stripesR[j] = np.array(kp_stripesR[j])
            distance.append([])
            # print(kp_stripesL[j].__len__(), " ", kp_stripesR[j].__len__())
            if kp_stripesL[j].__len__() > 0 and kp_stripesR[j].__len__() > 0:
                distance[j] = np.array(np.sqrt(
                    np.sum((des_stripesL[j][:, np.newaxis, :] - des_stripesR[j][np.newaxis, :, :]) ** 2, axis=-1)))
                ind = tuple(zip(*np.where(distance[j] < 150)))  ### GUARDA QUI!!!!!!!!!!!!!!!
                index = list(ind)
                # print(ind)

                # print(index)
                removed = np.ones(len(ind), dtype='uint8')
                for i in range(len(ind) - 1):
                    check = False
                    if removed[i] == 1:
                        for k in range(i + 1, len(ind)):
                            if ind[i][0] == ind[k][0] or ind[i][1] == ind[k][1]:
                                if distance[j][ind[i]] < distance[j][ind[k]]:
                                    if removed[k] == 1:
                                        # print(ind[k])
                                        index.remove(ind[k])
                                        removed[k] = 0
                                else:
                                    if removed[i] == 1:
                                        # print('ciao', ind[i])
                                        index.remove(ind[i])
                                        removed[i] = 0
                index = tuple(index)
                # print(removed)

                # print('ind after cleaning',ind)

                # print('ind after cleaning',index)
                for i in index:
                    uL = int(kp_stripesL[j][i[0]].pt[0] + off_x_L)
                    uR = int(kp_stripesR[j][i[1]].pt[0] + off_x_R)
                    vL = int(kp_stripesL[j][i[0]].pt[1] + off_y_L)
                    vR = int(kp_stripesR[j][i[1]].pt[1] + off_y_R)
                    disparity = uL - uR
                    # print("(", uL, ", ",  vL, ") ", "(", uR, ", ",  vR, ") ", disparity)
                    kp_struct.append(((uL, vL), (uR, vR)))
                    if disparity + frameL.shape[1] > 0:
                        disparity_map.append(disparity + frameL.shape[1])
                        cv2.circle(outimg, (uL, vL), 3, (255, 0, 0), 1)
                        cv2.circle(outimg, (uR, vR), 3, (255, 0, 0), 1)
                        cv2.line(outimg, (uL, vL), (uR, vR), (255, 0, 0), 1)
            #     cv2.circle(finalL, (int(kp_stripesL[j, i[0]].pt[0]), int(kp_stripesL[j, i[0]].pt[1])), 4, (10 * i, 0, 0), 1)

            #     cv2.circle(finalR, (int(kp_stripesR[j, i[1]].pt[0]), int(kp_stripesR[j, i[1]].pt[1])), 4, (10 * i, 0, 0), 1)

            # temp_match = flann.knnMatch(des_stripesL[j], des_stripesR[j], k=2)
        # matches.append(temp_match)

        # ratio test as per Lowe's paper

        # for i, (m, n) in enumerate(temp_match):

        #     if m.distance < 0.8 * n.distance:

        #         good.append(m)
        n_kp = len(kp_struct)
        # print(n_kp)

        fig = None
        if len(disparity_map) > 2:
            d_main = np.mean(disparity_map)
            # print(d_main)

            # min_disp = d_main - 32

            # max_disp = d_main + 32
            disparity_map = np.array(disparity_map)
            # disparity_map_star = disparity_map < max_disp

            # disparity_map_star = disparity_map > min_disp
            disparity_map_star = np.ma.masked_inside(disparity_map, min_disp, max_disp)
            min_disp = d_main - (d_main / 2)
            max_disp = d_main + (d_main / 2)
            # disp_tot = (disparity_map_star.all() == disparity_map_star1.all())
            disparity_map_star = disparity_map[disparity_map_star.mask]
            std_dev = np.std(disparity_map_star)
            print(std_dev)
            print(2 / dist_ob)
            if std_dev > 0:#(2 / dist_ob):
                val = filters.threshold_otsu(disparity_map_star)
                # print(val)
                d_main_background = np.mean(disparity_map_star[disparity_map_star <= val])
                dist_bg = round(0.001 * focal_lenght * baseline / d_main_background, 2)
                print("d_main_background: ", round(d_main_background, 2), 'distance_background: ', dist_bg, "m")
                d_main_object = np.mean(disparity_map_star[disparity_map_star > val])
                dist_ob = round(0.001 * focal_lenght * baseline / d_main_object, 2)
                print("d_main_object: ", round(d_main_object, 2), 'distance_object: ', dist_ob, "m")
            else:
                d_main_object = np.mean(disparity_map_star)
                dist_ob = round(0.001 * focal_lenght * baseline / d_main_object, 2)
                print("d_main: ", round(d_main_object, 2), 'distance: ', dist_ob, "m")
                flag = False
        else:
            if not flag:
                print("d_main ~ ", round(d_main_object, 2), 'distance ~ ', dist_ob, "m")
            else:
                print("d_main <= ", round(d_main_object, 2), 'distance <= ', dist_ob, "m")
            flag = True

        # cv2.putText(outimg, d_main, (10, 10), cv2.FONT_ITALIC, 2, 255)
        if dist_ob <= 0.8:
            print('Warning: object too close')
        # for i in range(int(min(des_stripesL.__len__(), des_stripesR.__len__()))):

        #     try:

        #         cv2.drawMatchesKnn(finalL, kp_stripesL[i], finalR, kp_stripesR[i], good[i], outimg)

        #         cv2.knn

        #     except(SystemError):

        #         continue

        # kpL = kp_stripesL[4]

        # kpR = kp_stripesR[4]

        # outimg = cv2.resize(outimg, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)

        cv2.imshow("outimg", outimg)
        # n_kp = np.sum(len(kp_struct[:]))

        # max_kp.append(n_kp)

        # d4 = d3

        # d3 = d2

        # d2 = d1

        # d1 = d0

        # d0 = temp_dim

        m = (30 - 60) / 27
        q = 60 - m * 3
        if 128 > d_main_object >= 0:
            if n_kp <= 3:
                temp_dim = 100
            elif 3 < n_kp < 30:
                temp_dim = int(m * n_kp + q)
            else:
                temp_dim = 50

        # dist_vect[4] = dist_vect[3]
        #
        # dist_vect[3] = dist_vect[2]
        #
        # dist_vect[2] = dist_vect[1]
        #
        # dist_vect[1] = dist_vect[0]
        #
        # dist_vect[0] = temp_dim
        for i in range(len(dist_vect) - 1, 0, -1):
            dist_vect[i] = dist_vect[i - 1]
        dist_vect[0] = temp_dim
        dim_kp = int(np.mean(dist_vect))

        # print("n_kp: ", n_kp)

        # good = []

        # pts1 = []

        # pts2 = []

        #

        # # ratio test as per Lowe's paper

        # for i, (m, n) in enumerate(matches):

        #     if m.distance < 0.8 * n.distance:

        #         good.append(m)

        #         pts2.append(kp_stripesL[i][m.trainIdx].pt)

        #         pts1.append(kp_stripesR[i][m.queryIdx].pt)
    #     # # BFMatcher with default params

    #     # bf = cv2.BFMatcher(cv2.NORM_L2)

    #     # matches = bf.knnMatch(des1, des2, k=2)

    #     #

    #     # # Apply ratio test

    #     # good = []

    #     # for m, n in matches:

    #     #     if m.distance < 0.75 * n.distance:

    #     #         good.append([m])

    #

    #     # draw key points detected

    #     img1 = cv2.drawKeypoints(finalR, kp1, finalR, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

    #     cv2.imshow("grayframe1", img1)

    #     # distance = np.zeros((des1.shape[0], des2.shape[0]))

    #     # for i in range(des1.shape[0]-1):

    #     #     for j in range(des2.shape[0]-1):

    #     #         if kp1[i].pt[1] - kp2[j].pt[1] < 0.3 or kp1[i].pt[1] - kp2[j].pt[1] > -0.3:

    #     #             distance[i, j] = np.sqrt(np.sum((des1[i, :] - des2[j, :]) ** 2, axis = -1))

    #

    #     distance = np.array(np.sqrt(np.sum((des1[:, np.newaxis, :] - des2[np.newaxis, :, :]) ** 2, axis=-1)))

    #     #SIFT descriptor of a point is just 128-dimensional vector, so you can simple compute Euclidean distance

    #     between every two and match nearest pairs.

    #

    #     # for k in range(len(kp1)):

    #     #     for z in range(len(kp2)):

    #     #         if kp1[k].angle - kp2[z].angle > 0.5 or kp1[k].angle - kp2[z].angle < -0.5:

    #     #             distance[k, z] = 100000000000

    #     #         if kp1[k].pt[1] - kp2[z].pt[1] > 3 or kp1[k].pt[1] - kp2[z].pt[1] < -3:

    #     #             distance[k, z] = 100000000000

    #

    #     ind = np.unravel_index(np.argmin(distance, axis=None), distance.shape)

    #     print(distance.min())

    #     #ciccio = np.unravel_index(distance<100

    #     ind = tuple(zip(*np.where(distance < 50)))

    #     kpL = []

    #     kpR = []

    #     for i in ind:

    #         if 0.05 > kp2[i[1]].pt[1] - kp1[i[0]].pt[1] > -0.05 and 128 > kp2[i[1]].pt[0] - kp1[i[0]].pt[0] > 0:

    #             kpL.append(kp2[i[1]])

    #             kpR.append(kp1[i[0]])

    #     for i,j in enumerate(kpL):

    #         cv2.circle(centerL, (int(j.pt[0]), int(j.pt[1])), 4, (10*i, 3*i,25*i), 1)

    #     for i, j in enumerate(kpR):

    #         cv2.circle(centerR, (int(j.pt[0]), int(j.pt[1])), 4, (10*i, 3*i,25*i), 1)

    #     cv2.imshow('centerL', centerL)

    #

    #     cv2.imshow('centerR', centerR)

    #     # # create BFMatcher object

    #     #bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)

    #

    #     ## Match descriptors.

    #     #matches = bf.match(des1, des2)

    #

    #     ## Sort them in the order of their distance.

    #     #matches = sorted(matches, key=lambda x: x.distance)

    #     # good = []

    #     # for m, n in matches:

    #     #     if m.distance < 0.2 * n.distance:

    #     #         good.append([m])

    #     # # Draw first 10 matches.

    #     # img4 = np.hstack((centerL, centerR))

    #     # img3 = cv2.drawMatchesKnn(centerL, kp1, centerR, kp2, good, img4, flags=2)

    #

    #     #cv2.imshow('matches', img3)

    #

    #     cv2.imshow('FrameL', frameL)

    #     cv2.imshow('FrameR', frameR)

    # # Press Q on keyboard to  exit

    if cv2.waitKey(25) & 0xFF == ord('q'):
        break
    # if k == 27:  # Esc key to stop

    #     break

    # elif k == -1:  # normally -1 returned,so don't print it

    #     continue

    # else:

    #     print(k)

    if cv2.waitKey(33) == ord('a'):
        outimg = cv2.resize(outimg, None, fx=1.5, fy=1.5, interpolation=cv2.INTER_CUBIC)
        cv2.imshow("stopped_frame", outimg)
        while (True):
            k = cv2.waitKey(33)
            if k == 27:  # Esc key to stop
                break

capL.release()
capR.release()
cv2.destroyAllWindows()


#！/usr/bin/env.python
#coding:utf-8
#写入excel操作

import xlsxwriter
import datetime
#创建excel文件

workbook = xlsxwriter.Workbook('test1.xlsx')#创建文件
worksheet = workbook.add_worksheet('test1')#创建sheet，清空文件

#2.特定单元格写入

worksheet.write('A1','黄爱华')
worksheet.write(1,0,'下标进行写入')
worksheet.write(0,1,32)

worksheet.set_row(0,40)#设置好行属性
worksheet.set_column('A:A',20)#设置列属性\

#写入数字和函数
worksheet.write(0,1,32)
worksheet.write(1,1,35.5)
worksheet.write(2,1,'=sum(B1:B2)')

#写入日期
#worksheet.write(0,2,datetime.datetime.strptime('2017-11-11','%Y-%m-%d'),workbook.add_format({'num.format':'yyyy-mm-dd'}))

#插入图片
worksheet.insert_image(0,4,'sfdfa.jpg')
worksheet.insert_image(0,4,'sfdfa.jpg',{'x_scale':0.2,'y_scale':0.2,'url':'www.baidu.com'})

#批量写入单元格
worksheet.write_column('A22',[1,2,3,4])#列写入，从A22写起
worksheet.write_row('A21',[5,6,7,8])#行写入，从A21写起

#合并单元格写入
worksheet.merge_range(4,0,5,2,'黄爱华')

#写入图表
workbook.add_chart()

#关闭文件
workbook.close()


import pygame
import os
import time

pygame.init()
size = width, height = 1000, 700
screen = pygame.display.set_mode(size)
screen.fill((255, 255, 255))
all_sprites = pygame.sprite.Group()
fishes = pygame.sprite.Group()
shark = pygame.sprite.Group()
ontime = 0
running = True
clock = pygame.time.Clock()
speed = 10

def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    image = pygame.image.load(fullname).convert()
    if colorkey is not None:
        if colorkey == -1:
            colorkey = image.get_at((0, 0))
        image.set_colorkey(colorkey)
    else:
        image = image.convert_alpha()
    return image

fon = pygame.transform.scale(load_image('background.jpg'), (width, height))
screen.blit(fon, (0, 0))

def cut_sheet(self, sheet, columns, rows, frames):
    self.rect = pygame.Rect(0, 0, sheet.get_width() // columns,
                            sheet.get_height() // rows)
    for j in range(rows):
        for i in range(columns):
            frame_location = (self.rect.w * i, self.rect.h * j)
            frames.append(sheet.subsurface(pygame.Rect(
                frame_location, self.rect.size)))

player = 0

class Sharky(pygame.sprite.Sprite):
    def __init__(self, x, y):
        global player
        super().__init__(all_sprites)
        self.swimframes = []
        self.moveframes = []
        self.eatframes = []
        self.rect = pygame.Rect((0, 0), (207, 85))
        for i in range(1, 6):
            sheet = load_image(f'bluesharkswim(' + str(i) + ').png', colorkey=-1)
            self.swimframes.append(sheet.subsurface(pygame.Rect(
                (0, 0), sheet.get_rect().size)))
        for i in range(1, 11):
            sheet = load_image(f'bluesharkmove' + str(i) + '.png', colorkey=-1)
            self.moveframes.append(sheet.subsurface(pygame.Rect(
                (0, 0), sheet.get_rect().size)))
        cut_sheet(self, load_image('bluesharkeat.png', colorkey=-1), 2, 1, self.eatframes)
        self.add(shark)
        self.cur_frame = 0
        self.image = self.swimframes[self.cur_frame]
        self.rect = self.rect.move(x, y)
        player = self
        self.count = 0
        self.mask = pygame.mask.from_surface(self.image)
        self.mov = 0

    def update(self):
        self.count += 1
        if self.count == 25:
            self.cur_frame = (self.cur_frame + 1) % len(self.swimframes)
            if self.mov == 9:
                self.image = pygame.transform.flip(self.swimframes[self.cur_frame], 90, 0)
            else:
                self.image = self.swimframes[self.cur_frame]
            self.count = 0

    def movement(self, dir):
        if dir == -1:
            self.image = self.moveframes[self.mov]
            self.mov += 1
        elif dir == 1:
            self.image = self.moveframes[self.mov]
            self.mov -= 1

class Fish(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__(all_sprites)
        self.add(fishes)
        self.swimframes = []
        cut_sheet(self, load_image('yellowfishswim.png', colorkey=-1), 6, 1, self.swimframes)
        self.cur_frame = 0
        self.image = self.swimframes[self.cur_frame]
        self.rect = self.rect.move(x, y)
        self.count = 0
        self.mask = pygame.mask.from_surface(self.image)

    def update(self):
        self.count += 1
        if pygame.sprite.collide_mask(self, player):
            if player.mov <= 4:
                player.image = player.eatframes[0]
                player.image = player.eatframes[1]
            else:
                player.image = pygame.transform.flip(player.eatframes[0], 90, 0)
                player.image = pygame.transform.flip(player.eatframes[1], 90, 0)
            self.kill()
            for i in range(len(player.swimframes)):
                player.swimframes[i] = pygame.transform.smoothscale(player.swimframes[i],
                                                                    (player.swimframes[i].get_width(),
                                                                     player.swimframes[i].get_height()))

        if self.count == 20:
            self.cur_frame = (self.cur_frame + 1) % len(self.swimframes)
            self.image = self.swimframes[self.cur_frame]
            self.count = 0

speed = 100
motion = 'STOP'
Sharky(200, 200)
direct = 1
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                motion = 'LEFT'
            elif event.key == pygame.K_RIGHT:
                motion = 'RIGHT'
            elif event.key == pygame.K_UP:
                motion = 'UP'
            elif event.key == pygame.K_DOWN:
                motion = 'DOWN'
        elif event.type == pygame.MOUSEBUTTONDOWN:
            Fish(event.pos[0], event.pos[1])
        elif event.type == pygame.KEYUP:
            if event.key in [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN]:
                motion = 'STOP'

    if motion == 'LEFT':
        if player.mov < 9:
            player.movement(-1)
        else:
            player.rect.x -= 3
    elif motion == 'RIGHT':
        if player.mov > 0:
            player.movement(1)
        else:
            player.rect.x += 3
    elif motion == 'DOWN':
        player.rect.y += 3
    elif motion == 'UP':
        player.rect.y -= 3

    screen.blit(fon, (0, 0))
    all_sprites.draw(screen)
    all_sprites.update()
    pygame.display.flip()
    clock.tick(speed)


import requests
import json
import time
import sys
from bs4 import BeautifulSoup
import re

class xiaoiceApi():

    def __init__(self, header_file):
        self.header_file = header_file
        self.headers = {}
        self.loadheaders()

    def loadheaders(self):
        with open(self.header_file) as headers:
            line = headers.readline().strip()
            while line:
                key = line.split(":")[0]
                self.headers[key] = line[len(key)+1:].strip()
                line = headers.readline().strip()

    def chat(self, input_strs):
        if not self.headers:
            return self.dicts("error", "请打开浏览器 复制并将headers放入headers.txt中")
        data = {
            'location':'msgdialog',
            'module':'msgissue',
            'style_id':1,
            'text':input_strs,
            'uid':5175429989,
            'tovfids':'',
            'fids':'',
            'el':'[object HTMLDivElement]',
            '_t':0,
        }

        try:
            #原http的api已改为https的api
            url = 'https://weibo.com/aj/message/add?ajwvr=6'
            page = requests.post(url, data=data, headers=self.headers)
#             self.savePage(page.text, "./tmp/postpage.txt")
            if page.json()['code'] == '100000':
                code, text, res_type = self.loop(input_strs)
                return self.dicts(code, res_type, text)
            else:
                return self.dicts("500", "failed", page.json()['msg'])
        except Exception as e:
            return self.dicts("500", "error", e)

    def dicts(self, status, res_type, text):
        '''
            包装return
        '''
        return {"status":status, "type":res_type, "text":text}

    def loop(self, input_strs):
        '''
            刷新直到获取到回答
        '''
        times = 1
        while times <= 20:
            times += 1
            response = requests.get("https://weibo.com/aj/message/getbyid?ajwvr=6&uid=5175429989&count=1&_t=0" , headers={"Cookie":self.headers["Cookie"]})
            soup = BeautifulSoup(response.json()['data']['html'], "lxml")
            text = soup.find("p", class_='page')
            if text:
                if text.text == input_strs:
                    time.sleep(0.3)
                    continue
            elif "收起" in soup.get_text():
                #返回imgURL
                imgUrl = soup.find(href=re.compile('msget')).get('href')
                return 200, imgUrl, "img"

            elif "mp3" in soup.get_text():
                mp3Url = soup.find(href=re.compile('msget')).get('href')
                return 200, mp3Url,"voice"

            return 200, text.text, "text"
        text = "错误： 已达到最大重试次数"
        return 500, text, "failed"

if __name__ == '__main__':
    xb = xiaoiceApi('header_file/headers_1.txt')


import math
import pyrealsense2 as rs
from matplotlib import pyplot as plt
import cv2
import numpy as np

import rs_help

myRealSense = rs_help.MyRealsense()
myRealSense.rs_configure()
myRealSense.rs_start_pipe()

# height and rotation in mm and in radians
height = 130
angle = 0

# number of frames to average
N = 200

def get_filtered_color(color_frame, base_color, thresh):
    """
    will filter the class color frame with parameters
    :param color_frame:
    :param base_color:
    :param thresh:
    :return:
    """
    bound_lower = [base_color[0] - thresh[0], base_color[1] - thresh[1], base_color[2] - thresh[2]]
    bound_upper = [base_color[0] + thresh[0], base_color[1] + thresh[1], base_color[2] + thresh[2]]
    if bound_lower[0] < 0:
        bound_lower[0] = 0
    if bound_lower[1] < 0:
        bound_lower[1] = 0
    if bound_lower[2] < 0:
        bound_lower[2] = 0
    if bound_upper[0] > 179:
        bound_upper[0] = 179
    if bound_upper[1] > 255:
        bound_upper[1] = 255
    if bound_upper[2] > 255:
        bound_upper[2] = 255
    # return filtered frame
    return cv2.inRange(color_frame, np.array(bound_lower), np.array(bound_upper))

def average_colors(newest_color):
    if 'colorRGB' not in average_colors.__dict__:
        average_colors.colorRGB = np.array([newest_color])

    # create / update colorRGB array
    array_size = average_colors.colorRGB.shape[0]
    if array_size <= N:
        average_colors.colorRGB = np.vstack((average_colors.colorRGB, newest_color))
    else:
        for i in range(0, N - 1):
            average_colors.colorRGB[i] = average_colors.colorRGB[i + 1]
        average_colors.colorRGB[N - 1] = newest_color

    # average everything together
    row, col = average_colors.colorRGB.shape

    b = np.convolve(average_colors.colorRGB[:, 0], np.ones(row) / row, mode='valid')
    g = np.convolve(average_colors.colorRGB[:, 1], np.ones(row) / row, mode='valid')
    r = np.convolve(average_colors.colorRGB[:, 2], np.ones(row) / row, mode='valid')
    averaged_color = np.concatenate((b, g, r), axis=0)
    return averaged_color

try:
    while True:

        # Wait for a coherent pair of frames: depth and color
        myRealSense.rs_align_and_update_frames()

        color_frame = myRealSense.rs_color_frame
        hsv_frame = cv2.cvtColor(color_frame, cv2.COLOR_RGB2HSV)
        depth_frame = myRealSense.rs_get_depth()
        colored_depht_frame = cv2.applyColorMap(cv2.convertScaleAbs(depth_frame, alpha=0.03), cv2.COLORMAP_JET)

        # Mask the color image to get the ground
        groundMask, objectMask = myRealSense.rs_get_ground_obstacle_mask(height, angle)
        groundIMG = cv2.GaussianBlur(cv2.bitwise_and(hsv_frame, hsv_frame, mask=groundMask), (5, 5), 2)
        objectIMG = cv2.bitwise_and(color_frame, color_frame, mask=objectMask)
        groundIMGValue = groundIMG[:, :, 2]
        (minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(groundIMGValue)
        # Stack both images horizontally
        brightestColor = groundIMG[maxLoc[1], maxLoc[0]]
        brightestColor = average_colors(brightestColor)
        print(maxLoc)
        print(brightestColor)
        LinesMask = get_filtered_color(groundIMG, brightestColor, [50, 65, 100])
        LinesIMG = cv2.bitwise_and(color_frame, color_frame, mask=LinesMask)

        LinesDepthIMG = cv2.bitwise_and(colored_depht_frame, colored_depht_frame, mask=LinesMask)
        images = np.hstack((objectMask, LinesMask))

        # Show images
        cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
        # cv2.imshow('Normal Image', color_image)
        # cv2.imshow('Depth Image', depth_image)
        cv2.imshow('RealSense', images)
        key = cv2.waitKey(1) & 0xFF
        if key == ord('q'):
            break
        elif key == ord('p'):
            plt.imshow(groundIMG)
            plt.show()
            while cv2.waitKey(0) & 0xFF != ord('p'):
                x = 0

finally:

    # Stop streaming
    myRealSense.rs_stop_pipe()


from models import *
from django.core.exceptions import ObjectDoesNotExist

def update_token(token,paid): #set token as paid
    receipt = PaymentsReceipt.objects.get(token=token)
    receipt.payd = paid
    receipt.save()
    return 1

def check_token(token): #check if token is paid
    receipt = PaymentsReceipt.objects.get(token=token)
    return receipt.payd

def add_token(token, uid, paid): #add new payment
    receipts = PaymentsReceipt(token=token, user_id=uid,payd=paid)
    receipts.save()
    return  1

def add_credits(uid, nr_credits):#add credits to user
    try:
        user = UserCredits.objects.get(user_id=uid)
        user.credit_amt = user.credit_amt + nr_credits
    except ObjectDoesNotExist:
        user = UserCredits(user_id=uid,credit_amt=nr_credits)
    user.save()
    return  1

def remove_credits(uid, nr_credits):#remove credits from user
    try:
        user = UserCredits.objects.get(user_id=uid)
        if user.credit_amt >= nr_credits:
            user.credit_amt = user.credit_amt - nr_credits
            user.save()
        else:
            return 0 # insufficient funds
    except ObjectDoesNotExist:
        return -1 # object does not exist
    return  1 # ok


import os
import logging

from flask import Flask, request
from flask_babel import Babel, lazy_gettext as _l
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from flask_mail import Mail
from flask_migrate import Migrate
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from logging.handlers import SMTPHandler, RotatingFileHandler
from config import Config

application = Flask(__name__)
application.config.from_object(Config)  # File Configuration
babel = Babel(application)              # Language
bootstrap = Bootstrap(application)      # UI
login = LoginManager(application)       # Login Tool
login.login_view = 'login'
login.login_message = _l('Please log in to access this page.')
mail = Mail(application)                # Email Tool
db = SQLAlchemy(application)            # Database Tool
migrate = Migrate(application, db)      # Database Migration Tool
moment = Moment(application)            # Time

# Error notification
if not application.debug:
    # by Email
    if application.config['MAIL_SERVER']:
        auth = None
        if application.config['MAIL_USERNAME'] or application.config['MAIL_PASSWORD']:
            auth = (application.config['MAIL_USERNAME'], application.config['MAIL_PASSWORD'])
        secure = None
        if application.config['MAIL_USE_TLS']:
            secure = ()

        mail_handler = SMTPHandler(
            mailhost=(application.config['MAIL_SERVER'], application.config['MAIL_PORT']),
            fromaddr='no-reply@' + application.config['MAIL_SERVER'],
            toaddrs=application.config['ADMINS'],
            subject='Microblog Failure',
            credentials=auth,
            secure=secure
        )
        mail_handler.setLevel(logging.ERROR)
        application.logger.addHandler(mail_handler)

    # logging
    if not os.path.exists('logs'):
        os.mkdir('logs')

    file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240, backupCount=10)
    file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    file_handler.setLevel(logging.INFO)
    application.logger.addHandler(file_handler)
    application.logger.setLevel(logging.INFO)
    application.logger.info('Microblog startup')

@babel.localeselector
def get_locale():
    # return request.accept_languages.best_match(application.config['LANGUAGES'])
    return 'es'

from app import routes, models, errors


from PySide.QtCore import *
from PySide.QtGui import *

import csv
import datetime
import sys

infilename = datetime.datetime.now().strftime('%m%d%Y')+'.csv'

class CsvOutputWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        layout = QVBoxLayout()
        self.setLayout(layout)

        self.text_edit_outout = QTextEdit()
        layout.addWidget(self.text_edit_outout)
        self.show()

    def display_csv(self):
        with open(infilename) as filein:
            reader = csv.reader(filein)
            for row in reader:
                if len(row) != 9:
                    continue
                response = row[7]
                if response == 'True':
                    continue
                reviewdate = row[3]
                color = 'white'
                if not reviewdate == 'review_date' and datetime.datetime.strptime(reviewdate, '%m%d%Y') < datetime.datetime.now()-datetime.timedelta(days=2):
                    color = 'orange'
                self.write_text(', '.join(row)+'\n\n', color)

    def write_text(self, text, color):
        cursor = self.text_edit_outout.textCursor()
        cursor.movePosition(QTextCursor.End)
        textformat = QTextCharFormat()
        textformat.setBackground(QBrush(QColor(color)))
        cursor.setBlockCharFormat(textformat)
        cursor.insertText(text)
        self.text_edit_outout.setTextCursor(cursor)
        self.text_edit_outout.ensureCursorVisible()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mw = CsvOutputWindow()
    mw.display_csv()
    app.exec_()


#!/bin/env python3
# -*- coding: utf-8 -*-

# artu: auto rsync to udisk
# This program under the MIT open source License, see http://opensource.org/licenses/mit-license.php

program_name = 'artu.py'
short_program_name = 'artu'
__version__ = '0.0.1'

import os
import sys
import fcntl
import json

import pyudev

import dd_style_argparse

default_operands = {
    'config': '/etc/%s/%s.conf' % (short_program_name, short_program_name),
    'register': '/etc/%s/register.json' % short_program_name,
    'pid': '/run/%s.pid' % short_program_name,
    'root_of_mount_folder': '/run/mount_points'
}

operands_key = ['pid', 'config', 'register']
opts = ['--help', '--version']

def arg_help():
    pass

def arg_version():
    s = ('%s %s'
         'Copyright (C) 2014 Free Software Foundation, Inc.'
         'License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.'
         'This is free software: you are free to change and redistribute it.'
         'Written by Chen Meng.'
         % (program_name, __version__)
         )
    print(s)
    exit()

def process_device_event(device):
    if device.action == 'add':
        process_device_action_add(device)

def process_device_action_add(device):
    partition = None

    for one in register:
        if one['UUID'] == device.get('ID_FS_UUID') and one['available'] is True:
            partition = one
            print(partition)
            break

    if partition:
        mount_point = operands['root_of_mount_folder'] + '/' + device.get('ID_FS_UUID')

        # try:
        os.mkdir(mount_point)
        # except FileExistsError:

        mount(device.device_node, mount_point)
        rsync(partition['rsync_src'], mount_point)

def mount(source, target):
    cmd = '/bin/mount %s %s' % (source, target)
    print('mount: %s' % cmd)
    print('start mount')
    os.system(cmd)
    print('mounted')

def rsync(source, destination):
    cmd = '/usr/bin/rsync -aL --delete --exclude tmp/ %s %s' % (source, destination)
    print('rsync: %s' % cmd)
    print('start rsync')
    os.system(cmd)
    print('rsynced')

if __name__ == '__main__':

    inputted_operands, inputted_options = dd_style_argparse.get_split_args(sys.argv, operands_key, opts)
    operands = default_operands.copy()
    operands.update(inputted_operands)

    lock = open(operands['pid'], "w+")
    try:
        fcntl.lockf(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        sys.exit('%s: An instance is already running' % sys.argv[0])
    lock.write(str(os.getpid()))
    lock.flush()

    register = json.loads(open(operands['register']).read())

    try:
        os.makedirs(operands['root_of_mount_folder'])
    except FileExistsError:
        pass

    context = pyudev.Context()
    monitor = pyudev.Monitor.from_netlink(context)
    monitor.filter_by(subsystem='block', device_type='partition')
    observer = pyudev.MonitorObserver(monitor, callback=process_device_event, name='monitor-observer')
    observer.daemon = False
    observer.start()


from flask import jsonify
from flask.ext.restful import Resource, fields, reqparse
from myapi import db
from myapi.model.version import VersionModel
from myapi.model.user import UserModel
from myapi.model.project import ProjectModel
from myapi.model.enum import version_status

parser = reqparse.RequestParser()
parser.add_argument('title', type=str, location='json', required=True)
parser.add_argument('description', type=str, location='json')
parser.add_argument('image', type=str, location='json')
parser.add_argument('projectid', type=int, location='json', required=True)
parser.add_argument('userid', type=int, location='json', required=True)

class Version(Resource):
    def get(self, versionid):
        version = VersionModel.query.get(versionid)
        return jsonify(version.serialize())

    def post(self):
        args = parser.parse_args()
        version = VersionModel(args.title, args.description, args.image)
        db.session.add(version)

        project = ProjectModel.query.get(args.projectid)
        project.versions.append(version)

        user = UserModel.query.get(args.userid)
        user.versions.append(version)
        db.session.commit()
        return jsonify(version.serialize())

    def put(self):
        pass

    def delete(self):
        args = parser.parse_args()
        version = VersionModel.query.get(args.id)
        version.status = version_status.delete
        db.session.commit()
        return jsonify(version.serialize())

class ProjectVersions(Resource):
    def get(self, projectid):
        versions = VersionModel.query\
            .filter_by(status = version_status.normal)\
            .filter_by(project_id = projectid)\
            .order_by(VersionModel.publishDate.desc()).all()
        return jsonify(data=[e.serialize() for e in versions])


import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

import cv2
cap = cv2.VideoCapture(0)

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")

# ## Object detection imports
# Here are the imports from the object detection module.

# In[3]:

from utils import label_map_util

from utils import visualization_utils as vis_util

pts1 = np.float32([[69,108],[595,15],[42,390],[596,469]])
pts2 = np.float32([[0,0],[640,0],[0,480],[640,480]])

M = cv2.getPerspectiveTransform(pts1,pts2)

# while(True):
#   ret, image_np = cap.read()
#   image_np = cv2.resize(image_np, (640, 480))
#   imgae_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
#   cv2.imshow('original', image_np)

#   image_np = cv2.warpPerspective(image_np,M,(640,480))
#   cv2.imshow('warp', image_np)
#   cv2.waitKey(30)
# # Model preparation

# ## Variables
#
# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file.
#
# By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.

# In[4]:

# What model to download.
MODEL_NAME = 'deep-finger'
MODEL_NAME_F = 'finger-deep'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
PATH_TO_CKPT_F = MODEL_NAME_F + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = 'deep-finger.pbtxt'
PATH_TO_LABELS_F = 'finger-deep.pbtxt'

NUM_CLASSES = 1

# ## Load a (frozen) Tensorflow model into memory.

# In[6]:

detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')

# ## Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

## FINGER ###############################
detection_graph_f = tf.Graph()
with detection_graph_f.as_default():
  od_graph_def_f = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT_F, 'rb') as fid:
    serialized_graph_f = fid.read()
    od_graph_def_f.ParseFromString(serialized_graph_f)
    tf.import_graph_def(od_graph_def_f, name='')

# ## Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

label_map_f = label_map_util.load_labelmap(PATH_TO_LABELS_F)
categories_f = label_map_util.convert_label_map_to_categories(label_map_f, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index_f = label_map_util.create_category_index(categories_f)

# ## Helper code

# In[8]:

def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)

# # Detection

def crop(img, xmin, ymin, xmax, ymax):
    return img[ymin:ymax, xmin:xmax]

# In[10]:

with tf.Session(graph=detection_graph) as sess:
    with tf.Session(graph=detection_graph_f) as sess_f:
        while True:
          ret, image_np = cap.read()
          image_np = cv2.resize(image_np, (640, 480))
          image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
          cv2.imshow('original', image_np)
          img = image_np.copy()

          # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
          image_np_expanded = np.expand_dims(image_np, axis=0)
          image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
          # Each box represents a part of the image where a particular object was detected.
          boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
          # Each score represent how level of confidence for each of the objects.
          # Score is shown on the result image, together with the class label.
          scores = detection_graph.get_tensor_by_name('detection_scores:0')
          classes = detection_graph.get_tensor_by_name('detection_classes:0')
          num_detections = detection_graph.get_tensor_by_name('num_detections:0')
          # Actual detection.
          (boxes, scores, classes, num_detections) = sess.run(
              [boxes, scores, classes, num_detections],
              feed_dict={image_tensor: image_np_expanded})
          # Visualization of the results of a detection.

          vis_util.visualize_boxes_and_labels_on_image_array(
              image_np,
              np.squeeze(boxes),
              np.squeeze(classes).astype(np.int32),
              np.squeeze(scores),
              category_index,
              use_normalized_coordinates=True,
              line_thickness=8,
              min_score_thresh=0.05,
              max_boxes_to_draw=1)

          cv2.imshow('object detection', cv2.resize(image_np, (800,600)))

          chosen = boxes[0][0]
          tlx = max(int(chosen[1]*640) - 5, 0)
          tly = max(int(chosen[0]*480) - 5, 0)
          brx = int(chosen[3]*640)
          bry = int(chosen[2]*480)

          image_np = crop(img, tlx, tly, brx, bry)
          cv2.imshow('hand', image_np)

          ###########################################################

          image_np_expanded = np.expand_dims(image_np, axis=0)
          image_tensor = detection_graph_f.get_tensor_by_name('image_tensor:0')
          # Each box represents a part of the image where a particular object was detected.
          boxes = detection_graph_f.get_tensor_by_name('detection_boxes:0')
          # Each score represent how level of confidence for each of the objects.
          # Score is shown on the result image, together with the class label.
          scores = detection_graph_f.get_tensor_by_name('detection_scores:0')
          classes = detection_graph_f.get_tensor_by_name('detection_classes:0')
          num_detections = detection_graph_f.get_tensor_by_name('num_detections:0')
          # Actual detection.
          (boxes, scores, classes, num_detections) = sess_f.run(
              [boxes, scores, classes, num_detections],
              feed_dict={image_tensor: image_np_expanded})
          # Visualization of the results of a detection.

          vis_util.visualize_boxes_and_labels_on_image_array(
              image_np,
              np.squeeze(boxes),
              np.squeeze(classes).astype(np.int32),
              np.squeeze(scores),
              category_index,
              use_normalized_coordinates=True,
              line_thickness=8,
              min_score_thresh=0.05,
              max_boxes_to_draw=1)

          cv2.imshow('finger', image_np)

          ###########################################################

          if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break


from typing import Callable

import lib.state_machine as state_machine
import lib.vsm as vsm

class ExititingState(vsm.VSM):
    def __init__(self, cleanup: Callable):
        super().__init__()
        self.cleanup = cleanup

    def run(self, sm: 'state_machine.StateMachine'):
        # If the output queue is empty, the main loop of this thread will
        # be blocked, to unblock it, we put a None in it.
        if sm.output_queue.empty():
            sm.output_queue.put(None)

        fps, _ = sm._get_fps()
        print("FPS:", fps)

        self.cleanup()


import torch.nn as nn
import torch.nn.functional as F

class classifier(nn.Module):
    def __init__(self, isDropOut = True):
        super(classifier, self).__init__()
        self.conv1 = nn.Conv2d(1,32,5,padding=2,stride=1)
        self.pool = nn.MaxPool2d(2,stride=2)
        self.conv2 = nn.Conv2d(32,64,5,padding=2,stride=1)
        self.fc1 = nn.Linear(7*7*64, 1024)
        self.fc2 = nn.Linear(1024,10)
        self.relu = nn.ReLU(inplace=True);

    def forward(self, x):

        x = self.pool(self.relu(self.conv1(x)))
        x = self.pool(self.relu(self.conv2(x)))

        x = x.view(-1, 7*7*64)

        x = self.relu(self.fc1(x))
        x = (self.fc2(x))

        return x


from PyQt5.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QGroupBox, QFormLayout, QComboBox, QPushButton, QDoubleSpinBox, QSpinBox, QCheckBox, \
    QGridLayout, QLabel, QInputDialog, QFrame, QMessageBox
from PyQt5.Qt import QIcon

class SettingsDialog(QDialog):
    def __init__(self, main, profilecon):
        super().__init__()

        self.profilecon = profilecon
        self.main = main

        self.setWindowTitle("Settings")

        layout = QVBoxLayout()
        self.setLayout(layout)

        # BOX1 ##### profile selection #####
        box1 = QGroupBox("Profile")
        layout.addWidget(box1)
        box1_layout = QFormLayout()
        box1.setLayout(box1_layout)

        self.profile_selector = QComboBox()
        for name in self.profilecon.list_profiles():
            self.profile_selector.addItem(name)
        self.profile_selector.setCurrentIndex(self.main.profileSelector.currentIndex())
        self.profile_selector.currentTextChanged.connect(self.selected_profile_changed)
        box1_layout.addRow("", self.profile_selector)

        changes_layout = QHBoxLayout()
        save = QPushButton(QIcon("./res/save.svg"), "Save")
        save.setToolTip("Save changes")
        save_new_profile = QPushButton(QIcon("./res/plus-circle.svg"), "Save New")
        save_new_profile.setToolTip("Save changes to a new profile")
        undo = QPushButton(QIcon("./res/rotate-ccw.svg"), "Reset")
        undo.setToolTip("Reset unsaved changes")
        divider = QFrame()
        divider.setFrameShape(QFrame.VLine)
        delete = QPushButton(QIcon("./res/trash-2.svg"), "")
        delete.setToolTip("Delete current profile")

        changes_layout.addWidget(save)
        changes_layout.addWidget(save_new_profile)
        changes_layout.addWidget(undo)
        changes_layout.addWidget(divider)
        changes_layout.addWidget(delete)

        box1_layout.addRow("", changes_layout)

        save.pressed.connect(self.save_settings)
        save_new_profile.pressed.connect(self.save_new_profile)
        undo.pressed.connect(self.set_field_values)
        delete.pressed.connect(self.delete_profile)

        # BOX2 ##### bed size configuration #####
        box2 = QGroupBox("Bed")
        layout.addWidget(box2)
        self.box2_layout = QGridLayout(box2)

        self.bed_min_x = QSpinBox()
        self.bed_min_x.setProperty("key", "bed_min_x")
        lbl_min_x = QLabel("Minimum X")
        self.box2_layout.addWidget(lbl_min_x, 0, 0)
        self.box2_layout.addWidget(self.bed_min_x, 0, 1)

        self.bed_min_y = QSpinBox()
        self.bed_min_y.setProperty("key", "bed_min_y")
        lbl_min_y = QLabel("Minimum Y")
        self.box2_layout.addWidget(lbl_min_y, 1, 0)
        self.box2_layout.addWidget(self.bed_min_y, 1, 1)

        self.bed_max_x = QSpinBox()
        self.bed_max_x.setProperty("key", "bed_max_x")
        lbl_max_x = QLabel("Maximum X")
        self.box2_layout.addWidget(lbl_max_x, 2, 0)
        self.box2_layout.addWidget(self.bed_max_x, 2, 1)

        self.bed_max_y = QSpinBox()
        self.bed_max_y.setProperty("key", "bed_max_y")
        lbl_max_y = QLabel("Maximum Y")
        self.box2_layout.addWidget(lbl_max_y, 3, 0)
        self.box2_layout.addWidget(self.bed_max_y, 3, 1)

        for box in (self.bed_min_x, self.bed_min_y, self.bed_max_x, self.bed_max_y):
            box.setMinimum(-10000)
            box.setMaximum(10000)

        self.invert_x = QCheckBox()
        self.invert_x.setProperty("key", "invert_x")
        lbl_inv_x = QLabel("Invert X")
        self.box2_layout.addWidget(lbl_inv_x, 4, 0)
        self.box2_layout.addWidget(self.invert_x, 4, 1)

        self.invert_y = QCheckBox()
        self.invert_y.setProperty("key", "invert_y")
        lbl_inv_y = QLabel("Invert Y")
        self.box2_layout.addWidget(lbl_inv_y, 5, 0)
        self.box2_layout.addWidget(self.invert_y, 5, 1)

        self.bed_min_x.valueChanged.connect(lambda: self.field_value_changed(self.bed_min_x))
        self.bed_min_y.valueChanged.connect(lambda: self.field_value_changed(self.bed_min_y))
        self.bed_max_x.valueChanged.connect(lambda: self.field_value_changed(self.bed_max_x))
        self.bed_max_y.valueChanged.connect(lambda: self.field_value_changed(self.bed_max_y))
        self.invert_x.toggled.connect(lambda: self.field_value_changed(self.invert_x))
        self.invert_y.toggled.connect(lambda: self.field_value_changed(self.invert_y))

        # BOX 3 ##### speed, acceleration, ... limits #####
        box3 = QGroupBox("Kinematics")
        layout.addWidget(box3)
        self.box3_layout = QGridLayout(box3)

        self.min_speed = QSpinBox()
        self.min_speed.setProperty("key", "min_speed")
        self.min_speed.setMinimum(1)
        self.min_speed.setMaximum(5000)
        lbl_min_speed = QLabel("Minimum Speed [mm/s]")
        self.box3_layout.addWidget(lbl_min_speed, 0, 0)
        self.box3_layout.addWidget(self.min_speed, 0, 1)

        self.acceleration = QSpinBox()
        self.acceleration.setProperty("key", "acceleration")
        self.acceleration.setMinimum(1)
        self.acceleration.setMaximum(100000)
        lbl_acceleration = QLabel("Acceleration [mm/s²]")
        self.box3_layout.addWidget(lbl_acceleration, 1, 0)
        self.box3_layout.addWidget(self.acceleration, 1, 1)

        self.junction_dev = QDoubleSpinBox()
        self.junction_dev.setProperty("key", "junction_dev")
        self.junction_dev.setMinimum(0)
        self.junction_dev.setDecimals(2)
        self.junction_dev.setSingleStep(0.01)
        lbl_jdev = QLabel("Junction Deviation")
        self.box3_layout.addWidget(lbl_jdev, 2, 0)
        self.box3_layout.addWidget(self.junction_dev, 2, 1)

        self.min_speed.valueChanged.connect(lambda: self.field_value_changed(self.min_speed))
        self.acceleration.valueChanged.connect(lambda: self.field_value_changed(self.acceleration))
        self.junction_dev.valueChanged.connect(lambda: self.field_value_changed(self.junction_dev))

        # ##### List of All Settings Fields in This Dialog ##### #
        self.settings_fields = (self.bed_min_x, self.bed_min_y, self.bed_max_x, self.bed_max_y,
                                self.invert_x, self.invert_y, self.min_speed, self.acceleration,
                                self.junction_dev)

        self.set_field_values()

    def set_field_values(self):
        for field in self.settings_fields:
            if type(field) in (QSpinBox, QDoubleSpinBox):
                field.setValue(self.profilecon.get_value(field.property("key")))
            elif type(field) == QCheckBox:
                field.setChecked(self.profilecon.get_value(field.property("key")))

    def showEvent(self, event):
        self.finish_column_sizing()  # column width of QGridLayout is only known after parent widget is shown
        self.setFixedSize(self.size())  # disable possibility to resize the dialog
        super().showEvent(event)

    def finish_column_sizing(self):
        # align all columns in the QGridLayouts by setting the minimum width for all first columns to the width
        # of the widest first column
        max_width = 0
        for layout in (self.box2_layout, self.box3_layout):
            max_width = max(max_width, layout.cellRect(0, 1).x())
        for layout in (self.box2_layout, self.box3_layout):
            layout.setColumnMinimumWidth(0, max_width)

    def field_value_changed(self, field):
        # compare field value to settings value
        if type(field) in (QSpinBox, QDoubleSpinBox):
            if not field.value() == self.profilecon.get_value(field.property("key")):
                field.setStyleSheet("""QWidget {background-color: yellow;}""")
            else:
                field.setStyleSheet("""QWidget {background-color: None;}""")

        elif type(field) == QCheckBox:
            if not field.isChecked() == self.profilecon.get_value(field.property("key")):
                field.setStyleSheet("""QWidget {background-color: yellow;}""")
            else:
                field.setStyleSheet("""QWidget {background-color: None;}""")

    def selected_profile_changed(self, new_profile):
        self.profilecon.select_profile(new_profile)
        self.set_field_values()

        self.main.profileSelector.setCurrentIndex(self.profile_selector.currentIndex())  # update combobox in toolbar of mainwindow

    def save_settings(self):
        for field in self.settings_fields:
            if type(field) in (QSpinBox, QDoubleSpinBox):
                self.profilecon.set_value(field.property("key"), field.value())
            elif type(field) == QCheckBox:
                self.profilecon.set_value(field.property("key"), field.isChecked())

            self.field_value_changed(field)

        self.profilecon.save_to_file()

    def save_new_profile(self):
        name, ok = QInputDialog().getText(self, "Input", "Enter a name for the new profile:")
        if ok:  # only proceed if user didn't cancel
            self.profilecon.add_profile(name)
            self.profilecon.save_to_file()

            self.profilecon.select_profile(name)
            self.save_settings()

            self.profile_selector.addItem(name)
            self.main.profileSelector.addItem(name)
            self.profile_selector.setCurrentIndex(self.profile_selector.count() - 1)  # select last (i.e. newest) item

    def delete_profile(self):
        msgbox = QMessageBox()
        msgbox.setWindowTitle("Delete profile?")
        msgbox.setText("Are you sure you want to delete the current profile?")
        msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msgbox.setDefaultButton(QMessageBox.No)
        ret = msgbox.exec()

        if ret == QMessageBox.Yes:
            self.profilecon.delete_current_profile()
            self.profilecon.save_to_file()

            self.main.profileSelector.removeItem(self.main.profileSelector.currentIndex())  # update combobox in toolbar of mainwindow
            # needs to be done first, because modifying the combo box from the settings dialog updates the index of the combo box in the toolbar
            self.profile_selector.removeItem(self.profile_selector.currentIndex())

            self.profilecon.select_profile(self.profile_selector.currentText())