#!/usr/bin/python

import sys
import time
import os
import fnmatch
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
from datetime import datetime
from datetime import timedelta
from glob import glob
import pygsf
import shapefile

def main():
	parser = ArgumentParser(description='Read GSF file and create an ESRI shape file of the trackplot.',
			epilog='Example: \n To convert a single file use -i c:/temp/myfile.gsf \n to convert GSF files in a folder use -i c:/temp/*.gsf\n To convert all .GSF files recursively in a folder, use -r -i c:/temp \n To convert all files recursively from the current folder, use -r -i ./ \n', formatter_class=RawTextHelpFormatter)
	parser.add_argument('-i', dest='inputFile', action='store', help='-i <filename.gsf> : input filename to process. It can also be a wildcard, e.g. *.gsf')
	parser.add_argument('-o', dest='outputFile', action='store', default='track.shp', help='-o <SHPfilename.shp> : output filename to create. e.g. trackplot.shp [Default: track.shp]')
	parser.add_argument('-s', dest='step', action='store', default='1', help='step size in seconds.  Useful to reduce the complexity of the feature, which keeps ArcMap fastt. [Default: 1]')
	parser.add_argument('-r', action='store_true', default=False, dest='recursive', help='-r : search recursively.  [Default: False]')
	if len(sys.argv)==1:
		parser.print_help()
		sys.exit(1)

	args = parser.parse_args()
	# we need to remember the previous record so we only create uniq values, not duplicates
	fileOut = args.outputFile
	stepSize = float(args.step)
	if not fileOut.lower().endswith('.shp'):
		fileOut += '.shp'

	fileCounter=0
	matches = []
	lastTimeStamp = 0
	trackRecordCount = 0

	if args.recursive:
		for root, dirnames, filenames in os.walk(os.path.dirname(args.inputFile)):
			for f in fnmatch.filter(filenames, '*.GSF'):
				matches.append(os.path.join(root, f))
				print (matches[-1])
	else:
		for filename in glob(args.inputFile):
			matches.append(filename)
		print (matches)
	if len(matches) == 0:
		print ("Nothing found to convert, quitting")
		exit()

	if os.path.isfile(fileOut):
		try:
			# Create a shapefile reader
			r = shapefile.Reader(fileOut)
			# Create a shapefile writer
			# using the same shape type
			# as our reader
			w = shapefile.Writer(r.shapeType)
			# Copy over the existing dbf fields
			w.fields = list(r.fields)
			# Copy over the existing dbf records
			w.records.extend(r.records())
			# Copy over the existing polygons
			w._shapes.extend(r.shapes())
		except shapefile.error:
			print ("Problem opening existing shape file, aborting!")
			exit()
	else:
		# w = shapefile.Writer(shapefile.POINTZ)
		w = shapefile.Writer(shapefile.POLYLINE)
		w.autoBalance = 1
		w.field("LineName", "C")
		# w.field("WaterDepth", "N")
		w.field("UNIXTime", "N")
		w.field("SurveyDate", "D")

	for filename in matches:
		# print ("processing file: %s" % filename)
		line_parts = []
		line = []

		r = pygsf.GSFREADER(filename)
		start_time = time.time() # time  the process
		navigation = r.loadnavigation()
		for update in navigation:
			if update[0] - lastTimeStamp > stepSize:
				line.append([float(update[1]),float(update[2])])
				trackRecordCount += 1
				lastTimeStamp = update[0]
		# now add the very last update
		line.append([float(navigation[-1][1]),float(navigation[-1][2])])

		line_parts.append(line)
		w.line(parts=line_parts)
		# now add to the shape file.
		recTimeStamp = from_timestamp(navigation[0][0]).strftime("%Y/%m/%d %H:%M:%S")
		recDate = from_timestamp(navigation[0][0]).strftime("%Y%m%d")
		# depth = 1111.123
		w.record(os.path.basename(filename), int(navigation[0][0]), recDate)
		# w.record(os.path.basename(filename), depth, navigation[0][0], recDate)

		update_progress("Processed: %s (%d/%d)" % (filename, fileCounter, len(matches)), (fileCounter/len(matches)))
		lastTimeStamp = update[0]
		fileCounter +=1
		r.close()

	update_progress("Process Complete: ", (fileCounter/len(matches)))
	print ("Saving shapefile: %s position updates added %d" % (fileOut, trackRecordCount))
	w.save(fileOut)

	# now write out a prj file so the data has a spatial Reference
	f = open(fileOut.replace('.shp','.prj'), 'w')
	f.write('GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]') # python will convert \n to os.linesep
	f.close() # you can omit in most cases as the destructor will call it
	print("Duration %.3fs" % (time.time() - start_time )) # time the process

def from_timestamp(unixtime):
	return datetime(1970, 1 ,1) + timedelta(seconds=unixtime)

def update_progress(job_title, progress):
	length = 20 # modify this to change the length
	block = int(round(length*progress))
	msg = "\r{0}: [{1}] {2}%".format(job_title, "#"*block + "-"*(length-block), round(progress*100, 2))
	if progress >= 1: msg += " DONE\r\n"
	sys.stdout.write(msg)
	sys.stdout.flush()

if __name__ == "__main__":
	main()


import os

import hashids
from flask import Flask, request, jsonify, render_template, g, redirect, url_for
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from qultig import handler

app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])

# Add enumerate function
app.jinja_env.globals['enumerate'] = enumerate

def connect_db():
    """Connects to the specific database."""
    engine = create_engine(app.config['DATABASE_URI'], echo=False)
    Session = sessionmaker(bind=engine)
    return Session()

def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'database'):
        g.database = connect_db()
    return g.database

def redirect_to_art():
    """Redirect to art page"""
    db = get_db()
    h = hashids.Hashids(salt=app.config['HASH_SALT'])
    new_quiz = handler.build_art_quiz(db, handler.CategoryDistribution())
    return redirect(url_for('art', q=h.encode(new_quiz.id)))

@app.route('/')
def show_entries():
    return redirect_to_art()

@app.route('/art', methods=['GET'])
def art():
    try:
        db = get_db()
        h = hashids.Hashids(salt=app.config['HASH_SALT'])

        # Attempt to obtain the quid id
        decoded_tuple = h.decode(request.args['q'])
        quiz_id = int(decoded_tuple[0])
        quiz = handler.get_art_quiz(db, quiz_id)

    except (KeyError, IndexError, handler.HandlerError, ValueError):
        return redirect_to_art()

    return render_template('art.html', items=quiz.items, quiz_url=request.url)

@app.route('/evaluate_art', methods=['POST'])
def evaluate():
    response = handler.Response(item_id=int(request.form.get('item_id')),
                                option_id=int(request.form.get('option_id')))
    db = get_db()
    feedback = handler.get_art_feedback(db, response)
    return jsonify(correct=feedback.correct, labels=feedback.labels)

if __name__ == '__main__':
    app.run()


import luigi
import json
import mysql.connector
from transformTask import TransformTask

'''
    Variables
'''

# Target database
target_db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '',
    'database': 'wt_recommender'
}

'''
    Global functions
'''

# Function to load the data from the previous version
def load_previous_data(version):
    previous_version = version - 1
    filename = f'transformed_data_v{previous_version}.json'
    previous_data = {}
    try:
        previous_target = luigi.LocalTarget(filename)
        if previous_target.exists():
            with previous_target.open('r') as input_file:
                previous_data = json.load(input_file)
    except FileNotFoundError:
        pass
    return previous_data

'''
    Load tasks

    Every table that is loaded is split into a different task.
    This way we can parallel run multiple tasks using Luigi's requirement
    design pattern.
'''

# Load User_DIM
class LoadUserDim(luigi.Task):
    version = luigi.IntParameter(default=1)

    def requires(self):
        return TransformTask(version=self.version)

    def run(self):
        with self.input().open('r') as input_file:
            transformed_data = json.load(input_file)

        # Load the previously loaded data from file
        previous_data = load_previous_data(self.version)

        destination_conn = mysql.connector.connect(**target_db_config)
        destination_cursor = destination_conn.cursor()

        # Load data into User_DIM table with new surrogate keys for new entries
        self.load_user_dim(destination_cursor, transformed_data['User_DIM'], previous_data.get('User_DIM', []))

        destination_conn.commit()  # Commit the changes
        destination_conn.close()  # Close the connection

        # Make a .txt to log the version
        with self.output().open('w') as output_file:
            output_file.write(str(self.version))

    # Load data into User_DIM table with new surrogate keys for new entries
    def load_user_dim(self, cursor, data, previous_data):
        previous_user_ids = set(entry[0] for entry in previous_data)
        values = []
        for row in data:
            if row[0] not in previous_user_ids:
                values.append(row[0])

        # Combine all the to be inserted values into one SQL statement
        if values:
            sql = f"INSERT INTO User_DIM (user_id) VALUES (%s)"
            cursor.executemany(sql, [(value,) for value in values])

    def output(self):
        filename = f'user_load_complete_v{self.version}.txt'
        return luigi.LocalTarget(filename)

# Load Keyword_DIM
class LoadKeywordDim(luigi.Task):
    version = luigi.IntParameter(default=1)

    def requires(self):
        return TransformTask(version=self.version)

    def run(self):
        with self.input().open('r') as input_file:
            transformed_data = json.load(input_file)

        # Load the previously loaded data from file
        previous_data = load_previous_data(self.version)

        destination_conn = mysql.connector.connect(**target_db_config)
        destination_cursor = destination_conn.cursor()

        # Load data into Keyword_DIM table with new surrogate keys for new entries
        self.load_keyword_dim(destination_cursor, transformed_data['Keyword_DIM'], previous_data.get('Keyword_DIM', []))

        destination_conn.commit()  # Commit the changes
        destination_conn.close()  # Close the connection

        # Make a .txt to log the version
        with self.output().open('w') as output_file:
            output_file.write(str(self.version))

    # Load data into Keyword_DIM table with new surrogate keys for new entries
    def load_keyword_dim(self, cursor, data, previous_data):
        previous_keyword_ids = set(entry[0] for entry in previous_data)
        values = []
        for row in data:
            if row[0] not in previous_keyword_ids:
                values.append(row[0])

        # Combine all the to be inserted values into one SQL statement
        if values:
            sql = f"INSERT INTO Keyword_DIM (keyword_id) VALUES (%s)"
            cursor.executemany(sql, [(value,) for value in values])

    def output(self):
        filename = f'keyword_load_complete_v{self.version}.txt'
        return luigi.LocalTarget(filename)

# Load Book_DIM
class LoadBookDim(luigi.Task):
    version = luigi.IntParameter(default=1)

    def requires(self):
        return TransformTask(version=self.version)

    def run(self):
        with self.input().open('r') as input_file:
            transformed_data = json.load(input_file)

        # Load the previously loaded data from file
        previous_data = load_previous_data(self.version)

        destination_conn = mysql.connector.connect(**target_db_config)
        destination_cursor = destination_conn.cursor()

        # Load data into Book_DIM table with new surrogate keys for new entries
        self.load_book_dim(destination_cursor, transformed_data['Book_DIM'], previous_data.get('Book_DIM', []))

        destination_conn.commit()  # Commit the changes
        destination_conn.close()  # Close the connection

        # Make a .txt to log the version
        with self.output().open('w') as output_file:
            output_file.write(str(self.version))

    # Load data into Book_DIM table with new surrogate keys for new entries
    def load_book_dim(self, cursor, data, previous_data):
        previous_book_ids = {entry[0] for entry in previous_data}
        insert_values = []
        update_values = []

        for row in data:
            book_id = row[0]
            writer = row[1]
            avg_score = row[2]

            # If the book exists in previous_data, check if writer has changed
            if book_id in previous_book_ids:
                for prev_row in previous_data:
                    if prev_row[0] == book_id:
                        if prev_row[1] != writer:
                            update_values.append((writer, book_id))
                        break
            else:
                insert_values.append((book_id, writer, avg_score))

        # Insert new books
        if insert_values:
            insert_sql = f"INSERT INTO Book_DIM (book_id, writer, avg_score) VALUES (%s, %s, %s)"
            cursor.executemany(insert_sql, insert_values)

        # Update writer of edited books new value
        if update_values:
            update_sql = "UPDATE Book_DIM SET writer = %s WHERE book_id = %s"
            cursor.executemany(update_sql, update_values)

    def output(self):
        filename = f'book_load_complete_v{self.version}.txt'
        return luigi.LocalTarget(filename)

# Load Book_Keyword_FACT
class LoadBookKeywordFact(luigi.Task):
    version = luigi.IntParameter(default=1)

    # The new books and keywords have to be loaded to access the surrogate keys
    def requires(self):
        return [TransformTask(version=self.version), LoadBookDim(version=self.version),LoadKeywordDim(version=self.version)]

    def run(self):
        with self.input()[0].open('r') as input_file:
            transformed_data = json.load(input_file)

        # Load the previously loaded data from file
        previous_data = load_previous_data(self.version)

        destination_conn = mysql.connector.connect(**target_db_config)
        destination_cursor = destination_conn.cursor()

        # Load data into Book_Keyword_FACT table with new surrogate keys and foreign key mappings
        self.load_book_keyword_fact(destination_cursor, transformed_data['Book_Keyword_FACT'], previous_data.get('Book_Keyword_FACT', []))

        destination_conn.commit()  # Commit the changes
        destination_conn.close()  # Close the connection

        # Save the current version in log when complete
        with self.output().open('w') as output_file:
            output_file.write(str(self.version))

    # Load data into Book_Keyword_FACT table with new surrogate keys and foreign key mappings
    def load_book_keyword_fact(self, cursor, data, previous_data):
        previous_entries = set(tuple(entry) for entry in previous_data)
        insert_values = []

        for row in data:
            if tuple(row) not in previous_entries:
                book_id = row[0]
                keyword_id = row[1]
                insert_values.append((book_id, keyword_id))

        # Limit batch size for this dataset
        max_values_per_insert = 5000

        # Split the insert_values into chunks of maximum size
        value_chunks = [insert_values[i:i+max_values_per_insert] for i in range(0, len(insert_values), max_values_per_insert)]

        # Execute the INSERT statements for each value chunk
        for values in value_chunks:
            insert_sql = f"""INSERT INTO Book_Keyword_FACT (book_key, keyword_key) VALUES
                                    ((SELECT book_key FROM Book_DIM WHERE book_id = %s),
                                    (SELECT keyword_key FROM Keyword_DIM WHERE keyword_id = %s))"""
            cursor.executemany(insert_sql, values)

    def output(self):
        filename = f'bookKeywordFactLoaded_v{self.version}.txt'
        return luigi.LocalTarget(filename)

# Load Review_FACT
class LoadReviewFact(luigi.Task):
    version = luigi.IntParameter(default=1)

    def requires(self):
        return [TransformTask(version=self.version), LoadBookDim(version=self.version),LoadUserDim(version=self.version)]

    def run(self):
        with self.input()[0].open('r') as input_file:
            transformed_data = json.load(input_file)

        # Load the previously loaded data from file
        previous_data = load_previous_data(self.version)

        destination_conn = mysql.connector.connect(**target_db_config)
        destination_cursor = destination_conn.cursor()

        # Load data into Review_FACT table with new surrogate keys and foreign key mappings
        self.load_review_fact(destination_cursor, transformed_data['Review_FACT'], previous_data.get('Review_FACT', []))

        destination_conn.commit()  # Commit the changes
        destination_conn.close()  # Close the connection

        with self.output().open('w') as output_file:
            output_file.write(str(self.version))

    # Load data into Review_FACT table with new surrogate keys and foreign key mappings
    def load_review_fact(self, cursor, data, previous_data):
        previous_entries = set(tuple(entry) for entry in previous_data)
        insert_values = []

        for row in data:
            if tuple(row) not in previous_entries:
                review_id = row[0]
                user_id = row[1]
                book_id = row[2]
                rating = row[3]
                insert_values.append((review_id, rating, book_id, user_id))

        # Combine all the to be inserted values into one SQL statement
        if insert_values:
            insert_sql = f"""INSERT INTO review_fact (review_id, rating, book_key, user_key)
                VALUES (%s, %s,
                (SELECT book_key FROM Book_DIM WHERE book_id = %s),
                (SELECT user_key FROM User_DIM WHERE user_id = %s))"""
            cursor.executemany(insert_sql, insert_values)

    def output(self):
        filename = f'reviewFactLoaded_v{self.version}.txt'
        return luigi.LocalTarget(filename)

# Load Loan_FACT
class LoadLoanFact(luigi.Task):
    version = luigi.IntParameter(default=1)

    def requires(self):
        return [TransformTask(version=self.version), LoadBookDim(version=self.version),LoadUserDim(version=self.version)]

    def run(self):
        with self.input()[0].open('r') as input_file:
            transformed_data = json.load(input_file)

        # Load the previously loaded data from file
        previous_data = load_previous_data(self.version)

        destination_conn = mysql.connector.connect(**target_db_config)
        destination_cursor = destination_conn.cursor()

        # Load data into Review_FACT table with new surrogate keys and foreign key mappings
        self.load_loan_fact(destination_cursor, transformed_data['Loan_FACT'], previous_data.get('Loan_FACT', []))

        destination_conn.commit()  # Commit the changes
        destination_conn.close()  # Close the connection

        with self.output().open('w') as output_file:
            output_file.write(str(self.version))

    # Load data into Loan_FACT table with new surrogate keys and foreign key mappings
    def load_loan_fact(self, cursor, data, previous_data):
        previous_entries = {tuple(entry) for entry in previous_data}
        insert_values = []
        update_values = []

        for row in data:
            # If loan exists in previous_data, check if return_date has changed
            if tuple(row) in previous_entries:
                for prev_row in previous_data:
                    if tuple(prev_row) == tuple(row):
                        if prev_row['return_date'] != row['return_date']:
                            update_values.append((row['return_date'], row['loan_id']))
                        break
            # If it is a new loan, add it to the to be inserted list
            else:
                insert_values.append((
                    row['loan_id'],
                    row['loan_date'],
                    row['return_date'],
                    row['employee_id'],
                    row['book_id']
                ))

        # Insert new loans
        if insert_values:
            insert_sql = f"""INSERT INTO Loan_FACT (loan_id, loan_date, return_date, user_key, book_key) VALUES (%s, %s, %s,
                                    (SELECT user_key FROM User_DIM WHERE user_id = %s),
                                    (SELECT book_key FROM Book_DIM WHERE book_id = %s)) """
            cursor.executemany(insert_sql, insert_values)

        # Update edited loans
        if update_values:
            update_sql = "UPDATE Loan_FACT SET return_date = %s WHERE loan_id = %s"
            cursor.executemany(update_sql, update_values)

    def output(self):
        filename = f'loanFactLoaded_v{self.version}.txt'
        return luigi.LocalTarget(filename)


"""
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        # first thought, add characters if unique, when we find a duplicate
        # find the occurance of that letter and remove everything before it.
        # keep a rolling window of the substring.
        # O(s+l) time/space, s is input, l is subsequence // find on l
        # since l < s, O(2s) -> O(s)
        temp_str = ""
        max_temp_len = 0
        current_temp_len = 0
        for index in range(len(s)):
            current_letter = s[index]
            if current_letter not in temp_str:
                temp_str += current_letter
                current_temp_len = len(temp_str)
                if current_temp_len > max_temp_len:
                    max_temp_len = current_temp_len
            else:
                # find duplicate
                duplicate = temp_str.index(current_letter)
                # remove all the characters before the duplicate we are adding
                # if duplicate was the last character we saw, set empty string
                if duplicate == len(temp_str):
                    temp_str = ""
                # otherwise remove all the previous characters before duplicate
                else:
                    temp_str = temp_str[duplicate+1:]
                    temp_str += current_letter
                # no need to update current_temp_len or max_temp_len as we are not adding
        return max_temp_len


from django.shortcuts import render,redirect, get_object_or_404
from .models import Video, Comment_Model, ReplyModel, Rating
from .forms import VideoUpload, CommentForm, ReplyCommentForm, RatingForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect

# Create your views here.

@login_required(login_url='login')
def file_upload(request):
    form = VideoUpload()
    user_id = User.objects.get(id=request.user.id)
    if request.method == 'POST':
        form = VideoUpload(request.POST or None, request.FILES or None)
        if form.is_valid():
            form_obj = form.save(commit=False)
            form_obj.user = user_id
            form_obj.save()
            return redirect('profile')
    return render(request, 'app/upload.html', {'form': form})

def show_video(request): # Show Video List in UI
    videos= Video.objects.filter(make_privet=False).order_by('-created_on')
    if videos is not None:
        return render(request, 'app/index.html', {'video': videos})

@login_required(login_url='login')
def add_ratting(request, video_id):
    url = request.META.get('HTTP_REFERER')

    if request.method == 'POST':
        try:
            ratings = Rating.objects.get(video_id=video_id, user=request.user)
            ratings.delete()
        except:
            ratings = None
        rating = request.POST.get('rating')
        rating_obj = Rating(user=request.user, video_id=video_id, rating=rating)
        rating_obj.save()
        return HttpResponseRedirect(url)

    return HttpResponseRedirect(url)

def play_video(request, id): # Show clicked Video with list into UI
    url = request.META.get('HTTP_REFERER')
    video = Video.objects.get(pk=id)
    list = Video.objects.all().order_by('-created_on')
    comments = Comment_Model.objects.filter(is_aproved=True, comment_video=video)
    ratings = Rating.objects.filter(video=video)

    if request.method =='POST':
        url = request.META.get('HTTP_REFERER')
        user_id = User.objects.get(id=request.user.id)
        comment_form = CommentForm(request.POST)

        # comment section
        if comment_form.is_valid():
            comment_obj = comment_form.save(commit=False)
            comment_obj.comment_video = video
            comment_obj.comment_user=user_id
            comment_obj.save()
            return HttpResponseRedirect(url)

    total_rating =0
    avg_rating = 0
    no_rating = len(ratings)
    if ratings is not None:
        for rating in ratings:
            total_rating += rating.rating
            avg_rating = total_rating / no_rating;
            avg_rating= round(avg_rating, 1)

    rating_form = RatingForm()
    comment_form = CommentForm()
    context={'video': video,
             'list': list,
             'comments': comments,
             'comment_form': comment_form,
             'rating_form':rating_form,
             'no_rating':no_rating,
             'avg_rating': avg_rating, }
    return render(request, 'app/play.html', context)

@login_required(login_url='login')
def comment_reply(request, id):
    url = request.META.get('HTTP_REFERER')
    parent_comment = Comment_Model.objects.get(pk=id)
    child_comment = ReplyModel.objects.filter(comment=id)
    comment_form = ReplyCommentForm()
    if request.method == 'POST':
        comment_form = ReplyCommentForm(request.POST)
        if comment_form.is_valid():
            reply_obj = comment_form.save(commit=False)
            reply_obj.comment = parent_comment
            reply_obj.comment_user = request.user
            reply_obj.save()
            return HttpResponseRedirect(url)

    context= {
        'comment': parent_comment,
        'replys': child_comment,
        'form': comment_form

    }
    return render(request, 'app/reply.html', context)

@login_required(login_url='login')
def delete_view(request, id):
    url = request.META.get('HTTP_REFERER')
    video = Video.objects.get(pk=id)
    video.delete()
    return HttpResponseRedirect(url)

@login_required(login_url='login')
def delete_comment(request, id):
    url = request.META.get('HTTP_REFERER')
    comment = Comment_Model.objects.get(pk=id)
    comment.delete()
    return HttpResponseRedirect(url)

@login_required(login_url='login')
def delete_reply(request, comment, reply):
    url = request.META.get('HTTP_REFERER')
    reply_comment = ReplyModel.objects.get(pk=reply)
    reply_comment.delete()
    return HttpResponseRedirect(url)


# solved python search path for import module in other sub directories
import sys
import os
current_working_directory = os.getcwd()
sys.path.append(current_working_directory)

import script_modules.subscript.line.CreateLine as line
from script_modules.subscript.information.information import Print_Information
from script_modules.subscript.check_file_exist.CheckFile import CheckFile
from script_modules.subscript.read_file.read_file import ReadExcel
from script_modules.subscript.cleanup_file.cleanup import DataCleaner
############################################################################

class Template:

    def __init__(self, dateObj) :
        self.dateObj = dateObj

    def template_reading(self):
        path = ".\input\EDL_vs_BIB_Reconciliation.xlsx"
        readExcelObj = ReadExcel(path)
        db_sources = readExcelObj.readExcelSheet("DB Sources", None, [0,1])
        print("\n  DB Sources from template was read .")
        return db_sources

    def template_cleaning(self, df):
        dataCleanObj = DataCleaner(self.dateObj, df, 'db')
        dbSourceClean = dataCleanObj.clean_exelsheet()
        print("  Old data was removed from the db source.\n")
        return dbSourceClean

    def template_header_update(self, df):
        updateObj = DataCleaner(self.dateObj, df, 'db')
        updatedf = updateObj.update_header()
        print("  Update header.\n")
        return updatedf

    def executive(self):
        line.title_between_line("Read DB Template")
        db_source = self.template_reading()
        db_source = self.template_cleaning(db_source)
        db_source = self.template_header_update(db_source)
        return db_source


## RISHI RAWAT, HW6 AY250

from enthought.traits.api import *
from enthought.traits.ui.api import *
from enthought.traits.ui.menu import NoButtons
from mpl_figure_editor import MPLFigureEditor  #this editor is from code.enthought.com/.../traits/.../tutorials/traits_ui_scientific_app.html; I have saved the file locally to treat it as a module
from matplotlib.figure import Figure
from scipy import *
import wx
from PIL import Image
from cStringIO import StringIO
from urllib2 import urlopen
from yahoo.search.image import ImageSearch
import ImageFilter

class search(HasTraits):
	'''A search object has a gui which allows users to edit a picture returned from a search query;
	yahoo search image API is used to fetch an image;
	A matplotlib editor is used with traits to display the picture. The editor was borrowed from the tutorial at: http://code.enthought.com/projects/traits/docs/html/tutorials/traits_ui_scientific_app.html'''

	#TEXT FIELDS DEFINED:
	text_entry_field= String()
	text_entry_submit = Button()
	imageURL = String()

	#EDITING METHODS(BUTTONS):
	rotate90 = Button()
	blur = Button()
	sharpen=Button()
	emboss=Button()

	#This is the matplotlib figure
	figure = Instance(Figure, ())

	#WHEN THE USER PRESSES THE text_entry_submit BUTTON:
	def _text_entry_submit_fired(self):
		'''action for button; when fired, button executes 3 methods:
			1.) get_url_of_image(input = text_entry_field, output = url for yahoo search's first image result)
			2.) get_image_from_url(input=url of image, action = saves current_image.png in directory)
			3.) image_show(input=self, the file "current_image.png" in the directory; output=sets the image on the MPL canvas and uses wx to redraw/update plot)'''

		url = get_url_of_image(str(self.text_entry_field))
		self.imageURL = url
		get_image_from_url(url)
		image_show(self)

	#EDITING METHODS:
	def _rotate90_fired(self):
		image = Image.open("current_image.png")
		image.rotate(90).save('current_image.png')
		image_show(self)

	def _blur_fired(self):
		image = Image.open("current_image.png")
		image.filter(ImageFilter.BLUR).save('current_image.png')
		image_show(self)

	def _sharpen_fired(self):
		image = Image.open("current_image.png")
		image.filter(ImageFilter.SHARPEN).save('current_image.png')
		image_show(self)

	def _emboss_fired(self):
		image = Image.open("current_image.png")
		image.filter(ImageFilter.EMBOSS).save('current_image.png')
		image_show(self)

	#DEFINING THE VIEW, GROUPING TO IMPROVE ASTHETICS
	view = View(
				Group(
					Group(	Item('text_entry_field',show_label=False),
							Item('text_entry_submit',show_label = False),
							label = 'input',
							show_border = True),

					Group(	Item('imageURL',show_label=False,style='readonly'),
							label='imageURL',
							show_border = True),

					Group(	Item('figure',  editor=MPLFigureEditor(),show_label=False),
							label = 'Image Display',
							show_border = True),

					Group(	Item('rotate90',show_label=False),
							Item('blur',show_label=False),
							Item('sharpen',show_label=False),
							Item('emboss',show_label=False),
							label = 'Editing Options',
							show_border = True,

							orientation= 'horizontal',
							layout='flow',
							show_labels=False),
						),
				width = 500,
				height = 500,
				resizable=True  )

#FUNCTION THAT DISPLAYS A LOCALLY SAVED IMAGE ON THE MPL PLOT
def image_show(self):
	'''Opens 'current_image.png' and displays on plot;
	image_show(input=self, the file "current_image.png" in the directory; output=sets the image on the MPL canvas and uses wx to redraw/update plot)'''
	image = Image.open("current_image.png")
	axes = self.figure.add_subplot(111)
	axes.imshow(image)
	wx.CallAfter(self.figure.canvas.draw)

#GETS A URL USING THE YAHOO API
def get_url_of_image(query_string):
	'''gets an image from a yahoo image search of "query string", returns a url'''

	srch = ImageSearch(app_id="YahooDemo", query='%s'%query_string)
	srch.results = 1
	for each in srch.parse_results():
		url = str(each.Url)
	return url

#SAVES AN IMAGE TO DISK FROM A URL
def get_image_from_url(url):
	'''get_image_from_url(url) takes a url, reads it into a PIL Image object, saves the image as current_image.png'''
	image = urlopen(url)
	im2 = StringIO(image.read())
	im = Image.open(im2).transpose(Image.FLIP_TOP_BOTTOM)
	im.save('current_image.png')

#STARTS THE APP
search().configure_traits()


from tkinter.filedialog import asksaveasfilename as Askfile
from tkinter import StringVar, Tk, Canvas, Frame, Entry
from scrolledframe import ScrolledFrame as SFrame
from tkinter import LabelFrame as LFrame
from tkinter.ttk import Style, Button
from PIL.ImageTk import PhotoImage
from typing import Optional as O
from PIL.Image import Image
from pathlib import Path
from re import split
import json

try:
    from .datachart import DataChart
except ImportError:
    from subprocess import run
    pth = Path(__file__).parent
    run(['py', '-m', pth.name], cwd=pth.parent)
    raise SystemExit

class GUI(Tk):
    """This app allows for easy editing of circular datatrees"""
    dataset: dict[str, dict[str, list[str]]] = dict()
    datapth = Path(__file__).with_name('dataset.json')
    imgcanvas: Canvas
    image: Image
    imagetk: PhotoImage
    cnvimg: int
    saveBtn: Button
    dataScrl: SFrame
    dataFrm: Frame
    datadict: dict[Entry, dict[Entry, list[Entry]]]
    imgargs: tuple[StringVar, StringVar, StringVar, StringVar]

    def __init__(self):
        Tk.__init__(self)
        self.protocol("WM_DELETE_WINDOW", self.on_exit)
        wd = (self.winfo_screenwidth() // 2)
        ht = (self.winfo_screenheight() // 2)
        self.geometry(f'{wd * 1.5:.0f}'
                      f'x{ht * 1.5:.0f}'
                      f'+{wd - wd * 0.75:.0f}'
                      f'+{ht - ht * 0.75:.0f}')

        self.columnconfigure(1, weight=1)
        self.rowconfigure(1, weight=1)
        self.option_add('*font', 'Ebrima 12')
        self.option_add('*Entry.width', 15)
        s = Style()
        s.configure('TButton', font='Ebrima 12')
        s.configure('sm.TButton', width=6, font='Ebrima 8')
        self.datadict = dict()
        self.build()

    def on_exit(self):
        self.quit()
        self.destroy()

    def build(self):
        # data buttons
        dataBtns = LFrame(master=self,
                          text="Dataset")
        dataBtns.grid(column=0,
                      row=0)
        self.buildDataBtns(dataBtns)
        # data
        self.dataScrl = SFrame(master=self)
        self.dataScrl.grid(column=0,
                           row=1,
                           sticky='nsew')
        self.buildData()
        # image buttons
        imgBtns = LFrame(master=self,
                         text="Image")
        imgBtns.grid(column=0,
                     row=2,
                     pady=3)
        self.buildImgBtns(imgBtns)
        # canvas
        cnvfrm = SFrame(master=self,
                        padding=3)
        cnvfrm.grid(column=1,
                    row=0,
                    rowspan=3,
                    sticky='nsew')
        self.buildCanvas(cnvfrm)

#  ___ _   _ _____ _____ ___  _  _ ___
# | _ ) | | |_   _|_   _/ _ \| \| / __|
# | _ \ |_| | | |   | || (_) | .` \__ \
# |___/\___/  |_|   |_| \___/|_|\_|___/

  #    ___  ___ _________
  #   / _ \/ _ /_  __/ _ |
  #  / // / __ |/ / / __ |
  # /____/_/ |_/_/ /_/ |_|

    def buildDataBtns(self, parent):
        loadBtn = Button(master=parent,
                         text="Load",
                         command=self.loadData)
        loadBtn.grid(column=0,
                     row=0,
                     padx=3)
        clearBtn = Button(master=parent,
                          text="Clear",
                          command=self.clearData)
        clearBtn.grid(column=1,
                      row=0,
                      padx=3)
        saveBtn = Button(master=parent,
                         text="Save",
                         command=self.saveData)
        saveBtn.grid(column=2,
                     row=0,
                     padx=3)

    def loadData(self):
        with self.datapth.open('r') as f:
            self.dataset = json.load(f)
        self.datadict.clear()
        for w in self.dataFrm.winfo_children():
            w.destroy()
        for inr, sub in self.dataset.items():
            mfrm, k = self.addInner(inr)
            for mid, items in sub.items():
                ofrm, v = self.addMid(mfrm, k, mid)
                for out in items:
                    self.addOuter(ofrm, k, v, out)

    def clearData(self):
        self.dataset.clear()
        self.datadict.clear()
        for w in self.dataScrl.winfo_children():
            w.destroy()
        self.buildData()

    def saveData(self):
        self.getData()
        with self.datapth.open('w') as f:
            json.dump(self.dataset, f, indent=4)

  #    ______  ______  _________
  #   /  _/  |/  / _ |/ ___/ __/
  #  _/ // /|_/ / __ / (_ / _/
  # /___/_/  /_/_/ |_\___/___/

    def buildImgBtns(self, parent):
        def lblent(txt, var, col, row) -> None:
            lfrm = LFrame(master=parent,
                          text=txt,
                          font='Ebrima 8')
            lfrm.grid(column=col,
                      row=row,
                      padx=3)
            ent = Entry(master=lfrm,
                        textvariable=var)
            ent.pack()

        cmapnm = StringVar()
        offset = StringVar()
        ffamily = StringVar()
        fsize = StringVar()
        self.imgargs = (cmapnm, offset, ffamily, fsize)
        cmapnm.set('hsv')
        offset.set('20')
        ffamily.set('Ebrima')
        fsize.set('8, 7, 6.5')

        lblent("Colormap Name", cmapnm, 0, 0)
        lblent("Color Offset", offset, 1, 0)
        lblent("Font Family", ffamily, 0, 1)
        lblent("Font Size (inner, mid, outer)", fsize, 1, 1)
        drawBtn = Button(master=parent,
                         text="Draw",
                         command=self.drawImg)
        drawBtn.grid(column=0,
                     row=2,
                     padx=3)
        self.saveBtn = Button(master=parent,
                              text="Save",
                              command=self.saveImg,
                              state='disabled')
        self.saveBtn.grid(column=1,
                          row=2,
                          padx=3)

    def drawImg(self):
        self.getData()
        cm, off, fam, sz = self.imgargs
        self.image = DataChart(dataset=self.dataset,
                               colormap_name=cm.get(),
                               offset=float(off.get()),
                               fontfamily=fam.get(),
                               fontsize=[float(n) for n in split(r', ?| ', sz.get())])
        self.imagetk = PhotoImage(self.image)
        self.imgcanvas.itemconfigure(self.cnvimg, image=self.imagetk)
        self.saveBtn.configure(state='normal')

    def saveImg(self):
        saveas = Askfile(parent=self,
                         title="Save image as...",
                         filetypes=[('PNG Image (*.png)', '*.png'),
                                    ('JPG Image (*.jpg)', '*.jpg')],
                         defaultextension='.png')
        if saveas:
            file = Path(saveas)
            if file.suffix == '.jpg':
                self.image.convert('RGB').save(file)
            else:
                self.image.save(file)

#  ___   _ _____ _
# |   \ /_\_   _/_\
# | |) / _ \| |/ _ \
# |___/_/ \_\_/_/ \_\

    def buildData(self):
        self.dataFrm = Frame(self.dataScrl)
        self.dataFrm.grid(column=0,
                          row=0)
        addBtn = Button(master=self.dataScrl,
                        text="Add Category",
                        command=self.addInner)
        addBtn.grid(column=0,
                    row=1,
                    sticky='w',
                    padx=3,
                    pady=3)
        self.addInner()

    def addInner(self, name: str = None) -> O[tuple[Frame, Entry]]:
        def remInner():
            frm.destroy()
            self.datadict.pop(Entry)

        frm = Frame(master=self.dataFrm)
        frm.grid()
        remBtn = Button(master=frm,
                        text='Delete',
                        style='sm.TButton',
                        command=remInner)
        remBtn.grid(column=0,
                    row=0,
                    sticky='ne',
                    pady=3)
        ent = Entry()
        lfrm = LFrame(master=frm,
                      labelwidget=ent,
                      bd=3,
                      padx=5,
                      pady=5)
        lfrm.grid(column=1,
                  row=0,
                  sticky='w')
        subfrm = Frame(master=lfrm)
        subfrm.grid(column=0,
                    row=0)
        addBtn = Button(master=lfrm,
                        text="Add Subcategory",
                        command=(lambda a=(subfrm, ent): self.addMid(*a)))
        addBtn.grid(column=0,
                    row=1,
                    sticky='w',
                    padx=3,
                    pady=3)
        self.datadict[ent] = dict()
        self.dataScrl.redraw()
        if name:
            ent.insert(0, name)
            return (subfrm, ent)
        else:
            self.addMid(subfrm, ent)

    def addMid(self, parent: Frame, key: Entry, name: str = None) -> O[tuple[Frame, Entry]]:
        def remMid():
            frm.destroy()
            self.datadict[key].pop(ent)

        frm = Frame(master=parent)
        frm.grid()
        remBtn = Button(master=frm,
                        text='Delete',
                        style='sm.TButton',
                        command=remMid)
        remBtn.grid(column=0,
                    row=0,
                    sticky='ne',
                    pady=3)
        ent = Entry()
        lfrm = LFrame(master=frm,
                      labelwidget=ent,
                      bd=3,
                      padx=5,
                      pady=5)
        lfrm.grid(column=1,
                  row=0,
                  sticky='w')
        subfrm = Frame(master=lfrm)
        subfrm.grid(column=0,
                    row=0)
        addBtn = Button(master=lfrm,
                        text="Add Item",
                        command=(lambda a=(subfrm, key, ent): self.addOuter(*a)))
        addBtn.grid(column=0,
                    row=1,
                    sticky='w',
                    padx=3,
                    pady=3)
        self.datadict[key][ent] = list()
        self.dataScrl.redraw()
        if name:
            ent.insert(0, name)
            return (subfrm, ent)
        else:
            self.addOuter(subfrm, key, ent)

    def addOuter(self, parent: Frame, key: Entry, val: Entry, name: str = '') -> None:
        def remOuter():
            frm.destroy()
            i = self.datadict[key][val].index(ent)
            self.datadict[key][val].pop(i)

        frm = Frame(master=parent,
                    pady=1)
        frm.grid()
        remBtn = Button(master=frm,
                        text='Delete',
                        style='sm.TButton',
                        command=remOuter)
        remBtn.grid(column=0,
                    row=0,
                    sticky='ne',
                    pady=3)
        ent = Entry(master=frm)
        ent.insert(0, name)
        ent.grid(column=1,
                 row=0,
                 sticky='w',
                 padx=3,
                 pady=3)
        self.datadict[key][val].append(ent)
        self.dataScrl.redraw()

    def getData(self):
        self.dataset = {
            inr.get(): {
                mid.get(): [
                    out.get() for out in items]
                for mid, items in sub.items()}
            for inr, sub in self.datadict.items()}

        #   ___   _   _  ___   ___   ___
        #  / __| /_\ | \| \ \ / /_\ / __|
        # | (__ / _ \| .` |\ V / _ \\__ \
        #  \___/_/ \_\_|\_| \_/_/ \_\___/

    def buildCanvas(self, parent):
        self.imgcanvas = Canvas(master=parent,
                                width=1440,
                                height=1440)
        self.imgcanvas.pack()
        self.cnvimg = self.imgcanvas.create_image(0, 0, anchor='nw')
        self.image = None
        self.imagetk = None


# -*- coding: utf-8 -*-
"""
Created on Wed Jul 28 06:17:25 2021

@author: tjame
"""

import random

user_wins = 0
computer_wins = 0
ties = 0
number_of_games = 0

options = ["rock", "paper", "scissors"]

while True:
    user_input = input("Type Rock/Paper/Scissors or Q to quit: ").lower()
    if user_input == "q":
        break

    if user_input not in options:
        continue

    random_number = random.randint(0, 2)
    # rock: 0, paper: 1, scissors: 2
    computer_pick = options[random_number]
    print(f"Computer picked {computer_pick}.")

    if user_input == "rock" and computer_pick == "scissors":
        print("You won!")
        user_wins += 1
        number_of_games += 1

    elif user_input == "paper" and computer_pick == "rock":
        print("You won!")
        user_wins += 1
        number_of_games += 1

    elif user_input == "scissors" and computer_pick == "paper":
        print("You won!")
        user_wins += 1
        number_of_games += 1

    elif user_input == "rock" and computer_pick == "rock":
        print("It's a tie!")
        ties += 1
        number_of_games += 1

    elif user_input == "paper" and computer_pick == "paper":
        print("It's a tie!")
        ties += 1
        number_of_games += 1

    elif user_input == "scissors" and computer_pick == "scissors":
        print("It's a tie!")
        ties += 1
        number_of_games += 1

    else:
        print("You lost!")
        computer_wins += 1
        number_of_games += 1

print(f"Of the {number_of_games} games played, you won {user_wins} times, the computer won {computer_wins} times, and there were {ties} ties! Goodbye.")


import sys

def command_program(operation, number):
    global res
    if operation == "add":
        res.add(number)

    elif operation == "remove":
        res.discard(number)

    elif operation == "check":
        if number in res:
            print(1)
        else:
            print(0)

    elif operation == "toggle":
        if number in res:
            res.discard(number)
        else:
            res.add(number)

def solution():
    global res
    m = int(input())
    res = set()

    for i in range(m):
        command = sys.stdin.readline().split()
        if len(command) == 1:
            if command[0] == "all":
                res = set([i for i in range(1, 21)])
            else:
                res = set()
            continue

        operation = command[0]
        number = int(command[1])
        command_program(operation, number)

if __name__ == "__main__":
    solution()


"""
    This is Example of Python Mixin,
"""
import json

class Jsonizable(object):

    @classmethod
    def from_json(cls, data):
        kwargs = json.loads(data)
        return cls(**kwargs)

    def to_json(self):
        return json.dumps(self.__dict__)

class DeserializeObj(Jsonizable):

    def __init__(self, **kwargs):
        self.created_at = kwargs.pop("created_at", None)
        self.tags = kwargs.pop("tags", None)

if __name__ == "__main__":
    meta = DeserializeObj()
    meta.created_at = 1234567
    meta.tags = ["Node",]

    meta_str = meta.to_json()
    print(meta_str)

    meta2 = DeserializeObj.from_json(meta_str)
    print(meta2.created_at)
    print(meta2.tags)
    print(meta2.to_json())


# https://www.acmicpc.net/problem/2529
N = int(input())

signs = input().split()
check = [False] * 10
answers = []
def go(index, num):
    if index == N + 1:
        answers.append(num)
        return

    for i in range(10):
        if check[i]:
            continue
        if index != 0 and (not good(num[index - 1], str(i), signs[index - 1])):
            continue
        check[i] = True
        go(index + 1, num + str(i))
        check[i] = False

def ok(num: str):
    for i in range(N):
        if signs[i] == '<':
            if num[i] > num[i + 1]:
                return False
        else:
            if num[i] < num[i + 1]:
                return False

    return True

def good(x, y, op):
    return (op == '<' and x < y) or (op == '>' and x > y)

go(0, '')

print(max(answers))
print(min(answers))


"""Block/quality check processes."""

from typing import TYPE_CHECKING

from ..specimens import Specimen
from .__core import Process

if TYPE_CHECKING:
    from ..model import Model

def register(env: "Model"):
    """Register processes to the simulation environment."""
    env.processes['qc'] = Process('qc', env=env, in_type=Specimen, fn=qc)

    # Since slides are already scanned, no need to hand to histopathologist after QC,
    # therefore, batching and delivery are not part of this stage.

def qc(self: Specimen):
    """Label all slides of a specimen."""
    env: Model = self.env
    env.wips.in_qc.value += 1
    self.data['qc_start'] = env.now()

    self.request((env.resources.qc_staff, 1, self. prio))
    self.hold(env.task_durations.block_and_quality_check)
    self.release()

    env.wips.in_qc.value -= 1
    self.data['qc_end'] = env.now()

    self.enter(env.processes['assign_histopath'].in_queue)


"""
Definition of views.
"""

from django.shortcuts import *
from django.http import HttpRequest
from django.template import RequestContext
from django.views.generic import CreateView
from django.views.generic import DeleteView
from django.views.generic import ListView
from datetime import datetime
from app.forms import *
from app.models import *
from django.core.urlresolvers import reverse

"""This view renders the home page."""

def home(request):
    assert isinstance(request, HttpRequest)

    context = RequestContext(request)
    return render(
        request,
        'app/index.html',
        context
    )

"""This view renders the customers page."""
def customers(request):
    assert isinstance(request, HttpRequest)
    customer_list = customer.objects.all()

    if request.method == 'POST':
        cusForm = CustomerForm(request.POST)
        if cusForm.is_valid():
            cusForm.save()
            return HttpResponseRedirect('/customers')
    else:
        cusForm = CustomerForm()

    context = RequestContext(request, {
        'customers':customer_list,
        'cus_form':cusForm
        })
    return render(
        request,
        'app/customers.html',
        context
    )

"""This view renders the jobs for a specific customer page."""
def customer_specific(request, custid_url):
    assert isinstance(request, HttpRequest)

    job_list = job.objects.filter(custid=customer.objects.get(custid=custid_url))
    custurl = '/customer/' + str(custid_url) + '/'
    cust = customer.objects.get(custid=custid_url)

    if request.method == 'POST':
        if 'edit_customer' in request.POST:
        #This is where I put the edit form response
            cusFormEdit = CustomerEditForm(request.POST)
            if cusFormEdit.is_valid():
                #here is where I grab the cleaned_data from the form and then use it to alter the current model instance.
                cust.name = cusFormEdit.cleaned_data['name']
                cust.contactName = cusFormEdit.cleaned_data['contactName']
                cust.email = cusFormEdit.cleaned_data['email']
                cust.address = cusFormEdit.cleaned_data['address']
                cust.city = cusFormEdit.cleaned_data['city']
                cust.state = cusFormEdit.cleaned_data['state']
                cust.zip = cusFormEdit.cleaned_data['zip']
                cust.phone = cusFormEdit.cleaned_data['phone']
                cust.save()
            return HttpResponseRedirect(custurl)
        elif 'new_job' in request.POST:
        #This is where I put the new job form response
            jobForm = JobForm(request.POST)
            if jobForm.is_valid():
                newjob = job(custid=cust, description=jobForm.cleaned_data['description'], address=jobForm.cleaned_data['address'], city=jobForm.cleaned_data['city'], state=jobForm.cleaned_data['state'], zip=jobForm.cleaned_data['zip'])
                newjob.save()
            return HttpResponseRedirect(custurl)
        else:
            print(security)
    else:
        jobForm = JobForm()
        cusFormEdit = CustomerEditForm(instance=customer.objects.get(custid=custid_url))

    context = RequestContext(request, {
                             'jobs':job_list,
                             'job_form':jobForm,
                             'cus_form_edit':cusFormEdit,
                             'cust':cust,
                             })
    return render(
              request,
              'app/jobs.html',
              context
              )

"""This view renders the invoices for a specific job."""
def job_specific(request, custid_url, jobid_url):
    assert isinstance(request, HttpRequest)

    custurl = '/job/' + str(custid_url) + '/' + str(jobid_url) + '/'
    joblist = job.objects.filter(custid=customer.objects.get(custid=custid_url))
    job_spec = job.objects.get(jobid=jobid_url)
    cust = customer.objects.get(custid=custid_url)
    inv_list = invoices.objects.filter(jobid=jobid_url)

    if request.method == 'POST':
        if 'edit_job' in request.POST:
#This is where I put the edit form response
            jobFormEdit = JobEditForm(request.POST)
            if jobFormEdit.is_valid():
        #here is where I grab the cleaned_data from the form and then use it to alter the current model instance.
                job_spec.description = jobFormEdit.cleaned_data['description']
                job_spec.address = jobFormEdit.cleaned_data['address']
                job_spec.state = jobFormEdit.cleaned_data['state']
                job_spec.zip = jobFormEdit.cleaned_data['zip']
                job_spec.save()
            return HttpResponseRedirect(custurl)
        elif 'new_invoice' in request.POST:
            #This is where I put the new job form response
            invForm = InvForm(request.POST)
            if invForm.is_valid():
                datetime.now().date()
                newinv = invoices(jobid=job_spec, description=invForm.cleaned_data['description'], active=invForm.cleaned_data['active'], amount=invForm.cleaned_data['amount'])
                newinv.save()
            return HttpResponseRedirect(custurl)
        else:
            print('security')
    else:
        jobFormEdit = JobEditForm(instance=job.objects.get(jobid=jobid_url))
        invForm = InvForm()

    context = RequestContext(request, {
                             'invs':inv_list,
                             'inv_form':invForm,
                             'job_spec':job_spec,
                             'job_form_edit':jobFormEdit,
                             'cust':cust
                             })
    return render(
              request,
              'app/invoices.html',
              context
              )

def inv_specific(request, jobid_url, invid_url):
    assert isinstance(request, HttpRequest)
    inv_spec = invoices.objects.get(invoiceid=invid_url)
    cust_url = '/invoice/' + str(jobid_url) + '/' + str(invid_url) + '/'
    flag = 1

    if request.method == 'POST':
        if 'edit_invoice' in request.POST:
            invformedit = InvEditForm(request.POST)
            if invformedit.is_valid():
                inv_spec.description = invformedit.cleaned_data['description']
                inv_spec.amount = invformedit.cleaned_data['amount']
                inv_spec.createdate = invformedit.cleaned_data['createdate']
                if inv_spec.active == True:
                    if invformedit.cleaned_data['active'] == False:
                        inv_spec.closedate = datetime.now().date()
                inv_spec.active = invformedit.cleaned_data['active']
                inv_spec.save()
            return HttpResponseRedirect(cust_url)
        elif 'edit_invoice_simple' in request.POST:
            invformedit = InvEditFormSimple(request.POST)
            if invformedit.is_valid():
                inv_spec.description = invformedit.cleaned_data['description']
                inv_spec.amount = invformedit.cleaned_data['amount']
                inv_spec.createdate = invformedit.cleaned_data['createdate']
                if inv_spec.active == True:
                    if invformedit.cleaned_data['active'] == False:
                        inv_spec.closedate = datetime.now().date()
                inv_spec.active = invformedit.cleaned_data['active']
                inv_spec.save()
            return HttpResponseRedirect(cust_url)
        else:
            print('security')

    else:
        invformedit = InvEditForm(instance=invoices.objects.get(invoiceid=invid_url))
        invformeditsimple = InvEditFormSimple(instance=invoices.objects.get(invoiceid=invid_url))
    if inv_spec.active == False:
        context = RequestContext(request, {
                             'inv_spec':inv_spec,
                             'invformedit':invformedit,
                             'invformeditsimple':invformeditsimple,
                             'flag':flag
                             })
    else:
        context = RequestContext(request, {
                                 'inv_spec':inv_spec,
                                 'invformedit':invformedit,
                                 'invformeditsimple':invformeditsimple
                                 })
    return render(
                  request,
                  'app/invoice-detail.html',
                  context
                  )


import unittest
from datetime import datetime, timedelta

from automover.test.helpers import *

from automover.remover import handle_remove

class TestRemover(unittest.TestCase):
    def setUp(self):
        self.client = client = DummyClient()
        self.torrents = [
            DummyTorrent(client, '1', datetime.now(), 0, '/matchpath/', False, True, ['http://matchtracker.com']),
            DummyTorrent(client, '2', datetime.now(), 2, '/matchpath/', True, True, ['http://matchtracker.com']),
            DummyTorrent(client, '3', datetime.now()-timedelta(hours=20), 0.5, '/matchpath/', True, True, ['http://matchtracker.com']),
            DummyTorrent(client, '4', datetime.now()-timedelta(hours=50), 50, '/matchpath/', True, True, ['http://matchtracker.com']),
            DummyTorrent(client, '5', datetime.now()-timedelta(hours=50), 50, '/matchpath/', True, True, ['http://matchtracker.com']),
            DummyTorrent(client, '6', datetime.now(), 50, '/matchpath/', False, True, ['http://matchtracker.com']),
            DummyTorrent(client, '7', datetime.now(), 50, '/matchpath/', True, True, ['http://matchNOTtracker.com']),
            DummyTorrent(client, '8', datetime.now(), 50, '/matchNOTpath/', True, True, ['http://matchtracker.com']),
        ]
        self.client.torrents = self.torrents

    def test_timed_remove(self):
        handle_remove(self.client, {'fakesite1': ('time', 'matchtracker', '3')}, ['/matchpath'])
        self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '2', '6', '7', '8'], 'Did not remove correct torrents')

    def test_ratio_remove(self):
        handle_remove(self.client, {'fakesite1': ('ratio', 'matchtracker', 1.5)}, ['/matchpath'])
        self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '3', '6', '7', '8'], 'Did not remove correct torrents')

    def test_combined_remove(self):
        handle_remove(self.client, {'fakesite1': ('ratio', 'matchtracker', 1.5), 'fakesite2': ('time', 'matchtracker', '3')}, ['/matchpath'])
        self.assertEqual([torrent.torrent_id for torrent in self.torrents], ['1', '6', '7', '8'], 'Did not remove correct torrents')


from msrest.serialization import Model

class ModuleAssetParameter(Model):
    """Parameter definition for a module asset.

    :param name: Parameter name.
    :type name: str
    :param parameter_type: Parameter type.
    :type parameter_type: str
    :param mode_values_info: Definitions for nested interface parameters if
     this is a complex module parameter.
    :type mode_values_info: dict
    """

    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'parameter_type': {'key': 'parameterType', 'type': 'str'},
        'mode_values_info': {'key': 'modeValuesInfo', 'type': '{ModeValueInfo}'},
    }

    def __init__(self, name=None, parameter_type=None, mode_values_info=None):
        self.name = name
        self.parameter_type = parameter_type
        self.mode_values_info = mode_values_info


import sys
input = sys.stdin.readline

floor=int

for _ in range(10):
    x=int(input())
    a,b,c,d=map(float,input().split())
    n=int(input())
    total=floor(n*a+1e-15)*12 + floor(n*b+1e-15)*10 + floor(n*c+1e-15)*7 + floor(n*d+1e-15)*5
    #print(total,x)
    if total>=x*2: print("NO")
    else: print("YES")


import numpy as np
import tensorflow as tf

# Modelo de la red neuronal:

# se definen las capas que tendra el modelo
def LoadModel():
        model = tf.keras.Sequential([
            tf.keras.layers.Conv2D(96, (11,11),activation='relu', input_shape=(128,128,3)),
            tf.keras.layers.MaxPooling2D(2,2),
            tf.keras.layers.Conv2D(256, (7,7),activation='relu'),
            tf.keras.layers.MaxPooling2D(2,2),
            tf.keras.layers.Conv2D(384, (5,5),activation='relu'),
            tf.keras.layers.MaxPooling2D(2,2),
            tf.keras.layers.Conv2D(384, (5,5),activation='relu'),
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(1024),
            tf.keras.layers.Dense(1024),
            tf.keras.layers.Dense(9, activation="softmax")
        ])

        return model

# se define la funcion de normalizacion
def Normalize(image):
    stdR = np.std(image[:,:,0]) #Calculamos la varianza para cada espacio de color
    stdG = np.std(image[:,:,1])
    stdB = np.std(image[:,:,2])

    R = np.mean(image[:,:,0]) #La mediana de cada espacio de color
    G = np.mean(image[:,:,1])
    B = np.mean(image[:,:,2])

    image[:,:,0] = image[:,:,0] - R
    image[:,:,1] = image[:,:,1] - G
    image[:,:,2] = image[:,:,2] - B

    image[:,:,0] = image[:,:,0]/stdR
    image[:,:,1] = image[:,:,1]/stdG
    image[:,:,2] = image[:,:,2]/stdB

    minimoR = np.min(image[:,:,0])
    minimoG = np.min(image[:,:,1])
    minimoB = np.min(image[:,:,2])

    image[:,:,0] = image[:,:,0]-minimoR # Restamos el valor minimo de cada espacio para que el valor mas bajo sea 0
    image[:,:,1] = image[:,:,1]-minimoG
    image[:,:,2] = image[:,:,2]-minimoB

    maximoR = np.max(image[:,:,0])
    maximoG = np.max(image[:,:,1])
    maximoB = np.max(image[:,:,2])

    factorR = 1/maximoR #Calculamos el factor escala por el que hay que multiplicar cada espacio para que su valor maximo sea 1
    factorG = 1/maximoG
    factorB = 1/maximoB

    image[:,:,0] = image[:,:,0] * factorR #Operamos de modo que cada color tiene sus valores comprendidos entre [0,1]
    image[:,:,1] = image[:,:,1] * factorG
    image[:,:,2] = image[:,:,2] * factorB

    return image


from time import sleep
import asyncio

class Sort:
    def __init__(self):
        self.array = []
        self.rect_array = []

    def swap(self, arr, rect_arr, k, m, window_self, sleep_time):
        c = arr[m]
        arr[m] = arr[k]
        arr[k] = c
        m_coord = window_self.canvas.coords(rect_arr[m])[0]
        k_coord = window_self.canvas.coords(rect_arr[k])[0]
        dif = m_coord - k_coord
        window_self.canvas.move(rect_arr[m], -dif, 0)
        window_self.canvas.move(rect_arr[k], dif, 0)
        rect_temp = rect_arr[m]
        rect_arr[m] = rect_arr[k]
        rect_arr[k] = rect_temp
        window_self.root.update()
        sleep(sleep_time)

    def BubbleSort(self, arr, rect_arr, window_self, sleep_time):
        lenght = len(arr)
        swaped = True
        for i in range(0, lenght):
            swaped = False
            for j in range(lenght-1, 0, -1):
                if (arr[j] > arr[j-1]):
                   self.swap(arr, rect_arr, j, j-1, window_self, sleep_time)
                   swaped = True
                if (window_self.stop):
                    break
            if not swaped:
                break

    def CocktailSort(self, arr, rect_arr, window_self, sleep_time):
        lenght = len(arr)
        swaped = True
        while(swaped):
            swaped = False
            for i in range(0, lenght-2):
                if(arr[i]>arr[i+1] and not window_self.stop):
                    self.swap(arr, rect_arr, i, i+1, window_self, sleep_time)
                    swaped = True
            if(not swaped):
                break
            swaped = False
            for i in range(lenght-2,-1,-1):
                if(arr[i]>arr[i+1] and not window_self.stop):
                    self.swap(arr, rect_arr, i, i+1, window_self, sleep_time)
                    swaped = True
                    if (window_self.stop):
                        break


from utils import SYMBOLS, IMG_TRANSFORM, IMG_DIR, pad_image
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.categorical import Categorical
from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
from PIL import Image, ImageOps
from tqdm import trange, tqdm
import math
import numpy as np
from collections import Counter
from . import resnet_scan, lenet_scan
from torchvision import transforms
import random

tok_convert = {'*': 'times', '/': 'div', 'a': 'alpha', 'b': 'beta', 'c': 'gamma', 'd': 'phi', 'e': 'theta'}
tok_convert = {v:k for k, v in tok_convert.items()}
def check_accuarcy(dataset):
    from utils import SYM2ID
    symbols = [x[0].split('/')[0] for x in dataset]
    symbols = [tok_convert.get(x, x) for x in symbols]
    symbols = [SYM2ID(x) for x in symbols]
    labels = [x[1] for x in dataset]
    acc = np.mean(np.array(symbols) == np.array(labels))
    print(acc, end=', ')

class Perception(object):
    def __init__(self):
        super(Perception, self).__init__()
        self.n_class = len(SYMBOLS)
        # self.model = SymbolNet(self.n_class)
        self.model = resnet_scan.make_model(self.n_class)
        # self.model = lenet_scan.make_model(self.n_class)
        self.optimizer = torch.optim.Adam(self.model.parameters(), lr=1e-4)
        self.device = torch.device('cpu')
        self.training = False
        self.min_examples = 200
        self.selflabel_dataset = None

    def train(self):
        # self.model.train()
        self.model.eval()
        self.training = True

    def eval(self):
        self.model.eval()
        self.training = False

    def to(self, device):
        self.model.to(device)
        self.device = device

    def save(self, save_optimizer=True):
        saved = {'model': self.model.state_dict()}
        if save_optimizer:
            saved['optimizer'] = self.optimizer.state_dict()
        return saved

    def load(self, loaded):
        self.model.load_state_dict(loaded['model'])
        if 'optimizer' in loaded:
            self.optimizer.load_state_dict(loaded['optimizer'])

    def extend(self, n):
        self.n_class += n
        self.model.extend(n)
        self.optimizer = torch.optim.Adam(self.model.parameters(), lr=1e-4)

    def selflabel(self, symbols):
        dataloader = torch.utils.data.DataLoader(ImageSet(symbols), batch_size=512,
                         shuffle=False, drop_last=False, num_workers=8)
        with torch.no_grad():
            self.eval()
            prob_all = []
            for img, _ in dataloader:
                img = img.to(self.device)
                prob = self.model(img)
                prob = nn.functional.softmax(prob, dim=-1)
                prob_all.append(prob)
            prob_all = torch.cat(prob_all)

        confidence = 0.95
        selflabel_dataset = {}
        probs, preds = torch.max(prob_all, dim=1)
        probs = probs.cpu().numpy()
        preds = preds.cpu().numpy()
        for cls_id in range(self.n_class):
            idx_list = np.where(preds == cls_id)[0]
            idx_list = sorted(idx_list, key=lambda x: probs[x], reverse=True)
            idx_list = [i for i in idx_list if probs[i] >= confidence]
            images = [symbols[i][0] for i in idx_list]
            # images = list(set(images))
            labels = [symbols[i][1] for i in idx_list]
            acc = np.mean(np.array(labels) == cls_id)
            selflabel_dataset[cls_id] = [(x, cls_id) for x in images]
            print("Add %d samples for class %d, acc %.2f."%(len(images), cls_id, acc))
        self.selflabel_dataset = selflabel_dataset

    def __call__(self, images):
        logits = self.model(images)
        # probs = torch.sigmoid(logits)
        probs = nn.functional.softmax(logits, dim=-1)
        if self.training:
            m = Categorical(probs=probs)
            preds = m.sample()
        else:
            preds = torch.argmax(probs, -1)

        return preds, probs

    def learn(self, dataset, n_iters=100):
        batch_size = 512
        labels = [l for i, l in dataset]
        counts = Counter(labels)

        check_accuarcy(dataset)
        classes_invalid = [i for i in range(self.n_class) if counts[i] < self.min_examples]
        if classes_invalid and self.selflabel_dataset is not None:
            for cls_id in classes_invalid:
                dataset.extend(random.choices(self.selflabel_dataset[cls_id], k=self.min_examples - counts[cls_id]))
            check_accuarcy(dataset)
            print(len(dataset), end=', ')

        labels = [l for i, l in dataset]
        counts = Counter(labels)
        sample_weights = np.array([1. / counts[l] for i, l in dataset])
        sampler = WeightedRandomSampler(torch.from_numpy(sample_weights), len(sample_weights))
        criterion = nn.CrossEntropyLoss()
        # criterion = nn.BCEWithLogitsLoss(pos_weight=class_weights, reduction='none')

        n_epochs = int(math.ceil(batch_size * n_iters / len(dataset)))
        print(n_epochs, "epochs, ", end='')
        dataset = ImageSet(dataset)
        train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
                         sampler=sampler, num_workers=8)
        self.model.train()
        for epoch in range(n_epochs):
            for img, label in train_dataloader:
                img = img.to(self.device)
                label = label.to(self.device)
                logit = self.model(img)
                # label = nn.functional.one_hot(label, num_classes=self.n_class).type_as(logit)
                loss = criterion(logit, label)
                self.optimizer.zero_grad()
                loss.backward()
                self.optimizer.step()

class SymbolNet(nn.Module):
    def __init__(self, n_class):
        super(SymbolNet, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 3, stride = 1, padding = 1)
        self.conv2 = nn.Conv2d(6, 16, 3, stride = 1, padding = 1)
        self.fc1 = nn.Linear(16 * 8 * 8, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, n_class)

    def forward(self, x):
        x = F.max_pool2d(F.relu(self.conv1(x)), 2)
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = torch.flatten(x, 1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

class ImageSet(Dataset):
    def __init__(self, dataset):
        super(ImageSet, self).__init__()
        self.dataset = dataset
        self.img_transform = IMG_TRANSFORM

    def __getitem__(self, index):
        sample = self.dataset[index]
        img_path, label = sample
        img = Image.open(IMG_DIR+img_path).convert('L')
        img = ImageOps.invert(img)
        img = pad_image(img, 60)
        img = transforms.functional.resize(img, 40)
        img = self.img_transform(img)

        return img, label

    def __len__(self):
        return len(self.dataset)


import cv2
import os
import glob
folder = 'folder-path-here'
extension = 'extension-here'
video_files = glob.glob(folder+'*.'+extension)
for file_name in video_files:
    vidcap = cv2.VideoCapture(file_name)
    success,image = vidcap.read()
    count = 0
    save_folder = file_name.split('.')[0]
    shortname1 = file_name.split('/')
    shortname2 = shortname1[-1].split('\\')
    shortname3 = shortname2[-1].split('.')
    if not os.path.exists(save_folder):
        os.mkdir(save_folder)
    while True: # .read() below sometimes returns false in middle of video.
        write_file = save_folder+'/'+shortname3[0]+"frame%d.png" % count
        cv2.imwrite(write_file, image)     # save frame as png file
        success,image = vidcap.read()
        print('Read a new frame: ', success)
        count += 1


import random
import time

def euclidean(num1, num2):
    while num2 != 0:
        num1, num2 = num2, num1 % num2

    return num1

def extended_euclidean(num1, num2):
    (x0, y0, x, y) = (1, 0, 0, 1)
    n = 1
    while num1 % num2:
        (x0, y0, x, y) = (x, y, x0 + x*(num1//num2), y0 + y*(num1//num2))
        num1, num2 = num2, num1 % num2
        n += 1

    return (num2, x * (-1)**n, y * (-1)**(n+1))

def fme(number, exponent, modulus):
    szorzat = 1
    b = number
    for i in "{0:b}".format(exponent)[::-1]:
        if int(i):
            szorzat *= b
        b = b**2 % modulus

    return szorzat % modulus

def miller_rabin(number):
    (a, s, p) = (2, 0, number-1)
    while not p % 2:
        s += 1
        p = p // 2

    elso = fme(a, p, number)
    if elso == 1 or elso == number-1:
        return True

    for _ in range(1, s):
        elso = (elso ** 2) % number
        if elso == number-1:
            return True

    return False

def generate_random_prime():
    random_szam2 = random.randrange(1000, 1500)
    i = 2**random_szam2 +1
    while True:
        if miller_rabin(i):
            return i
        else:
            i += 2

def generate_keys(prime1, prime2):
    n = prime1 * prime2
    fi_n = (prime1-1) * (prime2-1)
    e = 0
    for i in range(2, 5000):
        if euclidean(fi_n, i) == 1:
            e = i
            break

    return((n, e), (n, extended_euclidean(fi_n, e)[2] % fi_n))

def encrypt(message, public_key):
    return fme(message, public_key[1], public_key[0])

def fme_decrypt(encrypted_message, private_key):
    return fme(encrypted_message, private_key[1], private_key[0])

def chinese_remainder_decrypt(encrypted_message, private_key, prime1, prime2):
    c1, c2 = fme(encrypted_message, (private_key[1] % (prime2-1)), prime2), fme(encrypted_message, (private_key[1] % (prime1-1)), prime1)
    x1, x2 = extended_euclidean(prime1, prime2)[1:]

    return (c1*prime1*x1 + c2*prime2*x2) % private_key[0]

def main():
    start = time.time()
    gyors = time.time()
    prime1, prime2 = generate_random_prime(), generate_random_prime()
    print("Első prím:", prime1)
    print()
    print("Második prím:", prime2)
    print("Generálási idő:", time.time()-gyors)
    print()
    gyors = time.time()
    public_key, private_key = generate_keys(prime1, prime2)
    titkos = encrypt(124125426582348273569235872938, public_key)
    print(f"Publikus kulcspár: {public_key}")
    print()
    print(f"Privát kulcspár: {private_key}")
    print("Eltelt idő:", time.time()-gyors)
    print()
    gyors = time.time()
    print(f"Titkosított üzenet: {titkos}")
    print("Eltelt idő:", time.time()-gyors)
    print()
    gyors = time.time()
    print(f"Visszafejtett üzenet gyorshatványozással: {fme_decrypt(titkos, private_key)}")
    print("Eltelt idő:", time.time()-gyors)
    print()
    gyors = time.time()
    print(f"Visszafejtett üzenet kínai maradéktétellel: {chinese_remainder_decrypt(titkos, private_key, prime1, prime2)}")
    print("Eltelt idő:", time.time()-gyors)
    print()
    print("Összes eltelt idő:", time.time()-start)

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

if __name__ == "__main__":
    main()


import requests
import re
import lxml.html
import urllib.parse

CATEGORIES = [
    "art_and_design", "auto_and_vehicles","books_and_reference",
    "brain", "business", "comics","communication",
    "education","entertainment", "finance",
    "game", "health_and_fitness", "house_and_home",
    "libraries_and_demo", "lifestyle", "media_and_video",
    "medical", "music_and_audio", "news_and_magazines",
    "personalization", "photography", "productivity",
    "shopping", "social", "sports", "tools",
    "transportation", "travel_and_local", "weather"
]

TOPSELLING_FREE = 'topselling_free'
TOPSELLING_PAID = 'topselling_paid'

BASE_URL = "https://play.google.com"

def _get_float(s):
    for i in s.split():
        try:
            return float(i)
        except:
            continue

def _get_text(doc, _path):
    els = doc.xpath(_path)
    if len(els) > 0:
        return els[0].text_content().strip()
    else:
        return None

def _get_attrs(doc, _path, attr):
    return [el.get(attr) for el in doc.xpath(_path)]

def _get_apps(url):
    r = requests.get(url)
    if r.status_code != 200:
        return None

    doc = lxml.html.fromstring(r.content)
    pattern = r"id=(.+)"
    hrefs = _get_attrs(doc, '//a', 'href')

    apps = list(set([re.search(pattern, el).group(1)
         for el in hrefs if el.startswith('/store/apps/details')]))

    return apps

def leaderboard(identifier, category=None, start=0, num=24, hl="en"):
    if identifier not in ('topselling_paid', 'topselling_free'):
        raise Exception("identifier must be topselling_paid or topselling_free")

    url = 'https://play.google.com/store/apps'
    if category:
        if category not in CATEGORIES:
            raise Exception('%s not exists in category list' % category)
        url += "/category/" + str(category).upper()

    url += "/collection/%s?start=%s&num=%s&hl=%s" % (identifier, start, num, hl)
    return _get_apps(url)

def search(query, hl="en", c="apps"):
    url = ('https://play.google.com/store/search'
           '?q=%s&hl=%s&c=%s') % (query, hl, c)
    return _get_apps(url)

def developer(developer, num=24, hl="en", c="apps"):
    url = ('https://play.google.com/store/apps/developer'
           '?id=%s&num=%s&hl=%s&c=%s') % (
                   urllib.parse.quote_plus(developer), num, hl, c)
    return _get_apps(url)

class App(object):
    def __init__(self, package):
        self.url = "{}/store/apps/details?id={}&hl=en".format(BASE_URL, package)
        page = requests.get(self.url)
        tree = lxml.html.fromstring(page.content)

        for i in tree.xpath('//div[@class="IxB2fe"]/child::div[@class="hAyfc"]'):
            sel = i.xpath('div/text()')
            ans = i.xpath('span/div/span/text()')
            if len(sel) and len(ans) > 0:
                if sel[0] == 'Updated':
                    self.updated = ans[0]
                elif sel[0] == 'Size':
                    self.size = ans[0]
                elif sel[0] == 'Installs':
                    self.installs = ans[0]
                elif sel[0] == 'Current Version':
                    self.version = ans[0]
                elif sel[0] == 'Requires Android':
                    self.android = ans[0]
                elif sel[0] == 'Content Rating':
                    self.content_rating = ans[0]

        self.name = _get_text(tree, '//h1[@itemprop="name"]')
        self.package_name = package
        self.description = _get_attrs(tree, '//meta[@itemprop="description"]', 'content')
        self.category = _get_text(tree, '//a[@itemprop="genre"]')
        self.logo = _get_attrs(tree, '//img[@alt="Cover art"]', 'src')[0]
        self.price = _get_attrs(tree, '//meta[@itemprop="price"]', 'content')[0]
        self.free = self.price == 0
        self.developer_name = _get_text(tree, '//a[@class="hrTbp R8zArc"]')
        self.developer_email = _get_attrs(tree, '//a[starts-with(@href, "mailto")]', 'href')[0][7:]
        self.developer_website = _get_attrs(tree, '//a[text()="Visit website"]', 'href')[0]
        self.rating = _get_float(_get_attrs(tree, '//div[starts-with(@aria-label, "Rated")]', 'aria-label')[0])
        self.reviews = _get_text(tree, '//span[contains(@aria-label, "ratings")]').replace(',', '')
        self.images = list(filter(None, _get_attrs(tree, '//img[@alt="Screenshot Image"]', 'data-src')))
        self.similar = _get_apps(_get_attrs(tree, '//a[@aria-label="Check out more content from Similar"]', 'href')[0])

    def __repr__(self):
        return '<app title={}; package={}>'.format(self.name, self.package_name)

    def __str__(self):
        return self.name

    def __getitem__(self, key):
        return self.__dict__[key]


import numpy as np
from torch.utils.data import Dataset, DataLoader

class TabularDataset(Dataset):

  def __init__(self, data, cat_cols=None, output_col=None):

    self.n = data.shape[0]

    if output_col:
        self.y = data[output_col].astype(np.float32).values.reshape(-1, 1)
    else:
        self.y =  np.zeros((self.n, 1))

    self.cat_cols = cat_cols if cat_cols else []
    self.cont_cols = [col for col in data.columns if col not in self.cat_cols + [output_col]]

    if self.cont_cols:
        self.cont_X = data[self.cont_cols].astype(np.float32).values
    else:
        self.cont_X = np.zeros((self.n, 1))

    if self.cat_cols:
        self.cat_X = data[cat_cols].astype(np.int64).values
    else:
        self.cat_X =  np.zeros((self.n, 1))

  def __len__(self):
    return self.n

  def __getitem__(self, idx):
    return [self.y[idx], self.cont_X[idx], self.cat_X[idx]]


import requests
from pprint import pprint
import json

#search_url = 'http://www.ebi.ac.uk/pdbe/api/pdb/entry/molecules/'
id_code = '1cbs'
search_url = 'http://www.ebi.ac.uk/pdbe/api/pdb/entry/molecules/' + id_code

def url_response(url):
    print(url)
    r = requests.get(url=url)
    if r.status_code == 200:
        json_result = r.json()
        return json_result
    else:
        print(r.status_code, r.reason)
        return None

results = url_response(search_url)
molecules_list = results[id_code]
#pprint(molecules_list)
for dict in molecules_list:
    entity_id = dict['entity_id']
    molecule_name_list = dict['molecule_name']
    molecule_name = ','.join(molecule_name_list)
    print('entity id is %s ' % entity_id)
    print('molecule name is %s ' % molecule_name)
#pprint.pprint(results)


import numpy as np
import pickle as pk
import cv2
from softmax_lin import*

def show_by_cv2(img, name, enlarge=1):
    img1 = np.copy(img)
    img1 = change_to_2D(img1)
    img1[:,:,[0, 2]] = img1[:,:,[2, 0]]
    if not enlarge == 1:
        img1 = cv2.resize(img1, (0,0),
            fx=enlarge, fy=enlarge, interpolation=cv2.INTER_CUBIC)
    cv2.imshow(name, img1)

def change_to_2D(img1):
    img1 = np.reshape(img1, (3, 32, 32))
    img1 = img1.transpose(1, 2, 0)
    return img1

def test_all(imgs, labels, w):
    Count_yes = 0
    imgs = np.divide(imgs, 255.)
    for i in range(10000):
        y = np.argmax(softmax_pre(w, imgs[i]))
        if y == labels[i]:
            Count_yes += 1
    print("accuracy is: {0}".format(Count_yes / 10000))

def getMeta(img, w, metas):
    show_by_cv2(img, "pic", 2)
    cv2.waitKey(0)
    img = np.divide(img, 255.)
    y = np.argmax(softmax_pre(w, img))
    name = metas[y].decode("utf-8")
    print("this is: {0}".format(name))

def main():
    test_batch = load_train_set("../data/test_batch")
    imgs = test_batch[b"data"]
    labels = test_batch[b"labels"]
    metas = load_train_set("../data/batches.meta")[b"label_names"]
    mthd = input("which method?(softmax, svm): ")
    w_file = open("{0}_lin_res.pkl".format(mthd), "rb")
    w = pk.load(w_file)
    w_file.close()
    order = int(input("1.test accuracy 2.test one picture: "))
    if order == 1:
        test_all(imgs, labels, w)
    if order == 2:
        no = int(input("choose a pic(0--9999): "))
        getMeta(imgs[no], w, metas)

if __name__=="__main__":
    main()


import json
import os
import platform
import plistlib
import subprocess
import uuid
from lento.config import Config
from lento.utils import is_url
from PIL import Image

def create_card():
    new_card = {
        "id": str(uuid.uuid4().hex),
        "name": "Untitled Card",
        "emoji": "ðŸ˜ƒ",
        "time": 0,
        "hard_blocked_sites": {},
        "soft_blocked_sites": {},
        "hard_blocked_apps": {},
        "soft_blocked_apps": {},
        "notifications": {},
        "goals": {}
    }

    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")

    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    settings["cards"][new_card["name"]] = new_card

    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def read_cards():
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)
    return settings["cards"]

def delete_card(card_to_delete):
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)
    del settings["cards"][card_to_delete]
    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def update_metadata(card_to_modify, field_to_modify, new_value):
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    if settings["cards"][card_to_modify][field_to_modify] is None:
        raise Exception("Card field is nonexistent!")
    elif field_to_modify not in ["name", "emoji", "time"]:
        raise Exception("Card field is restricted!")
    elif field_to_modify == "time":
        new_value = float(new_value)

    settings["cards"][card_to_modify][field_to_modify] = new_value
    if field_to_modify == "name":
        new_cards = {
            new_value if k == card_to_modify
            else k: v for k, v in settings["cards"].items()
        }
        settings["cards"] = new_cards

    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def add_to_site_blocklists(card_to_modify, list_to_modify, new_value):
    """Add to either the `hard_blocked_sites` or `soft_blocked_sites` lists."""
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    card_to_mod = settings["cards"][card_to_modify]
    if card_to_mod[list_to_modify] is None:
        raise Exception("List is nonexistent!")
    elif list_to_modify not in [
                "hard_blocked_sites",
                "soft_blocked_sites"
            ]:
        raise Exception("Card field is restricted!")
    elif is_url(new_value) is False:
        raise Exception("URL not valid!")
    elif list_to_modify == "hard_blocked_sites":
        if new_value in card_to_mod["soft_blocked_sites"]:
            raise Exception(f"'{new_value}' already soft blocked!")
    elif list_to_modify == "soft_blocked_sites":
        if new_value in card_to_mod["hard_blocked_sites"]:
            raise Exception(f"'{new_value}' already hard blocked!")

    settings["cards"][card_to_modify][list_to_modify][new_value] = True
    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def update_site_blocklists(card_to_modify, list_to_modify, new_sites_dict):
    """Update one of the blocked_sites lists. Minimal validation."""
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    if settings["cards"][card_to_modify][list_to_modify] is None:
        raise Exception("List is nonexistent!")
    elif list_to_modify not in [
                "hard_blocked_sites",
                "soft_blocked_sites"
            ]:
        raise Exception("Card field is restricted!")
    elif not isinstance(new_sites_dict, dict):
        raise Exception("new_sites_dict is not a dict!")

    settings["cards"][card_to_modify][list_to_modify] = new_sites_dict
    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def add_to_app_blocklists(card_to_modify, list_to_modify, apps_to_add):
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    card = settings["cards"][card_to_modify]

    current_os = platform.system()
    if current_os == "Darwin":
        for app in apps_to_add:
            app_name = os.path.basename(app).replace(".app", "")

            if list_to_modify == "hard_blocked_apps":
                if app_name in card["soft_blocked_apps"]:
                    raise Exception(f"'{app_name}' already soft blocked!")
            elif list_to_modify == "soft_blocked_apps":
                if app_name in card["hard_blocked_apps"]:
                    raise Exception(f"'{app_name}' already hard blocked!")

            bundle_id = subprocess.check_output([
                "mdls",
                "-name",
                "kMDItemCFBundleIdentifier",
                "-r",
                app
            ]).decode("utf-8")

            if app[:14] == "/Applications/":
                app = os.path.join(
                    Config.MACOS_APPLICATION_FOLDER,
                    app_name + ".app"
                )
                plist_path = os.path.join(
                    app,
                    "Contents",
                    "Info.plist"
                )
            else:
                plist_path = os.path.join(app, "Contents", "Info.plist")
            with open(plist_path, "rb") as fp:
                app_plist = plistlib.load(fp)
            icon_name = app_plist["CFBundleIconFile"]
            if icon_name[-5:] != ".icns":
                icon_name = app_plist["CFBundleIconFile"] + ".icns"
            original_icon_path = os.path.join(
                app,
                "Contents",
                "Resources",
                icon_name
            )
            im = Image.open(original_icon_path)
            rgb_im = im.convert("RGB")

            path_to_save_at = os.path.join(
                    os.path.expanduser("~"),
                    "Library/Application Support/Lento/" + app_name + ".jpg"
                )
            rgb_im.save(path_to_save_at)

            card[list_to_modify][app_name] = {
                "enabled": True,
                "bundle_id": bundle_id,
                "app_icon_path": path_to_save_at
            }
    elif current_os == "Windows":
        for app in apps_to_add:
            app_name = app["name"]
            if list_to_modify == "hard_blocked_apps":
                if app_name in card["soft_blocked_apps"]:
                    raise Exception(f"'{app_name}' already soft blocked!")
            elif list_to_modify == "soft_blocked_apps":
                if app_name in card["hard_blocked_apps"]:
                    raise Exception(f"'{app_name}' already hard blocked!")
            card[list_to_modify][app["name"]] = {
                "enabled": True,
                "path": app["path"],
                "app_icon_path": app["icon_path"]
            }
    else:
        raise Exception("OS name invalid or not found!")

    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def update_app_blocklists(card_to_modify, list_to_modify, new_list_structure):
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    if list_to_modify not in [
                "hard_blocked_apps",
                "soft_blocked_apps"
            ]:
        raise Exception("Card field is restricted!")

    settings["cards"][card_to_modify][list_to_modify] = new_list_structure

    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def add_notification(
            name,
            enabled,
            card_to_modify,
            type,
            blocked_visit_triggers,
            associated_goals,
            time_interval_trigger,
            title,
            body,
            audio_paths
        ):
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    if not isinstance(name, str):
        raise Exception("Name must be a string!")
    elif not isinstance(enabled, bool):
        raise Exception("Enabled must be a boolean!")
    elif type not in ["banner", "popup", "audio"]:
        raise Exception("Notification type not valid!")
    elif not isinstance(blocked_visit_triggers, list):
        raise Exception("Blocked visit triggers is not a list!")
    for item in blocked_visit_triggers:
        list_checks = (
            item in settings["cards"][card_to_modify]["hard_blocked_sites"],
            item in settings["cards"][card_to_modify]["soft_blocked_sites"],
            item in settings["cards"][card_to_modify]["hard_blocked_apps"],
            item in settings["cards"][card_to_modify]["soft_blocked_apps"],
        )
        if True not in list_checks:
            raise Exception(f"Blocked visit triggers '{item}' not found in blocklists!")  # noqa: E501
    if not isinstance(associated_goals, list):
        raise Exception("Associated goals is not a list!")
    for item in associated_goals:
        if item not in settings["cards"][card_to_modify]["goals"]:
            raise Exception("Associated goals not found in goal list!")
    if not isinstance(time_interval_trigger, int) and time_interval_trigger is not None:  # noqa: E501
        raise Exception("Timer interval trigger is not an integer or None!")
    elif not isinstance(title, str) and title is not None:
        raise Exception("Notification title is not a string!")
    elif not isinstance(body, str) and body is not None:
        raise Exception("Notification body is not a string!")

    new_notif = {
        "name": name,
        "enabled": enabled,
        "type": type,
        "blocked_visit_triggers": blocked_visit_triggers,
        "associated_goals": associated_goals,
        "time_interval_trigger": time_interval_trigger,
        "title": title,
        "body": body,
        "audio_paths": audio_paths
    }

    card = settings["cards"][card_to_modify]
    card["notifications"][str(uuid.uuid4().hex)] = new_notif

    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def update_notification_list(card_to_modify, new_notifs_dict):
    """Update notifications for a card. Minimal validation."""
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    if not isinstance(new_notifs_dict, dict):
        raise Exception("new_notifs_dict is not a dict!")
    for item in list(new_notifs_dict.keys()):
        is_notif_dict_valid = set(new_notifs_dict[item].keys()) == set([
            "name",
            "enabled",
            "type",
            "blocked_visit_triggers",
            "associated_goals",
            "time_interval_trigger",
            "title",
            "body",
            "audio_paths"
        ])
        if not is_notif_dict_valid:
            raise Exception(f"Notif {item} had invalid structure!")

    settings["cards"][card_to_modify]["notifications"] = new_notifs_dict

    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def add_goal(card_to_modify: str, goal_to_add: str) -> None:
    """Add a goal to a card. Automatically adds as disabled."""
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")

    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    if not isinstance(goal_to_add, str):
        raise Exception("Goal to add is not string!")

    settings["cards"][card_to_modify]["goals"][goal_to_add] = False

    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)

def update_goal_list(card_to_modify, new_goals_dict):
    """Update goals for a card. Minimal validation."""
    path = os.path.join(os.path.expanduser("~"), "lentosettings.json")
    with open(path, "r", encoding="UTF-8") as settings_json:
        settings = json.load(settings_json)

    if not isinstance(new_goals_dict, dict):
        raise Exception("new_goals_dict is not a dict!")
    for item in list(new_goals_dict.keys()):
        if not isinstance(new_goals_dict[item], bool):
            raise Exception(f"Goal '{item}' has invalid structure!")

    settings["cards"][card_to_modify]["goals"] = new_goals_dict

    with open(path, "w", encoding="UTF-8") as settings_json:
        json.dump(settings, settings_json)