import unittest
import scanner.logSetup as logSetup

import deduplicator.ProcessArchive

import Tests.basePhashTestSetup

import os.path
import scanner.fileHasher

import pyximport
pyximport.install()
import deduplicator.cyHamDb as hamDb

from Tests.baseArchiveTestSetup import CONTENTS

class TestHasher(scanner.fileHasher.HashThread):

	def getDbConnection(self):
		return Tests.basePhashTestSetup.TestDbBare()

# Override the db connection object in the ArchChecker so it uses the testing database.
class TestArchiveChecker(deduplicator.ProcessArchive.ArchChecker):
	hasher = TestHasher
	def getDbConnection(self):
		return Tests.basePhashTestSetup.TestDbBare()

class TestArchChecker(unittest.TestCase):
	maxDiff = None

	def __init__(self, *args, **kwargs):
		logSetup.initLogging()
		super().__init__(*args, **kwargs)
		self.maxDiff = None

	def setUp(self):

		self.addCleanup(self.dropDatabase)

		self.db = Tests.basePhashTestSetup.TestDb()

		# Check the table is set up
		self.verifyDatabaseLoaded()

	def dropDatabase(self):
		self.db.tearDown()
		self.db.close()

	def _reprDatabase(self, db):
		'''
		This prints a reproduction of the db contents that can be pasted right into
		a python file. This makes updating the db template (baseArchiveTestSetup) much
		easier when new files are added to the test-suite.
		'''
		for row in db:
			print('{},   # phash: {:b}'.format(list(row), row[4] if row[4] else 0))

	def verifyDatabaseLoaded(self):
		expect = list(CONTENTS)
		expect.sort()
		items = list(self.db.getItems())
		items.sort()
		if items != expect:
			self._reprDatabase(items)

		self.assertEqual(items, expect)

class TestArchChecker_1(TestArchChecker):
	def test_significantlySimilar_1(self):
		cwd = os.path.dirname(os.path.realpath(__file__))

		ck = TestArchiveChecker('{cwd}/test_ptree/notQuiteAllArch.zip'.format(cwd=cwd))
		ret = ck.getSignificantlySimilarArches(searchDistance=2)
		expect = {
			5:
				[
					'{cwd}/test_ptree/allArch.zip'.format(cwd=cwd)
				]
		}
		self.assertEqual(ret, expect)

	def test_junkFileFiltering(self):

		cwd = os.path.dirname(os.path.realpath(__file__))

		# Remove junk zip so z_reg is actually unique
		ck = TestArchiveChecker('{cwd}/test_ptree/z_reg_junk.zip'.format(cwd=cwd))

		ret = ck.getSignificantlySimilarArches()

		expect = {
			2:
				[
					'{cwd}/test_ptree/z_reg.zip'.format(cwd=cwd),
				]
		}
		self.assertEqual(ret, expect)

	def test_sizeFiltering2(self):

		cwd = os.path.dirname(os.path.realpath(__file__))

		# Remove junk zip so z_reg is actually unique
		ck = TestArchiveChecker('{cwd}/test_ptree/z_sml.zip'.format(cwd=cwd))

		ret = ck.getSignificantlySimilarArches()

		expect = {
			2:
				[
					'{cwd}/test_ptree/z_reg.zip'.format(cwd=cwd),
					'{cwd}/test_ptree/z_reg_junk.zip'.format(cwd=cwd),
				]
		}
		self.assertEqual(ret, expect)

	def test_significantlySimilar_3(self):
		cwd = os.path.dirname(os.path.realpath(__file__))
		# Check that we are properly matching larger images
		ck = TestArchiveChecker('{cwd}/test_ptree/small.zip'.format(cwd=cwd))
		ret = ck.getSignificantlySimilarArches(searchDistance=2)

		expect = {
			4:
				[
					'{cwd}/test_ptree/regular.zip'.format(cwd=cwd),
					'{cwd}/test_ptree/small_and_regular.zip'.format(cwd=cwd),
				],
			5:
				[
					'{cwd}/test_ptree/regular-u.zip'.format(cwd=cwd),
				]
		}
		print(expect)
		print(ret)
		self.assertEqual(ret, expect)

class TestArchChecker_2(TestArchChecker):

	def test_significantlySimilar_2(self):
		cwd = os.path.dirname(os.path.realpath(__file__))

		ck = TestArchiveChecker('{cwd}/test_ptree/regular.zip'.format(cwd=cwd))
		ret = ck.getSignificantlySimilarArches(searchDistance=2)

		expect = {
			4:
				[
					'{cwd}/test_ptree/regular-u.zip'.format(cwd=cwd),
					'{cwd}/test_ptree/small_and_regular.zip'.format(cwd=cwd),
				]
		}
		print("ret:", ret)
		print("expect:", expect)
		self.assertEqual(ret, expect)


from dash import Dash, dash_table, dcc, html, Input, Output
import dash
import pandas as pd
# A bit of style
import dash_bootstrap_components as dbc
from fmp_extractor.news.news import extract_top_news

from aux import get_names_symbols, get_all_quotes, graph_callback_all_history

# List of options for tickers based on the list of available symbols
names_symbols = get_names_symbols()
exchanges = names_symbols.exchange.unique()

# Values to compute the averages of the means
SHORT_TERM = 30
LONG_TERM = 200

# Order of the columns to show in the table
order_column = ['name', 'symbol', 'price', 'changesPercentage', 'price_to_yearHighpercent', 'marketCap', 'volume',
                'voltoavgvolume', 'change', 'dayLow',
                'dayHigh', 'yearHigh', 'yearLow',
                'priceAvg200', 'exchange', 'open',
                'previousClose', 'eps', 'pe', 'earningsAnnouncement',
                'sharesOutstanding', 'timestamp']
app = Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div(className='row', children=[
    html.Div(children=[
        html.H4("Market view"),
        dcc.Dropdown(
            id='exchange',
            value='XETRA',
            clearable=True,
            options=exchanges
        ),
        html.Div(id='table')]),
    html.Div(className='row', children=[ html.Div(className='row', children=[
        html.H4("Historical Chart"),
        dcc.Dropdown(
            id='name_1',
            value='Netflix, Inc., NFLX',
            clearable=True,
            options=names_symbols.index
        ),
        dcc.Graph(id='close_price_1')], style={'display': 'inline-block', 'width': '48%', 'height': '50%'}),
                                        html.Div(className='row', children=[
                                            html.H4("Latest News"),
                                            html.Div(children=html.Div(id='no_news', children=[],
                                                                       style={'width': '3', 'height': '15'})),
                                            html.Div(className='row', children=[html.Div(id='news')])],
                                                 style={'display': 'inline-block', 'width': '48%', 'height': '700'}
                                                 )]
             )]
)

@app.callback(Output('table', 'children'), Input('exchange', 'value'))
def get_quotes_exchange(exch):
    df = get_all_quotes(exch)
    df.loc[:, 'price_to_yearHighpercent'] = (df.loc[:, 'price'] /
                                             df.loc[:, 'yearHigh'] * 100).copy()
    df['marketCap'] *= 1e-9
    df['voltoavgvolume'] = df['volume'] / df['avgVolume']
    return dash_table.DataTable(
        id='datatable-interactivity',
        columns=[
            {"name": i.capitalize(), "id": i, "deletable": True, "selectable": True} for i in df.loc[:, order_column]
        ],
        data=df.to_dict('records'),
        editable=True,
        filter_action="native",
        sort_action="native",
        virtualization=True,
        sort_mode="multi",
        column_selectable="single",
        row_selectable="multi",
        selected_columns=[],
        selected_rows=[],
        page_action="native",
        page_current=0,
        page_size=10,
        style_header={
            'backgroundColor': 'rgb(30, 30, 30)',
            'color': 'white',
        },
        style_data={
            'backgroundColor': 'rgb(50, 50, 50)',
            'color': 'white',
        },
        style_table={'minWidth': '100%'},
        fixed_columns={'headers': True, 'data': 1},

    ),

@app.callback(Output('close_price_1', 'figure'), Input('name_1', 'value'))
def price_hist_1(name_1):
    close_figure = graph_callback_all_history(name_1, names_symbols, freq=None, short_term=SHORT_TERM,
                                              long_term=LONG_TERM)
    close_figure.update_layout(height=700, yaxis=dict(autorange=True, fixedrange=False),
                               xaxis=dict(
                                   rangeselector=dict(
                                       buttons=list([
                                           dict(count=1,
                                                label="1m",
                                                step="month",
                                                stepmode="backward"),
                                           dict(count=6,
                                                label="6m",
                                                step="month",
                                                stepmode="backward"),
                                           dict(count=1,
                                                label="YTD",
                                                step="year",
                                                stepmode="todate"),
                                           dict(count=1,
                                                label="1y",
                                                step="year",
                                                stepmode="backward"),
                                           dict(count=2,
                                                label="2y",
                                                step="year",
                                                stepmode="backward"),
                                           dict(count=5,
                                                label="5y",
                                                step="year",
                                                stepmode="backward"),
                                           dict(step="all")
                                       ])
                                   ),
                                   rangeslider=dict(
                                       visible=True
                                   ),
                                   type="date"
                               )
                               )
    return close_figure

@app.callback(Output('news', 'children'),
              Output('no_news', 'children'),
              Input('name_1', 'value'))
def generate_table(name):
    ticker = names_symbols.at[name, 'symbol']
    news = extract_top_news([ticker], limit=50)
    try:
        df = pd.DataFrame.from_records(list(news.values())[0]).loc[:, ['publishedDate', 'title', 'text', 'url']]
    except KeyError:
        return dash.no_update, dbc.Alert('No news for the selected ticker', color='danger', dismissable=True)

    df['Date'] = df['publishedDate'].str[:11]
    df['Time'] = df['publishedDate'].str[11:]
    table = html.Table([
        html.Thead(
            html.Tr([html.Th(col) for col in ['Date', 'Time', 'Title']],
                    style={'white-space': 'nowrap', 'padding': '3px'})
        ),
        html.Tbody([
            html.Tr([
                html.Td(df.iloc[i]['Date'], style={'white-space': 'nowrap', 'padding': '3px'}),
                html.Td(df.iloc[i]['Time'], style={'white-space': 'nowrap', 'padding': '3px'}),
                dcc.Link(html.A(df.iloc[i]['title']), href=df.iloc[i]['url'], target="_blank")
            ]) for i in range(df.shape[0])])
    ])
    return dbc.Table(table, bordered=True, striped=True, responsive=True, color='light',
                     style={'white-space': 'nowrap', 'border-spacing': '3px'}), dash.no_update

if __name__ == '__main__':
    app.run_server(debug=True, port=8070)


S = input()
stack = []
count = {
    '0': 0,
    '1': 0,
}

for i in S:
    if len(stack) == 0:
        stack.append(i)
    if stack[-1] != i:
        stack = [i]
        count[i] += 1

print(max(count.values()))


#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import math
import tf
from tf.transformations import euler_from_quaternion
from nav_msgs.msg import Odometry
import geometry_msgs.msg
import numpy as np

OperationType = 'Teleoperation'
ESCALAR_FACTOR=70.0
p_ref_ant=np.array([[0.0],[0.0]])
p_ref=np.array([[0.0],[0.0]])
x= 0.0
y= 0.0
theta=0.0
m=0

#ODOMETRY DATA
def Odom(msg):
    global x
    global y
    global theta

    x=msg.pose.pose.position.x
    y=msg.pose.pose.position.y
    rot_q=msg.pose.pose.orientation
    angles=euler_from_quaternion([rot_q.x, rot_q.y, rot_q.z, rot_q.w])
    theta=angles[2]

def callback(data):
    global OperationType

    OperationType = data.data

def PostureReference(x_ant,y_ant):

    x = rospy.get_param('x_position',x_ant)
    y = rospy.get_param('y_position',y_ant)
    return x, y

def TrayReference(tray):
    tray = rospy.get_param('TrayMode',tray)
    t = rospy.Time.now().to_sec() * math.pi
    if tray == 1:
        x = 2.0 * math.cos(t/ESCALAR_FACTOR)
        y = 2.0 * math.sin(t/ESCALAR_FACTOR)
    elif tray == 2:
        x = 2.0 * math.sin(t/ESCALAR_FACTOR)/(1+math.pow(math.cos(t/ESCALAR_FACTOR),2))
        y = 2.0 * math.sin(t/ESCALAR_FACTOR) * math.cos(t/ESCALAR_FACTOR)/(1+math.pow(math.cos(t/ESCALAR_FACTOR),2))
    elif tray == 3:
        x = 2.0 * math.sin(t/ESCALAR_FACTOR)/(1+math.pow(math.sin(t/ESCALAR_FACTOR),2))
        y = 2.0 * math.sin(t/ESCALAR_FACTOR) * math.cos(t/ESCALAR_FACTOR)/(1+math.pow(math.sin(t/ESCALAR_FACTOR),2))
    else:
        x = 0.0
        y = 0.0
    return x, y, tray

#iNVERSE KINEMATIC PID CONTROL
def Control(angle,x_pos,y_pos,pos_before,pos_ref,K_sin):
    Jr=np.array([[math.cos(angle) ,-0.15 * math.sin(angle)],[math.sin(angle) ,0.15 * math.cos(angle)]])
    Jr_inv=np.linalg.inv(Jr)
    K=np.array([[K_sin[0], 0],[0, K_sin[1]]])
    posp_d=pos_ref - pos_before
    pos=np.array([[x_pos],[y_pos]])
    pos_error=pos_ref - pos
    pos_error[0, 0]=math.tanh(pos_error[0, 0])
    pos_error[1, 0]=math.tanh(pos_error[1, 0])
    c=np.dot(Jr_inv, (10 * posp_d + np.dot(K,pos_error)))
    c1=c[0, 0]
    c2=c[1, 0]
    return c1,c2

if __name__ == '__main__':

    rospy.init_node('ControlReactNative', anonymous=True)
    diff_vel = rospy.Publisher('/mobile_base_controller/cmd_vel', geometry_msgs.msg.Twist,queue_size=1)
    rospy.Subscriber("mode", String, callback)
    sub_odom = rospy.Subscriber('/mobile_base_controller/odom',Odometry,Odom)
    br = tf.TransformBroadcaster()
    rate = rospy.Rate(10.0)
    while not rospy.is_shutdown():
        if OperationType != 'Teleoperation':
            p_ref_ant[0, 0], p_ref_ant[1, 0] = p_ref[0, 0], p_ref[1, 0]
            if a == 0:
                diff_vel = rospy.Publisher('/mobile_base_controller/cmd_vel', geometry_msgs.msg.Twist,queue_size=1)
                a = 1
            if OperationType == 'Posture Control':
                p_ref[0, 0], p_ref[1, 0] = PostureReference(p_ref[0, 0], p_ref[1, 0])
            else:
                p_ref[0, 0], p_ref[1, 0], m = TrayReference(m)

            br.sendTransform(( p_ref[0, 0], p_ref[1, 0], 0.0),
                    (0.0, 0.0, 0.0, 1.0),
                    rospy.Time.now(),
                    "ref",
                    "odom")

            linear, angular = Control(theta, x, y, p_ref_ant, p_ref, [0.6, 0.6])
            cmd = geometry_msgs.msg.Twist()
            cmd.linear.x = linear
            cmd.angular.z = angular
            diff_vel.publish(cmd)
        else:
            a = 0
            diff_vel.unregister()
        rate.sleep()


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

import operator
import sqlite3

class Dictionary:
    def __init__(self, filename, index=True, load=True):
        self.filename = filename
        with open(filename) as f:
            pass
        if load:
            self.db = sqlite3.connect(filename)
            def isWord(tags):
                self.tags = tags.split(" ")
                return not set(tags.split(" ")).intersection(["p","m","f","g","h","s","u"])
            self.db.create_function("isWord",1,isWord)
            self.indices = set()

    def findTerm(self, word, wildcards=False):
        self.requireIndex('Terms', 'expression')
        self.requireIndex('Terms', 'reading')

        cursor = self.db.cursor()
        if wildcards and isinstance(word,list):
            def constr(x):
                return u"expression LIKE \"%{0}%\"".format(x)
            query = u" OR ".join(map(constr,word))
            self.query = query
            cursor.execute(u'SELECT * FROM Terms WHERE ('+query+u') AND isWord(tags) AND glossary NOT LIKE "%(obsc)%" AND glossary NOT LIKE "%(arch)%"')
        else:
            cursor.execute('SELECT * FROM Terms WHERE expression {0} ? OR\
                           reading=? LIMIT 100'.format('LIKE' if
                                                                    wildcards
                                                                    else '='),
                           (word, word))

        results = list()
        for fetch in cursor.fetchall():
            if len(fetch)==6:
                expression, reading, glossary, tags, defs, refs = fetch
            else:
                expression, reading, glossary, tags = fetch
                defs = refs = ''
            results.append({
                'expression': expression,
                'reading': reading,
                'glossary': glossary,
                'tags': tags.split(),
                'defs': defs,
                'refs': refs
            })

        return results

    def findCharacter(self, character):
        assert len(character) == 1
        self.requireIndex('Kanji', 'character')

        cursor = self.db.cursor()
        cursor.execute('SELECT * FROM Kanji WHERE character=? LIMIT 1', character)

        query = cursor.fetchone()
        if query is not None:
            character, kunyomi, onyomi, glossary, ongroup = query
            return {
                'character': character,
                'kunyomi': kunyomi,
                'onyomi': onyomi,
                'glossary': glossary,
                'ongroup': ongroup
            }

    def requireIndex(self, table, column):
        name = 'index_{0}_{1}'.format(table, column)
        if not self.hasIndex(name):
            self.buildIndex(name, table, column)

    def buildIndex(self, name, table, column):
        cursor = self.db.cursor()
        cursor.execute('CREATE INDEX {0} ON {1}({2})'.format(name, table, column))
        self.db.commit()

    def hasIndex(self, name):
        if name in self.indices:
            return True

        cursor = self.db.cursor()
        cursor.execute('SELECT * FROM sqlite_master WHERE name=?', (name,))
        if len(cursor.fetchall()) == 0:
            return False

        self.indices.update([name])
        return True


# standard deviation is a number that describes how spread out the values are

# a low standard deviation means that most of the numbers are close to the mean(average) value.

# a high standard deviation means that the values are spread out over a wider range.

"""
speed = [86,87,88,86,87,85,86]
The standard deviation is: 0.9
Meaning that most of the values are
within the range of 0.9 from the mean value, which is 86.4.

Let us do the same with a selection of numbers
with a wider range:

"""
import numpy as np

speed = np.array([86, 87, 88, 86, 87, 85, 86])

x = np.std(speed)

print('The standard deviation: ', x)


from mpi4py import MPI
import time
import math
import numpy as np
t0 = time.time()
from sympy import *
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
nprocs = comm.Get_size()
nsteps=10000000

x=symbols('x')

if rank == 0:

    sendbuf = np.arange(1,nsteps,dtype=np.float64)

    ave, res = divmod(nsteps, nprocs)
    counts = np.array([ave + 1 if p < res else ave for p in range(nprocs)])
    starts = np.array([sum(counts[:p]) for p in range(nprocs)])

else:
    sendbuf = None
    data = None
    counts = np.empty(nprocs, dtype=np.int)
    starts=np.empty(nprocs, dtype=np.int)

comm.Bcast(counts,root=0)
comm.Bcast(starts,root=0)

recvbuf = np.zeros(counts[rank])

partial_pi = np.zeros(nprocs)

t0 = time.process_time()
partial_pi[rank]= 4* integrate(1/(1+(x)**2),(x,starts[rank]/nsteps,(starts[rank]+counts[rank])/nsteps))
t1 = time.process_time()
print(partial_pi[rank])

counts=np.ones(nprocs)
pi_value= np.zeros(nprocs)
starts=np.array(list(range(nprocs)))

comm.Gatherv(partial_pi[rank], [pi_value, counts, starts, MPI.DOUBLE], root=0)
if rank == 0:
    print("Computed pi value is: {}".format(sum(pi_value)))
    print('*'*50)
    print('pi computed in {:.3f} sec'.format(t1 - t0))

    print('*'*50)
    print('error is {}'.format(abs(sum(pi_value)- math.pi)))


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image

df = pd.read_csv('malzenstwa13.csv', header=0, sep=';')
new_df = pd.melt(df, id_vars=["Województwo"], var_name="Rok", value_name="Liczba")

etykiety = new_df['Rok'].unique()
sl = new_df[new_df['Województwo'] == 'ŚLĄSKIE']
print(sl)
op = new_df[new_df['Województwo'] == 'OPOLSKIE']
print(op)
mp = new_df[new_df['Województwo'] == 'MAŁOPOLSKIE']
print(mp)

plt.plot(etykiety, sl['Liczba'], label='slaskie')
plt.plot(etykiety, op['Liczba'], label='opolskie')
plt.plot(etykiety, mp['Liczba'], label='malopolskie')
plt.legend()
plt.title('malzenstwa z podzialem na wojewodztwa')
plt.ylabel('Liczba malzesntw')
plt.xlabel('Rok')
plt.show()


import time
import requests
from kafka import KafkaProducer

# Define a function to get sensor data from a URL

def get_sensor_data_stream():
    try:
        url = 'http://0.0.0.0:3030/sensordata'
        r = requests.get(url)
        return r.text
    except:
        return "Error in Connection"

# Create a Kafka producer with bootstrap servers set to localhost:9092
producer = KafkaProducer(bootstrap_servers=['localhost:9092'])

while True:
    try:
        # Get sensor data using the get_sensor_data_stream() function
        msg = get_sensor_data_stream()

        # Send the message to the RawSensorData topic
        producer.send("RawSensorData", msg.encode('utf-8')).get(timeout=10)

        # Print a message indicating the message was produced
        print(f'Producing... {msg}')

        # Wait for 1 second before sending the next message
        time.sleep(1)

    except Exception as e:
        # Handle any errors that occur when sending the message
        print(f'Error sending message: {e}')
        # Wait for 5 seconds before trying to send the message again
        time.sleep(5)


from flask import Flask, request, render_template, session, send_file
from forms import StepUploadForm
import requests
from flask_wtf.csrf import CSRFProtect
from werkzeug.utils import secure_filename
import os
import shutil
from uuid import uuid4

app = Flask(__name__)
csrf = CSRFProtect(app)
csrf.init_app(app)
app.config['SECRET_KEY'] = 'hi'
app.config['ALLOWED_EXTENSIONS'] = ['STEP', 'step']
app.config['UPLOADED_STEP_FILES_DEST'] = os.getcwd() + '/step_uploads'
# app.config['COMPONENT_CLASSIFIER_URL'] = 'http://68.183.158.9:5000/api/classify_step/'
app.config['COMPONENT_CLASSIFIER_URL'] = 'http://component_classifier_cq_1:5000/api/classify_step/'

@app.route("/")
def hello():
    return "Hello Fat World!"

@app.route("/upload_step", methods=['GET', 'POST'])
def classify_step():
    form = StepUploadForm()
    image = None
    if form.validate_on_submit():
        step = request.files['step_file']
        step_filename = secure_filename(step.filename).replace(' ','_')
        step.filename = os.path.join('.',step_filename)
        if not os.path.exists(app.config['UPLOADED_STEP_FILES_DEST']):
            os.mkdir(app.config['UPLOADED_STEP_FILES_DEST'])
        step.filename = os.path.join(app.config['UPLOADED_STEP_FILES_DEST'], step_filename)

        if allowed_file(step.filename, 'step'):
            step.save(step.filename)
            files = {'step': open(step.filename, 'rb')}
            payload = {'filename': 'hello.step'}
            r = requests.post(app.config['COMPONENT_CLASSIFIER_URL'], files=files, data=payload, stream=True)

            img_id = str(uuid4())
            session['img_id'] = img_id
            image = 'static/{}.png'.format(img_id)

            with open(image, 'wb') as img:
                img.write(r.content)
        else:
            flash('Invalid file type! Only STEP files can be uploaded.')

    return render_template('upload_step.html', title='Home',form=form, image=image)

@app.after_request
def add_header(response):
    """
    Add headers to both force latest IE rendering engine or Chrome Frame,
    and also to cache the rendered page for 10 minutes.
    """
    response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
    response.headers['Cache-Control'] = 'public, no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '-1'
    return response

@app.route("/cc_image")
def cc_image():
    img_id = session['img_id']
    return send_file(os.path.join(app.root_path,'static/{}.png'.format(img_id)), cache_timeout=0)

def allowed_file(filename, file_type):
    """Determines whether filename has acceptable extension
    """
    extension = filename.rsplit('.', 1)[1].lower()
    if ('.' in filename) and \
       (extension in app.config['ALLOWED_EXTENSIONS']) and \
       (extension == file_type):
        return True
    else:
        return False

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True, threaded=True)


import math
import random
import json
import os
import sys
import time
import datetime
from termcolor import colored

import torch
import torch.nn as nn
import argparse

from . import data
from . import wsrt

parser = argparse.ArgumentParser(description='Forced Recursive Transformer')
parser.add_argument('--model-config', type=str, required=True,
                    help='Model json config')
parser.add_argument('--cuda', action='store_true',
                    help='use CUDA')
parser.add_argument('--params', type=str, help='Model params path', required=True)
parser.add_argument('--dict', type=str, help='Dictionary path')

args = parser.parse_args()

assert os.path.isdir("output/"), "You need a folder called 'output' in order to save test predictions"
assert os.path.isdir("tb/"), "You need a folder called 'tb' for tensorboard"
assert os.path.isdir("output/dict/"), "You need a folder called 'dict' in order to save/load a dictionary"
assert os.path.isdir("checkpoints/"), "You need a folder called 'checkpoints' in order to save model params"

# Set the random seed manually for reproducibility.
# torch.manual_seed(args.seed)
if torch.cuda.is_available():
    if not args.cuda:
    	utils.confirm("You have a CUDA device, so you should probably run with --cuda.")
    else:
    	print("Using CUDA device")

device = torch.device("cuda" if args.cuda else "cpu")

with open(args.model_config) as f:
  model_config = json.load(f)
  dictionary_path = args.dict if args.dict else "output/dict/{}_dict.json".format(model_config["NAME"])

  with open(model_config["DATASET_CONFIG"]) as f:
  	dataset_config = json.load(f)

dataset = data.Dataset(dataset_config)
dataset.loadDictionary(dictionary_path)
dataset.device = device
dataset.dictionary.freeze_dict = True

model_config["TOKENS"] = dataset.tokens()
model_config["SRC_LEN"] = dataset.SRC_LEN
model_config["TGT_LEN"] = dataset.TGT_LEN

model = wsrt.WSRT(model_config)
model.device = device
model.to(device)

model.load_state_dict(torch.load(args.params, map_location=torch.device(device)))
model.eval()

src_text = "51-19"
src_text = dataset.START + src_text + dataset.END
src_text += (dataset.SRC_LEN - len(src_text)) * dataset.PADDING

src_indicies = dataset.text2tensor(src_text).view(-1, 1)
# print(src_indicies)
output = model.predict(src_indicies, None, dataset.dictionary.word2idx[dataset.START])
# print(output)
# print(output.shape)
output_string = dataset.tensor2text(output.view(-1))   # .split(dataset.END)[0]
print(" ", colored(output_string, "blue"))


class Solution:
    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        N = len(num)
        carry = k
        i = N - 1
        res = []

        while i >= 0 or carry > 0:
            if i >= 0:
                carry += num[i]
                i -= 1

            res.append(carry % 10)
            carry //= 10

        return res[::-1]


from django.db import models
from django.forms.widgets import NumberInput
from  django.db.models.signals import post_save
from django.conf import settings
from simple_history.models import HistoricalRecords
from simple_history import register
import datetime
from django.urls import reverse
from applications.argumento.models import Estado
from applications.courrier.models import courrier
from applications.datos_g.models import Motivo
from applications.fisico.models import Fisico, Bolsa
from applications.guia.models import Guia
from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple
from model_utils.models import TimeStampedModel
from .managers import ProductManager

class Est_planilla(models.Model):
    estado = models.CharField(max_length=20)

    def __str__(self):
        return str(self.estado)

class Cargue(TimeStampedModel):

    id = models.AutoField(
        primary_key=True,
        verbose_name ='Planilla',
    )
    guia = models.ManyToManyField(
        Fisico,
        through= 'Planilla',

    )

    full_name = models.ForeignKey(
        courrier,
        on_delete=models.CASCADE,
        verbose_name= 'Mensajero'
        )

    fecha = models.DateTimeField(auto_now=True, verbose_name = 'Fecha de entrega')

    objects = ProductManager()

    class Meta:
        verbose_name = "Cargue"
        verbose_name_plural = "Cargue"

    def __str__(self):
        return str(self.id)

class Planilla(TimeStampedModel) :

    guia = models.ForeignKey(
        Fisico,
        related_name= "planilla_filtro",
        on_delete=models.CASCADE
    )
    cargue = models.ForeignKey(
        Cargue,
        on_delete=models.CASCADE,
        blank=True, null=True,
        verbose_name="Planilla"
    )
    full_name = models.ForeignKey(
        courrier,
        on_delete=models.CASCADE,
        verbose_name= 'Mensajero',
        blank = True
        )

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        blank=True, null=True,
        editable=True,
        verbose_name= 'Usuario Gestion',
    )

    fecha = models.DateField(
        auto_now=True
    )
    cont = models.IntegerField(blank=True, null=True)

    history = HistoricalRecords()

    def authenticated(self, user):
        return self.filter(user=user)

    def __str__(self):
        return str(self.guia)

    @property
    def cargues(self):
        return str(self.cargue)

    @property
    def mensajeros(self):
        return self.full_name

    @property
    def id_planilla(self):
        return self.id

    @property
    def contar(self):
        return self.cont

    @property
    def fecha_planilla(self):
        return self.fecha

#f
    def save(self, *args, **kwargs):
        self.guia.fecha_planilla = datetime.datetime.now()

        self.guia.id_est_id = self.guia.id_est_id = 4
        self.guia.mensajero = self.mensajeros
        self.guia.est_planilla = self.guia.est_planilla = 1
        self.guia.id_planilla = self.id_planilla
        self.guia.fecha_visita = datetime.datetime.now()

        self.guia.save()

        super(Planilla,  self).save(*args, **kwargs)

class Recepcion(models.Model):

    motivo = models.ForeignKey(
        Motivo,
        on_delete=models.CASCADE
    )

    guia = models.ForeignKey(
        Fisico,
        on_delete=models.CASCADE,
        related_name = 'recepcion_guia',
        related_query_name="recepcion",
    )

    fecha = models.DateField(
        auto_now=True,
        verbose_name = 'Fecha recepcion'
    )

    estado = models.ForeignKey(
        Estado,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
        default = 3
    )

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        blank=True, null=True,
        editable=True,
        verbose_name= 'Usuario Gestion',
    )

    history = HistoricalRecords()

    class Meta:
        verbose_name = "Recepcion"
        verbose_name_plural = "Recepciones"
        unique_together = ('guia', 'fecha')

    def __str__(self):
        return str(self.id)

    contador= 0

    @property
    def varu(self):
      return self.motivo.id

    @property
    def motivo_img(self):
      return self.motivo.id

    @property
    def varu(self):
      return self.motivo.id

    @property
    def fecha_re(self):
        return self.fecha

    @property
    def estados(self):
        return self.estado

    def save(self, *args, **kwargs):
        self.guia.fecha_recepciond = self.fecha_re
        self.guia.mot_id = self.varu
        self.guia.id_est = self.estados

        self.guia.est_planilla = self.guia.est_planilla = 2 # estado de planiñlla activo o inactivo para mostrar en filtro nomas
        self.guia.cantidad = self.guia.cantidad + 1

        self.guia.id_est_id = self.guia.id_est_id = 3

        ####################Para contador#######################
        self.cantidad_vi = int(self.varu)
        if int(self.cantidad_vi) >= 16 and int(self.cantidad_vi) > 18:
                self.guia.cantidad_vi = self.contador

        elif int(self.cantidad_vi) > 18:
            self.guia.cantidad_vi = self.contador

        elif int(self.cantidad_vi) < 16:
            self.guia.cantidad_vi = self.contador

        elif self.guia.cantidad_vi <=2:
            self.guia.cantidad_vi +=1
        ##################verificar si es igual a entregado guardar estado_img############

        if self.motivo_img == 21:
            self.guia.estado_img = "ENTREGA_DIGITALIZADA"
        self.guia.save()

        super(Recepcion, self).save(*args, **kwargs)

 # def save(self, *args, **kwargs):
    # contador = 0
        # self.guia.mot = self.var
    # self.guia.id_est = self.estados
        # self.guia.id_est_id = self.guia.id_est_id = 3
        # self.guia.cantidad = self.guia.cantidad + 1
    # # Funcion contador ok copiar codigo para pruebas
        # self.guia.suma = self.guia.suma
        # si self.guia.suma <=2:
        # self.guia.suma +=1 # suma en campo sum en cada momento que se ejecuta el boton de guardar

        # self.guia.save()

        # super(Recep_guia, self).save(*args, **kwargs)

class Sucursales(models.Model):
    sucursal= models.CharField(max_length=70)

    def __str__(self):
        return self.sucursal

class Destino(models.Model):
    sucursal= models.ForeignKey(
        Sucursales,
        on_delete=models.CASCADE,
        related_name= "guia_destino",
        blank=True,
        null=True)

    destino= models.ForeignKey(Sucursales, on_delete=models.CASCADE, related_name='destinos')
    guia = models.ForeignKey(Fisico, on_delete=models.CASCADE, related_name = 'guia_destino')
    origen_destino = models.CharField(max_length=60, blank=True, null=True)
    fecha = models.DateField(
        auto_now_add=True,
        blank=True,
        null=True,
        verbose_name= 'Fecha Destino'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        blank=True, null=True,
        editable=True,
        verbose_name= 'Usuario'
    )

    history = HistoricalRecords()

    def __str__(self):
        return str(self.sucursal)

    @property
    def origen(self):
        return str(self.user.ciudad.ciudad) + '/' + str(self.destino)

    @property
    def destinoss(self):
        return str(self.destino)

    # @property
    # def origen_dest(self):
    #   return str(self.user)+ '/' +(self.destino.sucursal)
    # print(origen_dest)

    def save(self, *args, **kwargs):
        # self.origen_destino = self.origen_dest
        self.guia.id_est_id = self.guia.id_est_id = 10
        self.guia.origen = self.origen
        print(self.guia.origen)
        self.guia.destino = self.destinoss
        self.guia.estado_destino = self.guia.estado_destino = True

        self.guia.save()

        super (Destino, self).save()

class Descargue(models.Model):
    guia = models.ForeignKey(Fisico, on_delete=models.CASCADE, related_name = 'guia_descargue')
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        blank=True, null=True,
        editable=True,
        verbose_name= 'Usuario'
    )
    fecha = models.DateField(
        auto_now_add=True,
        blank=True,
        null=True,
        verbose_name= 'Descargue'
    )

    history = HistoricalRecords()

    def __str__(self):
        return str(self.guia)

    @property
    def usuario(self):
        return self.user

    @property
    def fecha_re(self):
        return self.fecha

    def save(self, *args, **kwargs):
        (self.guia.id_est_id) = self.guia.id_est_id = 3
        print(self.guia.id_est.id)

        self.guia.users = self.usuario
        self.guia.estado_destino = self.guia.estado_destino = False

        print(self.guia.users)

        self.guia.save()

        super (Descargue, self).save()


"""This profile provides a single compute node for running `example.py`, which
programmaticaly starts an experiment based on another profile and interacts with
it using the tools in `./powder/`.

See the project README for more information.

"""

import geni.portal as portal
import geni.rspec.pg as rspec

request = portal.context.makeRequestRSpec()
node = request.RawPC('node')
node.disk_image = "urn:publicid:IDN+emulab.net+image+emulab-ops//UBUNTU18-64-STD"
node.addService(rspec.Execute(shell="bash", command="/local/repository/profile-startup.sh"))
portal.context.printRequestRSpec()


class DSU:
    def __init__(self, v):
        self.parent = [i for i in range(v+1)]
        self.size = [1 for i in range(v+1)]

    def findPar(self, node):
        if self.parent[node] == node:
            return node
        self.parent[node] = self.findPar(self.parent[node])
        return self.parent[node]

    def isSameComp(self, node1, node2):
        return self.findPar(node1) == self.findPar(node2)

    def merge(self, node1, node2):
        if self.isSameComp(node1, node2):
            return False
        par1 = self.findPar(node1)
        par2 = self.findPar(node2)

        if self.size[par1] >= self.size[par2]:
            self.size[par1] += self.size[par2]
            self.parent[par2] = self.parent[par1]
        else:
            self.size[par2] += self.size[par1]
            self.parent[par1] = self.parent[par2]
        return True

    def getLargestCompSize(self):
        return max(self.size)

d = DSU(5)
d.merge(1, 2)
d.merge(0, 3)
d.merge(3, 4)
for i in range(5):
    print(d.findPar(i))
print(d.getLargestCompSize())


import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, \
    QWidget, QGridLayout

class App(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.cw = QWidget()
        self.grid = QGridLayout(self.cw)
        self.btn = QPushButton('Botão')
        self.grid.addWidget(self.btn, 0, 0, 1, 1)
        self.btn.clicked.connect(self.acaodobotao)
        self.setCentralWidget(self.cw)

    def acaodobotao(self):
        print('Método usado!')

if __name__ == '__main__':
    qt = QApplication(sys.argv)
    app = App()
    app.show()
    qt.exec_()

CURSO PYTHON UDEMY/Curso Udemy/Mundo 6 (PyQT)/pyqt1.py


#!/usr/bin/env python3
""" moving average """
import numpy as np

def moving_average(data, beta):
    """ calcs weighted moving avg of data set
        data: list of data to calculate from
        beta: weights used for moving avg
        Return: list containing moving avg of data
    """
    m_avg = [0] * len(data)
    last = 0
    for i in range(0, len(data)):
        last = beta * last + (1 - beta) * data[i]
        m_avg[i] = last / (1 - beta**(i + 1))
    return m_avg


import numpy as np
import cv2
import random

selRoi = 0
top_left = [160, 213]
bottom_right = [320, 426]
first_time = 1

# Parameters for lucas kanade optical flow
lk_params = dict(winSize=(15, 15),
                 maxLevel=2,
                 criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

feature_params = dict(maxCorners=200,
                      qualityLevel=0.3,
                      minDistance=7,
                      blockSize=7)

def findDistance(r1, c1, r2, c2):
    d = (r1 - r2) ** 2 + (c1 - c2) ** 2
    d = d ** 0.5
    return d

# main function
cv2.namedWindow('tracker')
import time

cap = cv2.VideoCapture("D:\\DP\\Data\\Preprocess\\motion\\1\\1_sequence.avi")

def is_square(n):
    import math
    return math.sqrt(n).is_integer()

def getOldCorners():
    counter = 1
    while counter < int(cap.get(cv2.CAP_PROP_FRAME_COUNT)):
        _, frame = cap.read()
        # -----Drawing Stuff on the Image
        # cv2.putText(frame, 'Press a to start tracking', (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, color=(60, 100, 75),
        #             thickness=3)
        # cv2.rectangle(frame, (top_left[1], top_left[0]), (bottom_right[1], bottom_right[0]),
        #               color=(100, 255, 100), thickness=4)

        print("Frame ", counter)
        counter += 1
        # -----Finding ROI and extracting Corners
        frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # roi = frameGray[top_left[0]:bottom_right[0], top_left[1]:bottom_right[1]]  # selecting roi
        roi = frameGray.copy()
        new_corners = cv2.goodFeaturesToTrack(roi, 150, 0.01, 10)  # find corners

        # -----converting to complete image coordinates (new_corners)

        # new_corners[:, 0, 0] = new_corners[:, 0, 0] + top_left[1]
        # new_corners[:, 0, 1] = new_corners[:, 0, 1] + top_left[0]

        # -----drawing the corners in the original image
        for corner in new_corners:
            cv2.circle(frame, (int(corner[0][0]), int(corner[0][1])), 5, (0, 255, 0))

        # -----old_corners and oldFrame is updated
        oldFrameGray = frameGray.copy()
        old_corners = new_corners.copy()

        cv2.imshow('tracker', frame)

        a = cv2.waitKey(5)
        time.sleep(0.125)
        if counter == int(cap.get(cv2.CAP_PROP_FRAME_COUNT)):
            cv2.destroyAllWindows()
            cap.release()
            return oldFrameGray, old_corners

def is_in_segment(feature, segment):
    if (segment["startX"] < feature[0][1] < segment["startX"] + segment["X"] and
            segment["startY"] < feature[0][0] < segment["startY"] + segment["Y"]):
        return True
    return False

def trackSegmentMotion(old_image, new_image, parts = 16):
    """Images have to be grayscale"""
    import math
    old_features = cv2.goodFeaturesToTrack(old_image, mask=None, **feature_params)
    new_features, st, err = cv2.calcOpticalFlowPyrLK(old_image, new_image, old_features, None, **lk_params)

    if not is_square(parts):
        print("Parts are not a square number")
        return

    block_width = new_image.shape[1] / 4
    block_height = new_image.shape[0] / 4
    startX = 1
    startY = 1

    for i in range(1, parts + 1, 1):
        startX = i % math.sqrt(parts)

        if startX == 0:
            startX = 1
            startY += 1

        segment = {
            "startX": startX,  # height
            "startY": startY,  # width
            "X": block_width,
            "Y": block_height
        }

        if not is_in_segment(new_features, segment):
            continue
        # TODO: continue here?
        r_add, c_add = 0, 0
        for corner in new_features:

            r_add = r_add + corner[0][1]
            c_add = c_add + corner[0][0]
        centroid_row = int(1.0 * r_add / len(new_features))
        centroid_col = int(1.0 * c_add / len(new_features))
        # draw centroid
        cv2.circle(new_image, (int(centroid_col), int(centroid_row)), 5, (255, 0, 0))
        # add only those corners to new_corners_updated which are at a distance of 30 or less
        new_corners_updated = new_features.copy()
        tobedel = []
        for index in range(len(new_features)):
            if findDistance(new_features[index][0][1], new_features[index][0][0], int(centroid_row),
                            int(centroid_col)) > 90:
                tobedel.append(index)
        new_corners_updated = np.delete(new_corners_updated, tobedel, 0)

        # drawing the new points
        for corner in new_corners_updated:
            cv2.circle(new_image, (int(corner[0][0]), int(corner[0][1])), 5, (0, 255, 0))
        if len(new_corners_updated) < 10:
            print('OBJECT LOST, Reinitialize for tracking')
            break
        # finding the min enclosing circle
        ctr, rad = cv2.minEnclosingCircle(new_corners_updated)

        cv2.circle(new_image, (int(ctr[0]), int(ctr[1])), int(rad), (0, 0, 255), thickness=5)

def trackMotion():
    cap = cv2.VideoCapture("D:\\DP\\Data\\Preprocess\\motion\\1\\1_sequence.avi")

    # oldFrameGray, old_corners = getOldCorners()

    counter = 1
    while counter < int(cap.get(cv2.CAP_PROP_FRAME_COUNT)):
        'Now we have oldFrame,we can get new_frame,we have old corners and we can get new corners and update accordingly'
        print("Second cycle frame ", counter)

        # read new frame and cvt to gray
        ret, frame = cap.read()

        frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        if counter == 1:
            oldFrameGray = frameGray.copy()
            old_corners = cv2.goodFeaturesToTrack(frameGray, 100, 0.01, 10)

        counter += 1
        # finding the new tracked points
        new_corners, st, err = cv2.calcOpticalFlowPyrLK(oldFrameGray, frameGray, old_corners, None, **lk_params)

        # ---pruning far away points:
        # first finding centroid
        r_add, c_add = 0, 0
        for corner in new_corners:
            r_add = r_add + corner[0][1]
            c_add = c_add + corner[0][0]
        centroid_row = int(1.0 * r_add / len(new_corners))
        centroid_col = int(1.0 * c_add / len(new_corners))
        # draw centroid
        cv2.circle(frame, (int(centroid_col), int(centroid_row)), 5, (255, 0, 0))
        # add only those corners to new_corners_updated which are at a distance of 30 or less
        new_corners_updated = new_corners.copy()
        tobedel = []
        for index in range(len(new_corners)):
            if findDistance(new_corners[index][0][1], new_corners[index][0][0], int(centroid_row),
                            int(centroid_col)) > 90:
                tobedel.append(index)
        new_corners_updated = np.delete(new_corners_updated, tobedel, 0)

        # drawing the new points
        for corner in new_corners_updated:
            cv2.circle(frame, (int(corner[0][0]), int(corner[0][1])), 5, (0, 255, 0))
        if len(new_corners_updated) < 10:
            print('OBJECT LOST, Reinitialize for tracking')
            break
        # finding the min enclosing circle
        ctr, rad = cv2.minEnclosingCircle(new_corners_updated)

        cv2.circle(frame, (int(ctr[0]), int(ctr[1])), int(rad), (0, 0, 255), thickness=5)

        # updating old_corners and oldFrameGray
        oldFrameGray = frameGray.copy()
        old_corners = new_corners_updated.copy()

        # showing stuff on video
        cv2.putText(frame, 'Tracking Integrity : Excellent %04.3f' % random.random(), (20, 50),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, color=(200, 50, 75), thickness=3)
        cv2.imshow('tracker', frame)

        a = cv2.waitKey(5)
        time.sleep(0.125)
        if a == 27:
            cv2.destroyAllWindows()
            cap.release()
        elif a == 97:
            break
    cv2.destroyAllWindows()
    cap.release()

trackMotion()
print("Finished, waiting for key input.")
cv2.waitKey(0)
cv2.destroyAllWindows()


class Graphic_Cards:
    def __init__(self, ModelName, Memory, FanType, Overclock):
        self.model_name = ModelName
        self.memory = str(Memory)
        self.fan_type = FanType
        self.overclockable = Overclock

    def graphic_card(self):   # here the graphic_card is object instance within the class.
        print(
            "Model Name: " + self.model_name + "  " + "Memory: " + self.memory + "GB " + "  " + "Fan Style: " +
            self.fan_type + ", Do you want to OC? : " + " " +
            self.overclockable
         )

g1 = Graphic_Cards("GTX 1080", 8, "Blower", input("Do you want to OC?"))    #g1 is the first object
g2 = Graphic_Cards("R9 270X", 8, "Open Air", input("Do you want to OC?"))   #g2 is the second onbject

g1.graphic_card()
g2.graphic_card()


from typing import List

class Solution:
    def minimalKSum(self, nums: List[int], k: int) -> int:
        plus_num = 1
        cnt = 0
        answer = 0
        numset = set(nums)

        while True:
            if cnt == k:
                return answer
            if plus_num in numset:
                plus_num += 1
                continue
            else:
                answer += plus_num
                cnt += 1
                plus_num += 1

a= Solution()
print(a.minimalKSum([1],100000000))


from math import inf
def solution():
    dp=[-1] * (k+1)
    dp[0]=0

    if k < min(money_types):
        print(-1)
        exit(0)

    for i in range(1,k+1):
        temp=inf
        for money_type in money_types:
            prev_step=i-money_type
            if prev_step>=0:
                temp=min(temp,dp[prev_step])
        dp[i]=temp+1
    if dp[i]==inf:
      print(-1)
    else:
      print(dp[k])

if __name__ =="__main__":
  n,k=0,0
  money_types=[]
  with open("input2294.txt","r") as file:
    n,k=map(int,file.readline().split())
    for _ in range(n):
      money_types.append(int(file.readline().strip()))
  solution()


from composer.core.types import Dataset, DataLoader
from composer.datasets.dataloader import DataLoaderHparams
import dataclasses
from lth_diet.data.data import DataHparams
from lth_diet.utils import utils
import os
from torch.utils.data import Sampler
import torchvision
from torchvision import transforms

CINIC10_MEAN, CINIC10_STD = [0.4789, 0.4723, 0.4305], [0.2421, 0.2383, 0.2587]

@dataclasses.dataclass
class CINIC10DataHparams(DataHparams):
    @property
    def name(self) -> str:
        return utils.get_hparams_name(self, prefix="CINIC10", ignore_fields=["data_dir"])

    def get_dataset(self, data_dir: str, no_augment: bool) -> Dataset:
        data_dir = os.path.join(data_dir, "cinic10")
        if self.train and not no_augment:  # augment if training data and no_augment is False
            transform = transforms.Compose(
                [
                    transforms.RandomCrop(size=32, padding=4),
                    transforms.RandomHorizontalFlip(),
                    transforms.ToTensor(),
                    transforms.Normalize(CINIC10_MEAN, CINIC10_STD),
                ]
            )
        else:  # no augmentation if test data or no_augment is True
            transform = transforms.Compose(
                [
                    transforms.ToTensor(),
                    transforms.Normalize(CINIC10_MEAN, CINIC10_STD),
                ]
            )
        # Only checks if self.train is True
        if self.train:
            dataset = torchvision.datasets.ImageFolder(data_dir + '/train', transform=transform)
        else:
            dataset = torchvision.datasets.ImageFolder(data_dir + '/test', transform=transform)
        return dataset

    def get_data(
        self,
        dataset: Dataset,
        batch_size: int,
        sampler: Sampler,
        drop_last: bool,
        dataloader_hparams: DataLoaderHparams,
    ) -> DataLoader:
        data = dataloader_hparams.initialize_object(
            dataset, batch_size=batch_size, sampler=sampler, drop_last=drop_last
        )
        return data


from click import echo
from fabric import Connection

def init(ctx, cfg=None):
    if not cfg:
        raise ValueError("No config set, provide a config file.")

    host = cfg.get("host")
    user = cfg.get("user")
    echo(f"Connecting to {user} @ {host}")
    conn = Connection(host, user=user)

    conn.sudo("apt-get -y update")
    conn.sudo("apt-get -y upgrade")


import DBconnect

class LoginController:

    @staticmethod
    def login(username_input, password_input):
        login_result = list()
        q = "'"
        query_string = "SELECT * FROM littlebirds.manager where UserID like " + q + str(username_input) + q + \
                       "AND Password like " + q + str(password_input) + q
        result1 = DBconnect.DBconnect.tuple_to_list(query_string)

        if len(result1) == 0:
            login_result.append(-1)
            login_result.append("")
            return login_result

        else:
            query_string = "Update littlebirds.manager SET Status = 1 where UserID like " + q + str(username_input) + q
            result2 = DBconnect.DBconnect.tuple_to_list(query_string)
            if result2 is None:
                login_result.append(-1)
                login_result.append("")
                return login_result
            else:
                login_result.append(1)
                login_result.append((result1[0])[0])
                return login_result

    @staticmethod
    def logout(username_input):
        q = "'"
        query_string = "Update littlebirds.manager SET Status = 0 where UserID like " + q + str(username_input) + q
        result = DBconnect.DBconnect.tuple_to_list(query_string)
        if result is None:
            return -1
        else:
            return 1

    @staticmethod
    def isLoggedIn(username_input):
        q = "'"
        query_string = "SELECT Status FROM littlebirds.manager where UserID like " + q + str(username_input) + q
        result = DBconnect.DBconnect.tuple_to_list(query_string)
        if len(result) == 0:
            return -1
        else:
            return 1

Final Project LittleBirds/LittleBirds/source code/LoginController.py


from .prio import Prio
from .risk import Risk
from lexer.pattern_store import PatternStore
from .positive_expected import expected

class Risk_List:
    def __init__ (self):
        self.positiveList: list = []
        self.negativeList: list = []

    def load (self, patternStore, path):
        for i in patternStore.negatives:
            i.setPath(path)
        for i in patternStore.positives:
            i.setPath(path)

        self.negativeList.extend(patternStore.negatives)
        self.positiveList.extend(patternStore.positives)

    def merge (self, toMerge):
        self.positiveList = [ *self.positiveList, *toMerge.positiveList]
        self.negativeList = [ *self.negativeList,  *toMerge.negativeList]

    def negativeToString (self, verbose: bool = False, graphical: bool = False):
        n = []
        for item in self.negativeList:
            n.append(item.toString(verbose, graphical))
        print(n)
        return n

    def positiveToString (self, verbose: bool = False, graphical: bool = False):
        p = []
        for item in expected:
            if not item in self.positiveList:
                p.append(item.toString(verbose, graphical))
        return p


"""
Write a function that accepts a string with some number of consecutive repeating
characters and returns a copy of the string with consecutive repeating characters
replaced by a count of the repetitions.

 "sssssTTTTTTops" ? "s5T6ops"
"""

def compress_string(string):
    """
    :param string:
    :return:
    """
    result = string[:1]
    count = 1

    for index in range(len(string) - 1):
        if string[index] == string[index + 1]:
            count += 1
        else:
            if count > 1:
                result += str(count)
            result += string[index + 1]
            count = 1

    if count > 1:
        result += str(count)

    return result

def compress_string_with_dict(str):
    """
    different solution.
    """
    count_keeper = {}

    for char in str:
        if char in count_keeper:
            count_keeper[char] += 1
        else:
            count_keeper[char] = 1

    result = ''

    for key in count_keeper:
        if count_keeper[key] == 1:
            result = f"{result}{key}"
        else:
            result = f"{result}{key}{count_keeper[key]}"

    if len(result) > len(str):
        return str
    return result

assert compress_string('aaa') == 'a3'
assert compress_string('aaaabc') == 'a4b1c1'

assert compress_string('abc') == 'abc'


from .common_imports import *

class Github(object):
    @staticmethod
    def official_endpoint(env):
        env.attr.github.endpoint = 'api.github.com'

    @staticmethod
    def base_header(env):
        env.github.request.headers = {'Accept': 'application/vnd.github.v3+json'}

    @staticmethod
    def make_request(env, url, last_result=None):
        if last_result is not None and int(last_result.headers['X-RateLimit-Remaining']) <= 1:
            time_wait = float(last_result.headers['X-RateLimit-Reset']) - time.time() + 2.0
            if time_wait < 0:
                time.sleep( 120.0 )
            else:
                time.sleep( time_wait )
        return requests.get(url, headers=env.github.request.headers)

    @staticmethod
    def list_pull_requests(env):
        url = f'https://{env.attr.github.endpoint}/repos/{env.attr.github.owner}/{env.attr.github.repo}/pulls'
        return Github.make_request(env, url)

    @staticmethod
    def get_pull_request(env):
        url = f'https://{env.attr.github.endpoint}/repos/{env.attr.github.owner}/{env.attr.github.repo}/pulls/{env.attr.github.number}'
        return Github.make_request(env, url)

    @staticmethod
    def search_topic_default_params():
        return {"per_page":100, "sort":"stars"}

    @staticmethod
    def generate_topic_pages(env, total_counts, per_page=100):
        for i in range(1, 11):
            yield i
            if (i * per_page) > total_counts:
                break

    @staticmethod
    def search_topic(self, env, **kwargs):
        q = {'q': f"{kwargs['q']}+in:topics"}
        q.update(kwargs)
        qs = urllib.parse.urlencode(q)
        url = urllib.parse.quote(f"https://{env.attr.github.endpoint}/search/repositories?{qs}")
        return Github.make_request(env, url)

    @staticmethod
    def parse_datetime(s):
        return datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").timestamp()

    @staticmethod
    def list_all_commits(env, existing_commits=None):
        newest_commit = None
        oldest_commit = None
        have_newest = False
        have_oldest = False
        commits = {}

        url_prefix = f'https://{env.attr.github.endpoint}/repos/{env.attr.github.owner}/{env.attr.github.repo}'

        def add_commits(new_commits):
            nonlocal newest_commit
            nonlocal oldest_commit
            for commit in new_commits:
                commits[ commit["sha"] ] = commit
                commit[ "time" ] = Github.parse_datetime( commit["commit"]["committer"]["date"] )

                if newest_commit is None:
                    newest_commit = oldest_commit = commit

                if commit[ "time" ] > newest_commit["time"]:
                    newest_commit = commit
                if commit[ "time" ] < oldest_commit["time"]:
                    oldest_commit = commit

        if existing_commits is None:
            existing_commits = {}

        if len(existing_commits) == 0:
            url = f'{url_prefix}/commits?per_page=100'
            more_commits = Github.make_request(env, url)
            if len(more_commits) == 0:
                raise Exception("no results on fresh listing")
            add_commits(more_commits)
        else:
            add_commits(existing_commits.values())

        while not have_newest or not have_oldest:
            if not have_newest:
                url = f'{url_prefix}/commits?per_page=100&since={newest_commit["commit"]["committer"]["date"]}'
                more_commits = Github.make_request(env, url)
                if len(more_commits) == 1:
                    if more_commits[0]["sha"] == newest_commit["sha"]:
                        have_newest = True
                elif len(more_commits) == 0:
                    have_newest = True
                add_commits(more_commits)
            if not have_oldest:
                url = f'{url_prefix}/commits?per_page=100&until={oldest_commit["commit"]["committer"]["date"]}'
                more_commits = Github.make_request(env, url)
                if len(more_commits) == 1:
                    if more_commits[0]["sha"] == oldest_commit["sha"]:
                        have_oldest = True
                elif len(more_commits) == 0:
                    have_oldest = True
                add_commits(more_commits)
            time.sleep(1.0)
        return commits

    @staticmethod
    def pull_request_buildable(env):
        env.attr.scheduler.event_name = f'{env.attr.pull.id}.build'
        pull_info = env.attr.pull.info
        build_result = Scheduler.get_result(env)

        if build_result is None or 'recent_build_sha' not in build_result:
            build = True
        elif build_result['recent_build_sha'] != pull_info['merge_commit_sha']:
            build = True
        else:
            build = False

        return build


import unicurses as uni

WIDTH = 30
HEIGHT = 10
startx = 0
starty = 0

choices = ["Choice 1", "Choice 2", "Choice 3", "Choice 4", "Exit"]
n_choices = len(choices)

choice = 0
c = 0

def print_menu(menu_win, highlight):
    x = 2
    y = 2
    uni.box(menu_win, 0, 0)
    for i in range(0, n_choices):
        if (highlight == i + 1):
            uni.wattron(menu_win, uni.A_REVERSE)
            uni.mvwaddstr(menu_win, y, x, choices[i])
            uni.wattroff(menu_win, uni.A_REVERSE)
        else:
            uni.mvwaddstr(menu_win, y, x, choices[i])
        y += 1
    uni.wrefresh(menu_win)

def report_choice(mouse_x, mouse_y):
    i = startx + 2
    j = starty + 3
    for choice in range(0, n_choices):
        if (mouse_y == j + choice) and (mouse_x >= i) and (mouse_x <= i + len(choices[choice])):
            if choice == n_choices - 1:
                return -1
            else:
                return choice + 1
            break

stdscr = uni.initscr()
uni.clear()
uni.noecho()
uni.cbreak()
uni.curs_set(0)
startx = int((80 - WIDTH) / 2)
starty = int((24 - HEIGHT) / 2)

menu_win = uni.newwin(HEIGHT, WIDTH, starty, startx)
uni.keypad(menu_win, True)
uni.mvaddstr(0, 0, "Click on Exit to quit (works best in a virtual console)")
uni.refresh()
print_menu(menu_win, 1)
uni.mouseinterval(0)
uni.mousemask(uni.ALL_MOUSE_EVENTS)

msg = "MOUSE: {0}, {1}, {2}, Choice made is: {3}, Chosen string is: {4}"
while True:
    c = uni.wgetch(menu_win)
    if c == uni.KEY_MOUSE:
        id, x, y, z, bstate = uni.getmouse()
        if bstate & uni.BUTTON1_PRESSED:
            chosen = report_choice(x + 1, y + 1)
            if chosen is not None:
                uni.mvaddstr(23, 0, msg.format(
                    x, y, bstate, chosen, choices[chosen-1]))
                uni.mvaddstr(23, 0, msg.format(
                    x, y, bstate, chosen, choices[chosen-1]))
            uni.clrtoeol()
            uni.refresh()
            if (chosen == -1):
                uni.endwin()
                exit(1)
            print_menu(menu_win, chosen)

uni.endwin()


class Player:
    VERSION = "1.0"

    def get_round_status(self, community_cards):
        round_status_dict = {
            0: 'preflop',
            3: 'flop',
            4: 'turn',
            5: 'river'
        }

        return round_status_dict[len(community_cards)]

    def is_higher_than(self, card, rank):
        ranks = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A')
        rank_dict = {}
        i = 1
        for rank_ in ranks:
            rank_dict[rank_] = i
            i += 1
        return rank_dict[card['rank']] > rank_dict[rank]

    def is_hand_relatively_good(self, card1, card2):
        return self.is_higher_than(card1, '8') and self.is_higher_than(card2, '8')

    def betRequest(self, game_state):
        player_index = game_state['in_action']
        players = game_state['players']
        player_count = len(players)
        active_players = [plyr for plyr in players if plyr['status'] == 'active']
        player = players[player_index]
        card1, card2 = player['hole_cards']

        community_cards = game_state['community_cards']
        min_raise = game_state['minimum_raise']

        current_buy_in = game_state['current_buy_in']
        our_bet = players[player_index]['bet']

        CALL = current_buy_in - our_bet
        MIN_RAISE = current_buy_in - our_bet + min_raise
        round_status = self.get_round_status(community_cards)
        same_suits_nr = self.check_suit(card1, card2, community_cards)

        high_cards = card1['rank'] in ('J', 'K', 'Q', 'A') and card2['rank'] in ('J', 'K', 'Q', 'A')

        pair_in_hand = card1['rank'] == card2['rank']
        match_count = 1 if pair_in_hand else 0
        for card in community_cards:
            if card['rank'] in (card1['rank'], card2['rank']):
                match_count += 1

        if round_status == 'preflop':
            for plyr in active_players:
                if plyr['name'] == 'Incognito' and plyr['bet'] > MIN_RAISE:
                    if match_count and card1['rank'] in ('K', 'A'):
                        return CALL
                    else:
                        return 0
            if match_count and card1['rank'] == 'A':
                return player['stack']
            elif all(player_['id'] < player_index for player_ in players if player_['status'] == 'active') and CALL == 0:
                return MIN_RAISE
            elif high_cards:
                return CALL
            elif match_count and self.is_higher_than(card1, '8'):  # if cards are high or high pair
                return MIN_RAISE
            elif self.is_hand_relatively_good(card1, card2) or match_count:
                return CALL
            else:
                return 0

        if round_status == 'river' and match_count == 1:
            return 0

        else:
            if game_state['dealer'] == player_index and CALL == 0:
                return MIN_RAISE
            elif all(player_['id'] < player_index for player_ in players if player_['status'] == 'active') and CALL == 0:
                return MIN_RAISE
            elif same_suits_nr == 5:
                return player['stack']
            elif match_count > 1:
                return MIN_RAISE
            elif match_count == 1:
                return CALL
            elif same_suits_nr == 4 and round_status != 'river':
                return CALL
            elif self.check_if_straight(community_cards, card1, card2):
                return MIN_RAISE * 2
            return 0

    def check_suit(self, card1, card2, community_cards):
        same_suite = card1['suit'] if card1['suit'] == card2['suit'] else None

        same_suite_nr = 2 if same_suite else 0

        for card in community_cards:
            if card['suit'] == same_suite:
                same_suite_nr += 1

        return same_suite_nr

    # if "get_round_status" > 0
    def check_if_straight(self, community_cards, card1, card2):
        card_rank_letters_to_numbers = {'J': '11', 'Q': '12', 'K': '13', 'A': '14'}

        # if card['rank'] is a letter, then convert it to number
        card1 = (card_rank_letters_to_numbers[card1['rank']]
                 if card1['rank'] in card_rank_letters_to_numbers
                 else card1['rank'])

        card2 = (card_rank_letters_to_numbers[card2['rank']]
                 if card2['rank'] in card_rank_letters_to_numbers
                 else card2['rank'])
        # add your hand into a card rank list
        cards_rank_list = [int(card1), int(card2)]
        straight = 0

        for card in community_cards:
            # if card['rank'] is a letter, then convert it to number
            card['rank'] = (card_rank_letters_to_numbers[card['rank']]
                            if card['rank'] in card_rank_letters_to_numbers
                            else card['rank'])
            cards_rank_list.append(int(card['rank']))

        cards_rank_list.sort()

        for index, card_rank in enumerate(cards_rank_list):
            if (index + 1) <= len(cards_rank_list) and (cards_rank_list[index + 1] - card_rank) == 1:
                straight += 1
                #if straight is 4 then we have a minimum straight of ranks
                #(because minimum 5 cards is the requirement for the straight)
                if straight == 4:
                    return True
            else:
                return False

    def showdown(self, game_state):
        pass


# k : 최상품 사과 등급, m : 사과 갯수, score : 사과들의 점수
def solution(k, m, score):
    score = sorted(score, reverse = True) # 높은 사과 등급이 앞으로 올 수 있도록 sorted로 정렬 후 reverse를 사용해 내림차순 정렬을 한다.

    result = [score[i:i + m] for i in range(0, len(score), m)] # result는 m개씩 담은 list를 반환한다.

    answer = []

    for i in result:
        if len(i) == m: # 박스에 사과가 다 채워졌을 때
            answer.append(min(i) * m) # 문제에 쓰인 공식 응용

    return sum(answer)

k = 3
m = 4
score = [1, 2, 3, 1, 2, 3, 1]
print(solution(k, m, score))