import unittest

class test_reducetypes (unittest.TestCase):
    def runTest(self):
        a, c, f, i, l, n = ('Any', 'complex', 'float', 'int', 'long', 'number')
        none = 'None'
        table = (
            ([i,i],     i),
            ([i],       i),
            ([f, i],    f),
            ([c, i],    c),
            ([l, a],    'Union[Any, long]'),
            # Handle None
            ([None],        none),
            ([None, None],  none),
            ([None, a, c],  'Union[Any, complex]'),
        )
        # Top-level functions
        def dump(title, s=None):
            if s:
                print('===== %s...\n%s\n' % (title, s.rstrip()))
            else:
                print('===== %s...\n' % title)
        def dump_dict(title, d):
            '''Dump a dictionary with a header.'''
            dump(title)
            for z in sorted(d):
                print('%30s %s' % (z, d.get(z)))
            print('')
        def dump_list(title, aList):
            '''Dump a list with a header.'''
            dump(title)
            for z in aList:
                print(z)
            print('')
        def is_known_type(s):
            '''
            Return True if s is nothing but a single known type.
            Recursively test inner types in square brackets.
            '''
            trace = False
            s1 = s
            s = s.strip()
            table = (
                # None,
                'None',
                'complex', 'float', 'int', 'long', 'number',
                'dict', 'list', 'tuple',
                'bool', 'bytes', 'str', 'unicode',
            )
            for s2 in table:
                if s2 == s:
                    return True
                elif Pattern(s2+'(*)', s).match_entire_string(s):
                    return True
            if s.startswith('[') and s.endswith(']'):
                inner = s[1:-1]
                return is_known_type(inner) if inner else True
            elif s.startswith('(') and s.endswith(')'):
                inner = s[1:-1]
                return is_known_type(inner) if inner else True
            elif s.startswith('{') and s.endswith('}'):
                return True ### Not yet.
                # inner = s[1:-1]
                # return is_known_type(inner) if inner else True
            table = (
                # Pep 484: https://www.python.org/dev/peps/pep-0484/
                # typing module: https://docs.python.org/3/library/typing.html
                'AbstractSet', 'Any', 'AnyMeta', 'AnyStr',
                'BinaryIO', 'ByteString',
                'Callable', 'CallableMeta', 'Container',
                'Dict', 'Final', 'Generic', 'GenericMeta', 'Hashable',
                'IO', 'ItemsView', 'Iterable', 'Iterator',
                'KT', 'KeysView', 'List',
                'Mapping', 'MappingView', 'Match',
                'MutableMapping', 'MutableSequence', 'MutableSet',
                'NamedTuple', 'Optional', 'OptionalMeta',
                # 'POSIX', 'PY2', 'PY3',
                'Pattern', 'Reversible',
                'Sequence', 'Set', 'Sized',
                'SupportsAbs', 'SupportsFloat', 'SupportsInt', 'SupportsRound',
                'T', 'TextIO', 'Tuple', 'TupleMeta',
                'TypeVar', 'TypingMeta',
                'Undefined', 'Union', 'UnionMeta',
                'VT', 'ValuesView', 'VarBinding',
            )
            for s2 in table:
                if s2 == s:
                    return True
                pattern = Pattern(s2+'[*]', s)
                if pattern.match_entire_string(s):
                    # Look inside the square brackets.
                    # if s.startswith('Dict[List'): g.pdb()
                    brackets = s[len(s2):]
                    assert brackets and brackets[0] == '[' and brackets[-1] == ']'
                    s3 = brackets[1:-1]
                    if s3:
                        return all([is_known_type(z.strip())
                            for z in split_types(s3)])
                    else:
                        return True
            if trace: g.trace('Fail:', s1)
            return False
        def main():
            '''
            The driver for the stand-alone version of make-stub-files.
            All options come from ~/stubs/make_stub_files.cfg.
            '''
            # g.cls()
            controller = StandAloneMakeStubFile()
            controller.scan_command_line()
            controller.scan_options()
            controller.run()
            print('done')
        def merge_types(a1, a2):
            '''
            a1 and a2 may be strings or lists.
            return a list containing both of them, flattened, without duplicates.
            '''
            # Not used at present, and perhaps never.
            # Only useful if visitors could return either lists or strings.
            assert a1 is not None
            assert a2 is not None
            r1 = a1 if isinstance(a1, (list, tuple)) else [a1]
            r2 = a2 if isinstance(a2, (list, tuple)) else [a2]
            return sorted(set(r1 + r2))
        def pdb(self):
            '''Invoke a debugger during unit testing.'''
            try:
                import leo.core.leoGlobals as leo_g
                leo_g.pdb()
            except ImportError:
                import pdb
                pdb.set_trace()
        def reduce_numbers(aList):
            '''
            Return aList with all number types in aList replaced by the most
            general numeric type in aList.
            '''
            found = None
            numbers = ('number', 'complex', 'float', 'long', 'int')
            for kind in numbers:
                for z in aList:
                    if z == kind:
                        found = kind
                        break
                if found:
                    break
            if found:
                assert found in numbers, found
                aList = [z for z in aList if z not in numbers]
                aList.append(found)
            return aList
        def reduce_types(aList, name=None, trace=False):
            '''
            Return a string containing the reduction of all types in aList.
            The --trace-reduce command-line option sets trace=True.
            If present, name is the function name or class_name.method_name.
            '''
            trace = False or trace
            def show(s, known=True):
                '''Bind the arguments to show_helper.'''
                return show_helper(aList[:], known, name, s, trace)
            while None in aList:
                aList.remove(None)
            if not aList:
                return show('None')
            r = sorted(set(aList))
            if not all([is_known_type(z) for z in r]):
                return show('Any', known=False)
            elif len(r) == 1:
                return show(r[0])
            if 'None' in r:
                kind = 'Optional'
                while 'None' in r:
                    r.remove('None')
                return show('Optional[%s]' % r[0])
            r = reduce_numbers(r)
            if len(r) == 1:
                return show(r[0])
            else:
                return show('Union[%s]' % (', '.join(sorted(r))))
        def show_helper(aList, known, name, s, trace):
            '''Show the result of the reduction.'''
            s = s.strip()
            if trace and (not known or len(aList) > 1):
                if name:
                    if name.find('.') > -1:
                        context = ''.join(name.split('.')[1:])
                    else:
                        context = name
                else:
                    context = g.callers(3).split(',')[0].strip()
                context = truncate(context, 26)
                known = '' if known else '? '
                pattern = sorted(set([z.replace('\n',' ') for z in aList]))
                pattern = '[%s]' % truncate(', '.join(pattern), 53-2)
                print('reduce_types: %-26s %53s ==> %s%s' % (context, pattern, known, s))
                    # widths above match the corresponding indents in match_all and match.
            return s
        def split_types(s):
            '''Split types on *outer level* commas.'''
            aList, i1, level = [], 0, 0
            for i, ch in enumerate(s):
                if ch == '[':
                    level += 1
                elif ch == ']':
                    level -= 1
                elif ch == ',' and level == 0:
                    aList.append(s[i1:i])
                    i1 = i+1
            aList.append(s[i1:].strip())
            return aList
        def truncate(s, n):
            '''Return s truncated to n characers.'''
            return s if len(s) <= n else s[:n-3] + '...'
        class Pattern(object):
            '''
            A class representing regex or balanced patterns.
            Sample matching code, for either kind of pattern:
                for m in reversed(pattern.all_matches(s)):
                    s = pattern.replace(m, s)
            '''
            def __init__ (self, find_s, repl_s=''):
                '''Ctor for the Pattern class.'''
                self.find_s = find_s
                self.repl_s = repl_s
                if self.is_regex():
                    self.regex = re.compile(find_s)
                elif self.is_balanced():
                    self.regex = None
                else:
                    # Escape all dangerous characters.
                    result = []
                    for ch in find_s:
                        if ch == '_' or ch.isalnum():
                            result.append(ch)
                        else:
                            result.append('\\'+ch)
                    self.regex = re.compile(''.join(result))
            def __eq__(self, obj):
                """Return True if two Patterns are equivalent."""
                if isinstance(obj, Pattern):
                    return self.find_s == obj.find_s and self.repl_s == obj.repl_s
                else:
                    return NotImplemented
            def __ne__(self, obj):
                """Return True if two Patterns are not equivalent."""
                return not self.__eq__(obj)
            def __hash__(self):
                '''Pattern.__hash__'''
                return len(self.find_s) + len(self.repl_s)
            def __repr__(self):
                '''Pattern.__repr__'''
                return '%s: %s' % (self.find_s, self.repl_s)
            __str__ = __repr__
            def is_balanced(self):
                '''Return True if self.find_s is a balanced pattern.'''
                s = self.find_s
                if s.endswith('*'):
                    return True
                for pattern in ('(*)', '[*]', '{*}'):
                    if s.find(pattern) > -1:
                        return True
                return False
            def is_regex(self):
                '''
                Return True if self.find_s is a regular pattern.
                For now a kludgy convention suffices.
                '''
                return self.find_s.endswith('$')
                    # A dollar sign is not valid in any Python expression.
            def all_matches(self, s):
                '''
                Return a list of match objects for all matches in s.
                These are regex match objects or (start, end) for balanced searches.
                '''
                trace = False
                if self.is_balanced():
                    aList, i = [], 0
                    while i < len(s):
                        progress = i
                        j = self.full_balanced_match(s, i)
                        if j is None:
                            i += 1
                        else:
                            aList.append((i,j),)
                            i = j
                        assert progress < i
                    return aList
                else:
                    return list(self.regex.finditer(s))
            def full_balanced_match(self, s, i):
                '''Return the index of the end of the match found at s[i:] or None.'''
                i1 = i
                trace = False
                if trace: g.trace(self.find_s, s[i:].rstrip())
                pattern = self.find_s
                j = 0 # index into pattern
                while i < len(s) and j < len(pattern) and pattern[j] in ('*', s[i]):
                    progress = i
                    if pattern[j:j+3] in ('(*)', '[*]', '{*}'):
                        delim = pattern[j]
                        i = self.match_balanced(delim, s, i)
                        j += 3
                    elif j == len(pattern)-1 and pattern[j] == '*':
                        # A trailing * matches the rest of the string.
                        j += 1
                        i = len(s)
                        break
                    else:
                        i += 1
                        j += 1
                    assert progress < i
                found = i <= len(s) and j == len(pattern)
                if trace and found:
                    g.trace('%s -> %s' % (pattern, s[i1:i]))
                return i if found else None
            def match_balanced(self, delim, s, i):
                '''
                delim == s[i] and delim is in '([{'
                Return the index of the end of the balanced parenthesized string, or len(s)+1.
                '''
                trace = False
                assert s[i] == delim, s[i]
                assert delim in '([{'
                delim2 = ')]}'['([{'.index(delim)]
                assert delim2 in ')]}'
                i1, level = i, 0
                while i < len(s):
                    progress = i
                    ch = s[i]
                    i += 1
                    if ch == delim:
                        level += 1
                    elif ch == delim2:
                        level -= 1
                        if level == 0:
                            if trace: g.trace('found: %s' % s[i1:i])
                            return i
                    assert progress < i
                # Unmatched: a syntax error.
                print('***** unmatched %s in %s' % (delim, s))
                return len(s) + 1
            def match(self, s, trace=False):
                '''
                Perform the match on the entire string if possible.
                Return (found, new s)
                '''
                trace = False or trace
                caller = g.callers(2).split(',')[0].strip()
                    # The caller of match_all.
                s1 = truncate(s,40)
                if self.is_balanced():
                    j = self.full_balanced_match(s, 0)
                    if j is None:
                        return False, s
                    else:
                        start, end = 0, len(s)
                        s = self.replace_balanced(s, start, end)
                        if trace:
                            g.trace('%-16s %30s %40s ==> %s' % (caller, self, s1, s))
                        return True, s
                else:
                    m = self.regex.match(s)
                    if m and m.group(0) == s:
                        s = self.replace_regex(m, s)
                        if trace:
                            g.trace('%-16s %30s %30s ==> %s' % (caller, self, s1, s))
                        return True, s
                    else:
                        return False, s
            def match_entire_string(self, s):
                '''Return True if s matches self.find_s'''
                if self.is_balanced():
                    j = self.full_balanced_match(s, 0)
                    return j is not None
                else:
                    m = self.regex.match(s)
                    return m and m.group(0) == s
            def replace(self, m, s):
                '''Perform any kind of replacement.'''
                if self.is_balanced():
                    start, end = m
                    return self.replace_balanced(s, start, end)
                else:
                    return self.replace_regex(m, s)
            def replace_balanced(self, s1, start, end):
                '''
                Use m (returned by all_matches) to replace s by the string implied by repr_s.
                Within repr_s, * star matches corresponding * in find_s
                '''
                trace = False
                s = s1[start:end]
                f, r = self.find_s, self.repl_s
                i1 = f.find('(*)')
                i2 = f.find('[*]')
                i3 = f.find('{*}')
                if -1 == i1 == i2 == i3:
                    return s1[:start] + r + s1[end:]
                j = r.find('*')
                if j == -1:
                    return s1[:start] + r + s1[end:]
                i = min([z for z in [i1, i2, i3] if z > -1])
                assert i > -1 # i is an index into f AND s
                delim = f[i]
                if trace: g.trace('head', s[:i], f[:i])
                assert s[:i] == f[:i], (s[:i], f[:i])
                if trace: g.trace('delim',delim)
                k = self.match_balanced(delim, s, i)
                s_star = s[i+1:k-1]
                if trace: g.trace('s_star',s_star)
                repl = r[:j] + s_star + r[j+1:]
                if trace: g.trace('repl',self.repl_s,'==>',repl)
                return s1[:start] + repl + s1[end:]
            def replace_regex(self, m, s):
                '''Do the replacement in s specified by m.'''
                s = self.repl_s
                for i in range(9):
                    group = '\\%s' % i
                    if s.find(group) > -1:
                        # g.trace(i, m.group(i))
                        s = s.replace(group, m.group(i))
                return s
        for aList, expected in table:
            got = reduce_types(aList)
            assert expected == got, (aList, 'expected:', expected, 'got', got)


from bottle import redirect, template

import bson

from app import app
import helper

@app.get( "/admin" )
def admin( mongodb ):
	user = helper.get_user( mongodb )

	if not user or 'admin' not in user.get( 'roles', [] ):
		redirect("/")

	return helper.template( 'admin/admin', user=user )

@app.get( "/admin/users" )
@app.get( "/admin/users/<index:int>" )
@app.get( "/admin/users/<index:int>/<count:int>" )
@app.get( "/admin/users/search/<search>" )
@app.get( "/admin/users/search/<search>/<index:int>" )
@app.get( "/admin/users/search/<search>/<index:int>/<count:int>" )
def admin_users( mongodb, search="", index=0, count=10 ):
	user = helper.get_user( mongodb )

	if not user or 'admin' not in user.get( 'roles', [] ):
		redirect("/")

	if len( search ) == 0:
		users = mongodb['users'].find().skip( index ).limit( count )
	else:
		users = mongodb['users'].find( { "name": search } ).skip( index ).limit( count )

	return helper.template( 'admin/admin', user=user, main=template( "admin/users", users=users ) )


#HOW-TO:
#...This file must be in the same folder with sentences.txt.
#...when launched for the first time, extra files and one directory will
#...be created automatically.

import os
import time
import csv
from random import shuffle
corpus = []
f = open("sentences.txt", "r")
for line in f:
	corpus.append(line)
if not os.path.isfile('tracker.txt'):
	open('tracker.txt', 'w')
f2 = open("tracker.txt", 'r')
tracker = []
for line in f2:
	tracker.append(line)
if not os.path.exists('Audio Data'):
	print('It looks like you are launching this Recorder for the first time')
	print('initilizing/creating necessary files...\n')
	os.mkdir('Audio Data')
if not os.path.isfile('counter.txt'):
	c = 0
	counterFile = open('counter.txt', 'w')
	counterFile.write(str(c))
	counterFile.close()
if not os.path.isfile('files.csv'):
	file = open('files.csv', 'a')
	fields = ('filename', 'sentence')
	wr = csv.DictWriter(file, fieldnames=fields, lineterminator = '\n')
	wr.writeheader()
	file.close()
def record(s):
	global name
	global counter
	counterFile = open('counter.txt', 'r')
	counter = int(counterFile.readline())
	done = False
	while not done:
		print('SENTENCE TO READ:    ' + s)
		start = int(input('WHEN READY, ENTER 1 TO START RECORDING '))
		if start == 1:
			import speech_recognition as sr
			r = sr.Recognizer()
			with sr.Microphone() as source:
				print ("START READING NOW\n")
				audio = r.listen(source)
			confirm = input('Confirm the recording? Y/N ')[0]
			if confirm == 'Y':
				done = True
				fn = "Audio Data/{}_audio_{}.wav".format(name, counter)
				with open(fn, "wb") as f:
					f.write(audio.get_wav_data())
					print('Audio file ' + fn + ' saved successfully\n')

def toCSV(s):
	global csvOpen
	global name
	global counter

	counterFile = open('counter.txt', 'r')
	counter = int(counterFile.readline())
	#print('CURRENT COUNTER : ' + str(counter))
	fn = "{}_audio_{}.wav".format(name, counter)
	counter = counter + 1
	file = open('files.csv', 'a')
	fields = ('filename', 'sentence')
	wr = csv.DictWriter(file, fieldnames=fields, lineterminator = '\n')
	#wr.writeheader()
	wr.writerow({'filename':fn, 'sentence': s})
	file.close()
	counterFile = open('counter.txt', 'w')
	counterFile.write(str(counter))
	print('Remaining sentences : ' + str(len(corpus)))
def switch():
	print("1 : RECORD NEXT SENTENCE\n 2 : QUIT\n ")
	option = int(input("YOUR OPTION :"))
	#print(option)
	def nex():
		if (len(corpus) == len(tracker)) or not corpus:
			print('All sentences have been shown\nEXITTING')
			exit()
		while True:
			sentence = corpus.pop(0)
			if sentence not in tracker:
				record(sentence)
				temp = open("tracker.txt", 'a')
				temp.write(sentence)
				toCSV(sentence)
				break
	def quit():
		print('ENDING')
		exit()
	dictionary = {
	1 : nex,
	2 : quit
	}
	dictionary.get(option)()

print('What is your name?')
name = input()
counter = 0
csvOpen = False
print('Welcome, ' + name + ', what would you like to do?\n')
while True:
	switch()


#! /usr/bin/env Python3

import PyPDF2
import os
"""
#print(os.getcwd())

os.chdir('/Users/ymccarter/PycharmProjects/Mihon/working_mihon/Renshu_folder/automationPython/FileDirectory')

pdfFile=open('/Users/ymccarter/Downloads/meetingminutes1.pdf','rb')

reader=PyPDF2.PdfFileReader(pdfFile)
reader.numPages
page=reader.getPage(0)
print(page.extractText())

for pageNum in range(reader.numPages): #shows contents of PDF
    print(reader.getPage(pageNum).extractText())

#SAY WE WANT TO COMBINE MULTIPE PDF FILE. IN THIS SCENARIO MEETINGMINUTE 1 AND 2:

os.chdir('/Users/ymccarter/PycharmProjects/Mihon/working_mihon/Renshu_folder/automationPython/FileDirectory')

pdfFile1=open('/Users/ymccarter/Downloads/meetingminutes1.pdf','rb')
pdfFile2=open('/Users/ymccarter/Downloads/meetingminutes2.pdf','rb')
reader1=PyPDF2.PdfFileReader(pdfFile1)
reader2=PyPDF2.PdfFileReader(pdfFile2)

print(reader1.numPages) # numPages in PyPDF2 will count the number of page
print(reader2.numPages)

# and you can use 'reader.getPage('page#') ' to take the object of specified page
#page.extractText() will show the text format of content

page=reader1.getPage(0)
print(page.extractText())

#you can create a loop to extract page contents too:

for pageNum in range(reader1.numPages):
    print(reader1.getPage(pageNum).extractText())
"""

#writer function

#create the loop and add each page to add each page of two PDFs

pdfFile1=open('/Users/ymccarter/Downloads/meetingminutes1.pdf','rb')
pdfFile2=open('/Users/ymccarter/Downloads/meetingminutes2.pdf','rb')
reader1=PyPDF2.PdfFileReader(pdfFile1)
reader2=PyPDF2.PdfFileReader(pdfFile2)

writer = PyPDF2.PdfFileWriter() #creating written object

for pageNum in range(reader1.numPages):
    page = reader1.getPage(pageNum)
    writer.addPage(page) #adding the file1 to written object

for pageNum in range(reader2.numPages):
    page = reader2.getPage(pageNum)
    writer.addPage(page) #adding the file2 on the top of file1 to the written object.

outputfile=open('combinedminutes.pdf','wb')
writer.write(outputfile)

pdfFile2.close()
pdfFile1.close()
outputfile.close()

pdfFile3=open('combinedminutes.pdf','rb')
reader3=PyPDF2.PdfFileReader(pdfFile3)

print(reader3.numPages)
for pageNum in range(reader3.numPages): #shows contents of PDF
    print(reader3.getPage(pageNum).extractText())


import numpy as np
import matplotlib.pyplot as plt
nx,ny,m= 1,1,100
X=np.random.rand(nx,m)
Wrand=np.random.rand(ny,nx)*100
Y= 4 + Wrand@X + np.random.randn(ny, m)
plt.scatter(X,Y)
W=np.zeros((ny,nx))
Wopt=(np.linalg.solve(X@X.T,X@Y.T)).T # Using Normal Equation without bias
X_= np.vstack((np.ones((1,m)),X))
Wopt_=(np.linalg.solve(X_@X_.T,X_@Y.T)).T # Using Normal Equation with bias
Hopt=Wopt@X
Hopt_=Wopt_@X_
plt.scatter(X,Y)
plt.scatter(X,Hopt)
plt.scatter(X,Hopt_)
b=np.zeros((ny,))
lr=0.01

def costfunc(X,Y,W,b,m):
    return np.sum((W@X + b - Y)**2)/m

def dcostfunc(X,Y,W,b,m):
    return ((W@X+b-Y)@X.T)*(2/m) , (np.sum(W@X+b-Y))*(2/m)

costfunc(X,Y,Wopt,Wopt,m)
costfunc(X,Y,W,b,m)

iterations=10000
costarr=np.zeros((iterations,))

# Using Gradient Descent for error minimisation
for i in range(iterations):
    costarr[i]=costfunc(X,Y,W,b,m)
    dcostW, dcostb=dcostfunc(X,Y,W,b,m)
    W=W-lr*dcostW
    b=b-lr*dcostb

plt.plot(np.arange(i+1),costarr)

Hfinal= W@X+b

plt.scatter(X,Y)
plt.scatter(X,Hfinal)

costfunc(X,Y,W,b,m)

# Using Standard Library for the same problem
from sklearn.linear_model import LinearRegression

model=LinearRegression()
model.fit(X.T,Y.T)
model.intercept_
model.coef_
model.score(X.T,Y.T)


"""hoard.log - Logging configuration for the hoard
server."""

import logging

from tornado.options import options

logging.basicConfig(format="%(message)s")
log = logging.getLogger(__name__)
file_handler = logging.FileHandler(options.log)
log_level = logging.INFO
if options.debug:
	log_level = logging.DEBUG
log.setLevel(log_level)
file_handler.setLevel(log_level)
file_formatter = logging.Formatter("%(asctime)s - %(message)s")
file_handler.setFormatter(file_formatter)
log.addHandler(file_handler)


from flask import Flask, request, jsonify
import random

def create_app():
    app = Flask(__name__)

    current_job = {
        "datetime_cleaned": "2020-11-21T03:55:42",
        "datetime_finished": "2020-11-21T03:50:32",
        "datetime_started": "2020-11-21T03:44:31",
        "name": "UM3E_Letter_V",
        "reprint_original_uuid": "dd30fe04-dea8-4d7e-89bc-4b49f83284e9",
        "result": "Printing",
        "source": "USB",
        "time_elapsed": 0,
        "time_estimated": 0,
        "time_total": 0,
        "uuid": "a8f8e030-b24b-490a-b145-ce5d900ad768"
    }

    @app.route('/printer/status')
    def get_status():
        return jsonify({'status': 'printing'}), 200

    @app.route('/printer/print_job')
    def get_print_job():
        return jsonify(current_job), 200

    @app.route('/printer/nozzles/temperatures')
    def get_temps():
        nozzle_1_temp_change = round(random.random() + random.randint(220, 225), 1)
        nozzle_2_temp_change = round(random.random() + random.randint(220, 225), 1)
        return jsonify({"nozzle_1": nozzle_1_temp_change, "nozzle_2": nozzle_2_temp_change}), 200

    return app

if __name__ == '__main__':
    create_app().run(port=5501)


from builtins import input
from robolearn.envs.simple_envs import CliffEnv

env_params = dict(
    desc=None,
    map_name='4x12',
    is_slippery=True,
    reward_dict=None,
    nA=4,
)
env = CliffEnv(**env_params)

# for ii in range(400):
#     env.reset()
#     env.render()

env.reset()
env.render()
# input('Press a key to start...')

for ii in range(50):
    action = env.action_space.sample()
    obs, reward, done, env_info = env.step(action)
    print('---'*3, ii, '---'*3)
    print('action -->', action)
    print('obs -->', obs)
    print('reward -->', reward)
    print('done -->', done)
    print('info -->', env_info)
    env.render()

input('Press a key to reset...')

env.reset()
env.render()

input('Press a key to close the script')


# TRAFFIC SHAPING : using simple Leaky bucket algorithm, implemented using multi threading concept in python.

import threading
import time
from random import randint, random

buffer = []
condition = threading.Condition()
BUFFER_LEN = 10

def packet_producer(e1):
    global buffer
    while(True):

        # lock acquire
        condition.acquire()
        # buffer should not be full.
        if(buffer.__len__() == BUFFER_LEN):
            new_pkt = randint(100, 1000)
            print(
                f" ======== Buffer is full! ---> waiting for consumer, Buffer :{buffer} \n")
            print(f" ======== Packet Lost :{new_pkt} \n")
            condition.wait()
            print(
                f" ======== Space in buffer! ---> Consumer consumed , Buffer :{buffer} \n")

        if(buffer.__len__() < BUFFER_LEN):
            while(buffer.__len__() < randint(2, 4)):
                new_pkt = randint(100, 1200)
                buffer.append(new_pkt)
                print(f" ======== New Packet added! ---> Buffer :{buffer} \n")

        # Notify consumer and lock release
        condition.notify()
        condition.release()
        if(e1.isSet()):
            break
        time.sleep(random())

def packet_consumer(bandwidth, e2):
    global buffer
    current_bw = bandwidth
    residue = 0
    packet = 0

    while(True):

        # lock acquire
        condition.acquire()
        if(buffer.__len__() == 0):
            print("--------> Empty Buffer! ---> consumer is waiting...\n")
            condition.wait()
            print("--------> consumer resumes. \n")

        if(residue == 0 and buffer.__len__() != 0):
            packet = buffer.pop(0)
        else:
            packet = residue
            residue = 0

        if(packet < current_bw):
            print(
                f" --------> Current BW :{current_bw}, Packet size :{packet}, Packet sent:{packet}, Remaining BW:{current_bw-packet} \n")
            current_bw = current_bw-packet
        else:
            print(
                f" --------> Current BW :{current_bw}, Packet size :{packet}, Packet sent:{current_bw}, Remaining BW:{0} \n")
            residue = packet-current_bw
            current_bw = bandwidth
            continue

        # lock release
        condition.notify()
        condition.release()
        if(e2.isSet()):
            break
        time.sleep(random())

def Leaky_bucket():
    bandwidth = int(
        input("\n Enter Bandwidth : \n"))

    e1 = threading.Event()
    e2 = threading.Event()

    producer_thread = threading.Thread(target=packet_producer, args=(e1,))
    consumer_thread = threading.Thread(
        target=packet_consumer, args=(bandwidth, e2,))

    producer_thread.start()
    consumer_thread.start()

    print("\n Producer executes join ! \n")
    producer_thread.join(1)
    print("\n Consumer executes join ! \n")
    consumer_thread.join(1)

    if producer_thread.is_alive():
        print(" \n Producer will be terminated ! \n")
        e1.set()

    if consumer_thread.is_alive():
        print(" \n Consumer will be terminated ! \n")
        e2.set()

Leaky_bucket()


import numpy as np
import pandas as pd
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
from ast import literal_eval

import credentials

class twitter_authenticator():

    def authenticate_twitter_app(self):
        auth=OAuthHandler(credentials.CONSUMER_KEY,credentials.CONSUMER_SECRET_KEY)
        auth.set_access_token(credentials.ACCESS_KEY,credentials.ACCESS_KEY_SECRET)
        return auth

class TwitterStreamer():

    def __init__(self):
        self.twitter_authenticate=twitter_authenticator()

    def stream_tweets(self,fetched_file_names):
        auth=self.twitter_authenticate.authenticate_twitter_app()
        listener=Streamy(fetched_file_names)
        stream=Stream(auth,listener)
        hashq=input("Hashtag you want\n")
        stream.filter(track=['#'+hashq])

class Streamy(StreamListener):
    def __init__(self,fetched_file_names):
        self.fetched_file_names=fetched_file_names

    def on_data(self,datas):
        try:
            parsed_json = (json.loads(datas))
            print(parsed_json)
            text=parsed_json['text']
            with open(self.fetched_file_names,'a') as tf:
                tf.write('\n'+text)
        except BaseException as e:
            print("Error on data %s" %str(e))
        return True

    def on_error(self,error):
        print(error)
        if error==420:
            return False

fetched_file_names="tweets.json"
twitter_streamer=TwitterStreamer()
twitter_streamer.stream_tweets(fetched_file_names)
f = open("tweets.json", "r")
df=pd.DataFrame(data=[x for x in f])
f.close()
print(df.head())


# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 17:20:10 2020

@author: soura
"""

import numpy as np
import cv2
import imutils
import matplotlib.pyplot as plt

path='D:/Download/Py/FLIR/10802955081600883676000.jpg'
image = cv2.imread(path) # path = path to your file

#image=image[240:,100:500]
#bin = cv2.inRange(image, (130, 180, 10), (160, 190,20)
#cv2.bitwise_not(bin, bin)
#cnts = cv2.findContours(bin.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#cnts = imutils.grab_contours(cnts)
#cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
#rect = cv2.boundingRect(cnts[0])
#cv2.rectangle(image, rect, (0,255,0), 1)

image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)

#(BRG)

# def top(image):
#     image=image[120:360,:]
#     cv2.imshow('Cropped',image)

# #Color range for roof
#     lower_red = np.array([220, 40, 30])
#     upper_red = np.array([240, 140,80])
#     mask_red = cv2.inRange(image, lower_red, upper_red)
#     contours,heir= cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#     cv2.drawContours(image, contours, -1, (0, 0, 0), 3)
#     cv2.imshow('Cont',image)

#     cnt = (contours[0])
#     area = cv2.contourArea(cnt)
#     print(area)
#     #M = cv2.moments(cnt)

#     if cv2.contourArea(cnt)>20000:

#         x,y,w,h = cv2.boundingRect(cnt)
#         print(x,y,w,h)
#         cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)
#         #cv2.drawContours(image,[box],0,(0,0,255),2)
#         cropped=image[y:y+h,x:x+w]
#         print (w)
#         # rect = cv2.minAreaRect(cnt)
#         # box = cv2.boxPoints(rect)
#         # box = np.int0(box)
#         # cv2.drawContours(image,[box],0,(0,0,255),2)
#         # print(box)
#         # cv2.drawContours(image,[box],0,(0,0,255),2)
#         # cv2.drawContours(image, contours, -1, (0, 0, 0), 3)
#         cv2.imshow("Color",image)
#         #cv2.imwrite("contours_green.jpg",image)
#         cv2.imshow("Cropped",cropped)

#         width=25
#         #width=float(input("Width of Building in feet:"))
#         ppf=width/w
#         return ppf

def lower(image,ppf):
    image=image[240:,400:]

    #Color range for roof
    lower_green = np.array([130, 140, 10])
    upper_green = np.array([160, 200,30])
    mask_green = cv2.inRange(image, lower_green, upper_green)
    contours,heir= cv2.findContours(mask_green, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(image, contours, -1, (0, 0, 0), 3)
    cv2.imshow('Cont',image)
    cnt = contours[0]
    M = cv2.moments(cnt)
    if cv2.contourArea(cnt)>700:

        x,y,w,h = cv2.boundingRect(cnt)
        print(x,y,w,h)
        cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)
        cv2.drawContours(image,[box],0,(0,0,255),2)
        cropped=image[y:y+h,x:x+w]

        rect = cv2.minAreaRect(cnt)
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        print(box)
        cv2.drawContours(image,[box],0,(0,0,255),2)
        cv2.drawContours(image, contours, -1, (0, 0, 0), 3)
        cv2.imshow("Color",image)
        #cv2.imwrite("contours_green.jpg",image)
        #cv2.imshow("Cropped",cropped)

        height=h*ppf*12
        return height

PPF=lower(image)
# Height=lower(image,PPF)
# print("Calculated Height:",Height,"inches")
cv2.imwrite("Box.jpg",image)
cv2.waitKey(0)


class AdventOfCode:

    def __init__(self, filename):
        with open(filename) as f:
            self.input = f.read().splitlines()

        self.map = Map()
        for line in self.input:
            self.map.add_coordinate(line)

    def part1(self):
        self.map.fill_map()
        return self.map.largest_region().area()

    def part2(self):
        self.map.build_central_region()
        return len(self.map.central_region)

class Map:

    def __init__(self):
        self.regions = []
        self.min_x = None
        self.max_x = None
        self.min_y = None
        self.max_y = None
        self.biggest_region = None
        self.central_region = set()

    def add_coordinate(self, xy):
        self.regions.append(Region(xy, len(self.regions)))

    def find_region(self, x, y):
        distances = [(x - r.x if x > r.x else r.x - x) + (y - r.y if y > r.y else r.y - y) for r in self.regions]

        d = min(distances)
        return self.regions[distances.index(d)] if distances.count(d) == 1 else None

    def total_distance(self, x, y):
        return sum(list(map(lambda r: r.distance_to_center(x, y), self.regions)))

    def find_bounding_box(self):
        self.min_x = float('inf')
        self.max_x = 0
        self.min_y = float('inf')
        self.max_y = 0

        for r in self.regions:
            self.min_x = self.min_x if self.min_x < r.x else r.x
            self.max_x = self.max_x if self.max_x > r.x else r.x

            self.min_y = self.min_y if self.min_y < r.y else r.y
            self.max_y = self.max_y if self.max_y > r.y else r.y

    def fill_map(self):
        if self.min_x is None:
            self.find_bounding_box()

        for x in range(self.min_x+1, self.max_x):
            for y in range(self.min_y+1, self.max_y):

                region = self.find_region(x, y)
                if region:
                    region.add_point(x, y)

        for y in range(self.min_y, self.max_y + 1):
            for x in [self.min_x, self.max_x]:
                region = self.find_region(x, y)
                if region:
                    region.border_region = True

        for x in range(self.min_x, self.max_x + 1):
            for y in [self.min_y, self.max_y]:
                region = self.find_region(x, y)
                if region:
                    region.border_region = True

    def build_central_region(self):
        if self.min_x is None:
            self.find_bounding_box()

        for x in range(self.min_x, self.max_x + 1):
            for y in range(self.min_y, self.max_y + 1):

                if self.total_distance(x, y) < 10000:
                    self.central_region.add((x, y))

    def largest_region(self):
        if not self.biggest_region:
            self.biggest_region = self.regions[0]
            for r in self.regions:
                self.biggest_region = self.biggest_region if self.biggest_region.area() > r.area() else r

        return self.biggest_region

class Region:

    def __init__(self, xy, region_id):
        self.id = region_id

        xy = xy.split(', ')
        self.x = int(xy[0])
        self.y = int(xy[1])

        self.points = set()
        self.border_region = False

        self.furthest_distance = -1

    def distance_to_center(self, x, y):
        return (x - self.x if x > self.x else self.x - x) + (y - self.y if y > self.y else self.y - y)

    def add_point(self, x, y):
        self.points.add((x, y))

    def area(self):
        if self.border_region:
            return -1
        else:
            return len(self.points)


from PIL import Image

img = Image.open("oxygen.png", "r")

result = ""
lastRGB = 0

for x in range(int(img.width/7)):
    y = img.height / 2
    rgb = img.getpixel((x*7, y))
    if rgb[0] == rgb[1] and rgb[0] == rgb[2]:
        lastRGB = rgb[0]
        result += chr(lastRGB)
print(result)

print("")

arr = [105, 110, 116, 101, 103, 114, 105, 116, 121]

result = ""
for i in arr:
    result += chr(i)
print(result)


# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

from marshmallow import ValidationError, fields, validate, validates_schema

from polyaxon_schemas.base import BaseConfig, BaseSchema
from polyaxon_schemas.ops.environments.base import EnvironmentSchema
from polyaxon_schemas.ops.logging import LoggingSchema

class BuildBackend(object):
    NATIVE = 'native'
    KANIKO = 'kaniko'
    OTHER = 'other'

    VALUES = [NATIVE, KANIKO, OTHER]

def validate_image(image):
    if not image:
        return image
    if ' ' in image:
        raise ValidationError('Invalid docker image `{}`'.format(image))
    tagged_image = image.split(':')
    if len(tagged_image) > 3:
        raise ValidationError('Invalid docker image `{}`'.format(image))
    if len(tagged_image) == 3 and ('/' not in tagged_image[1] or tagged_image[1].startswith('/')):
        raise ValidationError('Invalid docker image `{}`'.format(image))

def validate_backend(backend):
    if backend and backend not in BuildBackend.VALUES:
        raise ValidationError('Build backend `{}` not supported'.format(backend))

def validate_build(image, dockerfile):
    build_data = [image, dockerfile]
    if all(build_data):
        raise ValidationError(
            'Invalid Build, only a dockerfile or image is required not both.'
            'received: image: `{}` and dockerfile: `{}`'.format(
                image,
                dockerfile
            ))
    if not any(build_data):
        raise ValidationError(
            'Invalid Build, a dockerfile or an image is required, received none.')

class BuildSchema(BaseSchema):
    version = fields.Int(allow_none=None)
    kind = fields.Str(allow_none=None, validate=validate.Equal('build'))
    logging = fields.Nested(LoggingSchema, allow_none=None)
    tags = fields.List(fields.Str(), allow_none=None)
    environment = fields.Nested(EnvironmentSchema, allow_none=True)
    backend = fields.Str(allow_none=True, validate=validate.OneOf(BuildBackend.VALUES))
    dockerfile = fields.Str(allow_none=True)
    context = fields.Str(allow_none=True)
    image = fields.Str(allow_none=True)
    build_steps = fields.List(fields.Str(), allow_none=True)
    env_vars = fields.List(fields.List(fields.Raw(), validate=validate.Length(equal=2)),
                           allow_none=True)
    commit = fields.Str(allow_none=True)
    branch = fields.Str(allow_none=True)
    nocache = fields.Boolean(allow_none=True)

    @staticmethod
    def schema_config():
        return BuildConfig

    @validates_schema
    def validate_image(self, data):
        """Validates docker image structure"""
        validate_image(data.get('image'))

    @validates_schema
    def validate_backend(self, data):
        """Validate backend"""
        validate_backend(data.get('backend'))

    @validates_schema
    def validate_config(self, data):
        validate_build(image=data.get('image'), dockerfile=data.get('dockerfile'))

class BuildConfig(BaseConfig):
    SCHEMA = BuildSchema
    IDENTIFIER = 'build'
    REDUCED_ATTRIBUTES = [
        'kind',
        'version',
        'logging',
        'tags',
        'environment',
        'build_steps',
        'env_vars',
        'nocache',
        'branch',
        'commit',
        'backend',
        'context',
        'dockerfile',
        'image'
    ]

    def __init__(self,
                 kind=None,
                 version=None,
                 logging=None,
                 tags=None,
                 environment=None,
                 dockerfile=None,
                 image=None,
                 context=None,
                 backend=None,
                 build_steps=None,
                 env_vars=None,
                 nocache=None,
                 commit=None,
                 branch=None):
        validate_image(image)
        validate_backend(backend)
        validate_build(image=image, dockerfile=dockerfile)
        self.kind = kind
        self.version = version
        self.logging = logging
        self.tags = tags
        self.environment = environment
        self.dockerfile = dockerfile
        self.context = context
        self.backend = backend
        self.image = image
        self.build_steps = build_steps
        self.env_vars = env_vars
        self.nocache = nocache
        self.commit = commit
        self.branch = branch

    @property
    def image_tag(self):
        if not self.image:
            return None
        tagged_image = self.image.split(':')
        if len(tagged_image) == 1:
            return 'latest'
        if len(tagged_image) == 2:
            return 'latest' if '/' in tagged_image[-1] else tagged_image[-1]
        if len(tagged_image) == 3:
            return tagged_image[-1]


from pokerbots.game.actions import Check, Bet, Raise, Fold, Call
from random import randint

class Testbot:
    def __init__(self):
        self.name = "testbot"
        self.hand = None
        self.stack = None

    def get_name(self):
        return self.name

    def respond(self, state):

        for action in state['legal_actions']:
            if isinstance(action, Raise):
                if randint(0, 100) < 30:
                    return Raise(action.amount)
                elif isinstance(action, Call):
                    return Call()
        for action in state['legal_actions']:
            if isinstance(action, Call):
                return Call()
        return Check()


import difflib
from itertools import combinations

with open('day2.in') as f:
    box_ids = [r.strip() for r in f.readlines()]

# Part 1
two = set()
three = set()
for box_id in box_ids:
    for c in box_id:
        if box_id.count(c) == 2:
            two.add(box_id)
        elif box_id.count(c) == 3:
            three.add(box_id)
print(f'Day 2 Part 1: {len(two) * len(three)}')  # 7221

# Part 2
id1 = id2 = ''
for box1, box2 in combinations(box_ids, 2):
    ratio = difflib.SequenceMatcher(None, box1, box2).ratio()
    if ratio == (len(box1)-1)/len(box1):
        id1, id2 = box1, box2
        break
# Unpack and find common characters
common = ''
for c in id1:
    if c in id2:
        common += c
print(f'Day 2 Part 2: {common}')  # mkcdflathzwsvjxrevymbdpoq


#!/usr/bin/python

from gpiozero import CPUTemperature
from time import sleep, strftime, time
from csv import writer
import os
import random

cpu = CPUTemperature()

#Define header for csv log files
header_temp = ['time', 'temperature', 'arus', 'battery']

#Specify direcroty path of sensor log
dirpath = os.path.dirname(os.path.realpath(__file__))
filename_sensor = dirpath + '/log/sensor-now.txt'

updateSensor = 300 #second interval update
tt = time() #temp initial timer
tn = time()

print("Logging Temperature")

def get_sensor_data(temperature, current, voltage):
	sensor_data = []
	sensor_data.append(strftime("%Y-%m-%d %H:%M:%S"))
	sensor_data.append(temperature)
	sensor_data.append(current)
	sensor_data.append(voltage)

	return sensor_data

def write_sensor(filename, data):
	with open(filename, 'a') as log:
		file_is_empty = os.stat(filename).st_size == 0
		temp_writer = writer(log, lineterminator='\n')
		if file_is_empty:
			temp_writer.writerow(header_temp)
		temp_writer.writerow(data)

def sensor_now(filename, temp, current, voltage):
	with open(filename, 'w') as now:
		now.write(str(temp) + '\n')
		now.write(str(current) + '\n')
		now.write(str(voltage) + '\n')

while True:
	filename_date = strftime("%Y-%m")
	filename_log = dirpath + '/log/' + filename_date + '.csv'
	temp = cpu.temperature
	curr = random.randint(10,80)
	volt = random.randint(60,100)
	sensorData = get_sensor_data(temp, curr, volt)
	t1 = time()
	t2 = time()
	if t1 - tt >= updateSensor:
		write_sensor(filename_log, sensorData)
		tt = time()

	if t2 - tn >= 5:
		sensor_now(filename_sensor, cpu.temperature, curr, volt)
		tn = time()