from flask import render_template, flash, redirect, g, Blueprint
from app import db
from models import UserGear
from forms import NewUserGearForm
from helpers import validate_signed_in, validate_correct_user

bp = Blueprint('gearshed', __name__, url_prefix='/gearshed')

@bp.route('/')
def show_user_gear():
    if not validate_signed_in("You must be logged in to view your Gear Shed!"):
        return redirect("/login")
    gear = UserGear.query.all()
    return render_template("/gear/gear_shed.html", user = g.user, gear = gear, num_photos_displayed=4, allow_user_gear_upload = True)

@bp.route('/<int:gear_id>/delete', methods=['POST'])
def delete_gear(gear_id):
    '''Delete a piece of gear from the database'''
    if not validate_signed_in("You must be logged in to delete gear"):
        return redirect("/login")

    gear = UserGear.query.get_or_404(gear_id)
    if not validate_correct_user("You can only delete gear from your own gearshed.",gear.user_id):
        return redirect("/gearshed")

    db.session.delete(gear)
    db.session.commit()
    return redirect(f"/gearshed")

@bp.route('/new', methods=['GET', 'POST'])
def create_user_gear():
    '''Show a form to create a new piece of gear and handle its submission'''
    if not validate_signed_in("You must be logged in to create gear for your Gear Shed."):
        return redirect("/login")

    form = NewUserGearForm()
    if form.validate_on_submit():
        name = form.name.data
        model = form.model.data
        brand = form.brand.data
        weight = form.weight.data
        time_used = form.time_used.data
        try:
            UserGear.create_gear(name, brand, model, weight, time_used, g.user.id)
            flash("Gear added successfully", 'success')
            return redirect("/gearshed")
        except Exception as e:
            flash("An error occurred, please try again", 'error')
            flash(f"{e}")
            return redirect("/gearshed/new")

    return render_template("gear/new_gear_item.html", form=form)


from torch.utils.data import Dataset
import numpy as np
import cv2
from torchvision import transforms
import os
import sys

BASE_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_PATH)

import DataSets.Utils.Transforms
import DataSets.Utils.Config as cfg

class JointsDataset(Dataset):
    """
        1st Level of dataset hirarchy implemented in this project
        Defines interface and contains generic pre-processing methods
        that are used by multiple child classes
    """

    def __init__(self, mode, numJoints):
        # Preprocessing constants
        self.mode = mode
        self.imageSize = cfg.generic["imageSize"]
        self.numJoints = numJoints
        self.db = []

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

    def _get_db(self):
        pass

    def __getitem__(self, idx):
        pass

    def visualiseSample(self, sample):
        pass

    def jointsToMPIIFormat(self, jointArray):
        MPIIFormat = []
        for i in range(len(self.MPIIMapping)):
            MPIIFormat.append(jointArray[self.MPIIMapping[i]])
        return np.array(MPIIFormat)

    def getBboxCentreAndScaleFrom2DJointPos(self, jointPos2D, imageSize):
        # Switch image size x and y
        imageSize = np.array(imageSize)
        imageSize[0], imageSize[1] = imageSize[1], imageSize[0]

        # Fill values do not bound subject so are removed
        jointsNoFillValues = jointPos2D[
            (jointPos2D[:, 0] != -1) & (jointPos2D[:, 1] != -1)
        ]

        # Min and max joint coordinates in each dimension
        # Padding added as terminal keypoints not always
        # at end of subject e.g. wrist keypoint
        padding = 100
        x1 = np.min(jointsNoFillValues[:, 0]) - padding
        y1 = np.min(jointsNoFillValues[:, 1]) - padding
        x2 = np.max(jointsNoFillValues[:, 0]) + padding
        y2 = np.max(jointsNoFillValues[:, 1]) + padding

        # Bbox is contrained to image dimensions
        bbox = np.array([x1, y1, x2, y2])
        bbox = np.clip(bbox, 0, np.concatenate((imageSize, imageSize)))

        bboxDimensions = bbox[2:] - bbox[:2]
        scale = max(bboxDimensions) / 200  # scale in relation to 200px
        centre = (bbox[2:] + bbox[:2]) / 2

        return centre, scale

    def preProcessImage(self, image, center, scale):
        # Get rotation angle (random if training 0 otherwise)
        orgImageWidth = -1
        if self.mode == "train":
            (
                image,
                center,
                rotation,
                orgImageWidth,
            ) = JointsDataset.randomRotationAndFlip(image, center, orgImageWidth)
        else:
            rotation = 0

        # Transform image
        trans = DataSets.Utils.Transforms.get_affine_transform(
            center, scale, rotation, self.imageSize
        )
        image = cv2.warpAffine(
            image, trans, (self.imageSize, self.imageSize), flags=cv2.INTER_LINEAR
        )
        image = transforms.ToTensor()(image)

        return image, trans, orgImageWidth

    def randomRotationAndFlip(image, center, orgImageWidth, rotation_factor=45):
        # rf = rotation_factor
        rotation = 0  # (
        #     np.clip(np.random.randn() * rf, -rf * 2, rf * 2)
        #     if random.random() <= 0.5
        #     else 0
        # )
        # if random.random() <= -1:
        #     image = image[:, ::-1, :]
        #     orgImageWidth = np.shape(image)[1]
        #     center[0] = np.shape(image)[1] - center[0] - 1
        return image, center, rotation, orgImageWidth

    def preProcessPixelLocations(anno, trans, orgImageWidth):
        # If image has been flipped orgImageWidth is supplied so joints cant be flipped also
        if orgImageWidth > -1:
            anno[:, 0] = orgImageWidth - anno[:, 0]

        # Transform joint position inaccordance to image transform
        for i in range(len(anno)):
            anno[i, 0:2] = DataSets.Utils.Transforms.affine_transform(anno[i, 0:2], trans)
        return anno


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('history', '0002_tag'),
    ]

    operations = [
        migrations.CreateModel(
            name='Season',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('gamename', models.CharField(max_length=200)),
                ('start_on', models.DateTimeField(verbose_name='start_on')),
                ('end_on', models.DateTimeField(null=True, verbose_name='end_on')),
                ('active', models.BooleanField(default=True)),
            ],
        ),
    ]


import dns.resolver

from spiderfoot import SpiderFootEvent, SpiderFootPlugin

class sfp_cleanbrowsing(SpiderFootPlugin):

    meta = {
        'name': "CleanBrowsing.org",
        'summary': "Check if a host would be blocked by CleanBrowsing.org DNS",
        'flags': [""],
        'useCases': ["Investigate", "Passive"],
        'categories': ["Reputation Systems"],
        'dataSource': {
            'website': "https://cleanbrowsing.org/",
            'model': "FREE_NOAUTH_UNLIMITED",
            'references': [
                "https://cleanbrowsing.org/guides/",
                "https://cleanbrowsing.org/how-it-works",
                "https://cleanbrowsing.org/web-filtering-for-shools-and-cipa-compliance",
                "https://cleanbrowsing.org/getting-started"
            ],
            'favIcon': "https://cleanbrowsing.org/favicon-new.ico",
            'logo': "https://cleanbrowsing.org/images/logos/CleanBrowsing-logo-large-2019-Orange-II.png",
            'description': "You get to decide what type of content is allowed in your home or network via our "
            "DNS-based content filtering service. Parents can protect their kids from adult content, "
            "schools can be CIPA compliant and businesses can block malicious domains and "
            "gain visibility into their network.\n"
            "CleanBrowsing is a DNS-based content filtering service that offers a safe way to browse the web without surprises. "
            "It intercepts domain requests and filter sites that should be blocked, based on your requirements. "
            "Our free family filter, for example, blocks adult content, while still allowing Google, "
            "Youtube, Bing, DuckDuckGo and the rest of the web to load safely.",
        }
    }

    opts = {
    }

    optdescs = {
    }

    results = None

    def setup(self, sfc, userOpts=dict()):
        self.sf = sfc
        self.results = self.tempStorage()

        for opt in list(userOpts.keys()):
            self.opts[opt] = userOpts[opt]

    def watchedEvents(self):
        return [
            "INTERNET_NAME",
            "AFFILIATE_INTERNET_NAME",
            "CO_HOSTED_SITE"
        ]

    def producedEvents(self):
        return [
            "MALICIOUS_INTERNET_NAME",
            "MALICIOUS_AFFILIATE_INTERNET_NAME",
            "MALICIOUS_COHOST"
        ]

    def queryAddr(self, qaddr):
        res = dns.resolver.Resolver()
        res.nameservers = ["185.228.168.168", "185.228.168.169"]

        try:
            addrs = res.resolve(qaddr)
            self.sf.debug(f"Addresses returned: {addrs}")
        except Exception:
            self.sf.debug(f"Unable to resolve {qaddr}")
            return False

        if addrs:
            return True
        return False

    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data
        parentEvent = event

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if eventData in self.results:
            return

        self.results[eventData] = True

        # Check that it resolves first, as it becomes a valid
        # malicious host only if NOT resolved by CleanBrowsing.org.
        if not self.sf.resolveHost(eventData):
            return

        found = self.queryAddr(eventData)

        # Host was found, not blocked
        if found:
            return

        typ = "MALICIOUS_" + eventName

        if eventName == "CO_HOSTED_SITE":
            typ = "MALICIOUS_COHOST"

        evt = SpiderFootEvent(
            typ,
            f"Blocked by CleanBrowsing.org [{eventData}]",
            self.__name__,
            parentEvent
        )
        self.notifyListeners(evt)

# End of sfp_cleanbrowsing class


#!/usr/bin/env python3

import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="kafka-e2e-perf-test",
    version="0.0.1",
    maintainer="Jan Hutar",
    maintainer_email="jhutar@redhat.com",
    description="Kafka end-to-end perf test",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/jhutar/kafka-e2e-perf-test",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: GNU General Public License (GPL)",
        "Operating System :: POSIX :: Linux",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Quality Assurance",
    ],
    python_requires='>=3.6',
    install_requires=[
        "kafka-python",
        "python-snappy",
        "opl-rhcloud-perf-team @ git+https://github.com/redhat-performance/opl.git",
    ],
    package_data={
        "kafka_e2e_perf_test": [
        ],
    },
    entry_points={
        "console_scripts": [
            "kafka-e2e-perf-test.py=kafka_e2e_perf_test.e2e:main",
        ],
    },
)


from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from contacts.models import UserGoogleContacts, UserContacts

class UserGoogleContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserGoogleContacts
        fields = '__all__'
        ordering = ('id',)

class UserContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserContacts
        fields = ('id', 'first_name', 'last_name', 'phone', 'email', 'in_app_user')
        ordering = ('id',)
        read_only_fields = ('id', 'in_app_user',)

    def validate(self, data):
        try:
            phone = data.get('phone')
        except:
            phone = None
        try:
            email = data.get('email')
        except:
            email = None
        if not phone and not email:
            raise ValidationError('Please provide phone or email for contact')
        return data

class UserContactRetrieveUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserContacts
        fields = ('id', 'first_name', 'last_name', 'phone', 'email', 'in_app_user')
        ordering = ('id',)
        read_only_fields = ('id', 'in_app_user',)


#!/usr/bin/env python3

import argparse
import sys
import time

parser = argparse.ArgumentParser()
parser.description = "Async process test emulator"
parser.add_argument('-s', '--stdout', action='store_true', help="Write to stdout")
parser.add_argument('-e', '--stderr', action='store_true', help="Write to stderr")
parser.add_argument('-i', '--iterations', default=3, nargs=1, type=int, help='Number of iterations (seconds)')

args = parser.parse_args()

for i in range(0, args.iterations[0]):
    time.sleep(0.3)
    if args.stdout:
        print('[%3d] stdout' % i, file=sys.stdout)
    time.sleep(0.3)
    if args.stderr:
        print('[%3d] stderr' % i, file=sys.stderr)
    time.sleep(0.4)


from datacollection.langclass import *
import random as r
import math as m
import sys

##################
# hyper-parameters
languages = 'nno'.split(' ')
source = 'nno'
proportion = 1

def add_lemmawords(source, pull, nwords):
    '''returns a dictionary of mixed languages, this can get repeated words'''

    possible_dict = [dictionary
                     for dictionary in pull.dictionary
                     if dictionary['lemma'] in dictionary['word']]

    if len(possible_dict) > nwords:
        # currently this can get repeated words
        add_dict = [possible_dict[r.randint(0, len(possible_dict)-1)]
                    for i in range(nwords)]
    else:
        add_dict = possible_dict

    new_dictionary = source.dictionary + add_dict
    r.shuffle(new_dictionary)

    return new_dictionary, len(add_dict)

# get norwegian nynorsk data files
trn_source = File(filetype='trn').get_language(source)
dev_source = File(filetype='dev').get_language(source)
tst_source = File(filetype='tst').get_language(source)

# first lets try adding 25 proportion (of the source language) more data from another language
add_nwords = m.ceil(trn_source.nwords * proportion)

for lang in languages:
    # get full addition languages to merge into training source language
    trn_lang = File(filetype='trn').get_language(lang)
    # merge languages with 10 proportion of nno language
    new_trn_dict, nadded = add_lemmawords(trn_source, trn_lang, add_nwords)

    print('training nwords:', trn_source.nwords,
          '| proportion asked:', proportion, '| words to add:', add_nwords)
    print('actual nwords added:', nadded,
          '| proportion of training:', nadded/trn_source.nwords)

    if nadded != add_nwords:
        proportion = nadded/trn_source.nwords

    # create training langauge from new dictionary
    trn_lang = File(new_trn_dict, 'trn')
    # create new name
    name = f'{source}+{int(proportion*100)}p+{lang}'

    # create language object and change name
    new_lang = Language(trn_lang, tst_source, dev_source)
    new_lang.change_name(name)
    # push language object into files
    print(new_lang)
    new_lang.create()


from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 784])

W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

y_ = tf.placeholder(tf.float32, [None, 10])

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.InteractiveSession()

tf.global_variables_initializer().run()

for _ in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

#************************************************************************************
#************************************************************************************

from sklearn import model_selection
from sklearn import metrics
import tensorflow as tf

# Load dataset.
iris = tf.contrib.learn.datasets.load_dataset('iris')

x_train, x_test, y_train, y_test = model_selection.train_test_split(
  iris.data, iris.target, test_size=0.2, random_state=42)

# Build 3 layer DNN with 10, 20, 10 units respectively.

feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input(
  x_train)

classifier = tf.contrib.learn.DNNClassifier(
  feature_columns=feature_columns, hidden_units=[10, 20, 10], n_classes=3)

# Fit and predict.
classifier.fit(x_train, y_train, steps=200)
predictions = list(classifier.predict(x_test, as_iterable=True))
score = metrics.accuracy_score(y_test, predictions)
print('Accuracy: {0:f}'.format(score))


import io
import os
import re
import shutil
import unittest
from orderedattrdict import AttrDict
from nose.tools import ok_
from . import folder
from gramex import variables
from gramex.install import init, _ensure_remove

class TestInit(unittest.TestCase):
    @classmethod
    def setUp(cls):
        cls.appname = 'test-gramex-init'
        cls.app_dir = os.path.join(folder, cls.appname)
        cls.cwd = os.getcwd()

    def test_init(self):
        if os.path.exists(self.app_dir):
            shutil.rmtree(self.app_dir, onerror=_ensure_remove)
        os.makedirs(self.app_dir)
        os.chdir(self.app_dir)
        init([], AttrDict())

        # Ensure files are present
        source = os.path.join(variables['GRAMEXPATH'], 'apps', 'init')
        for path in os.listdir(source):
            path = path.replace('appname', self.appname.replace('-', '_'))
            ok_(os.path.exists(os.path.join(self.app_dir, path)), path + ' in init')

        # Ensure templates work
        with io.open(os.path.join(self.app_dir, 'gramex.yaml'), encoding='utf-8') as handle:
            line = handle.readline().strip()
            ok_('don\'t delete this line' in line)
            ok_(re.match(r'# Generated by gramex init 1\.\d+', line))

    @classmethod
    def tearDown(cls):
        os.chdir(cls.cwd)
        try:
            shutil.rmtree(cls.app_dir, onerror=_ensure_remove)
        except OSError:
            # Ideally, we should clean up the app_dir
            # But on Windows, npm / git may prevent this for some time. Ignore this
            pass


# -*- coding: utf-8 -*-
"""
Created on Thu Aug  5 11:43:28 2021
@author: Emmanuel Bonnet
"""

import numpy as np
import cv2
import pandas as pd
from skimage.filters import roberts, sobel, scharr, prewitt
from scipy import ndimage as nd

img = cv2.imread('image_688575878_product_57497717.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#### Multiple images can be used for training. For that, you need to concatenate the data
img2 = img.reshape(-1)
df = pd.DataFrame()
df['Original Image'] = img2

#Generate Gabor features
num = 1  #To count numbers up in order to give Gabor features a label in dataframe
kernels = []
for theta in range(2):   #Define number of thetas
    theta = theta / 4. * np.pi
    for sigma in (1, 3):  #Sigma with 1 and 3
        for lamda in np.arange(0, np.pi, np.pi / 4):   #Range of wavelengths
            for gamma in (0.05, 0.5):   #Gamma values of 0.05 and 0.5

                gabor_label = 'Gabor' + str(num)  #Label Gabor columns as Gabor1, Gabor2, etc.
#                print(gabor_label)
                ksize=9
                kernel = cv2.getGaborKernel((ksize, ksize), sigma, theta, lamda, gamma, 0, ktype=cv2.CV_32F)
                kernels.append(kernel)
                #Now filter the image and add values to a new column
                fimg = cv2.filter2D(img2, cv2.CV_8UC3, kernel)
                filtered_img = fimg.reshape(-1)
                df[gabor_label] = filtered_img  #Labels columns as Gabor1, Gabor2, etc.
                print(gabor_label, ': theta=', theta, ': sigma=', sigma, ': lamda=', lamda, ': gamma=', gamma)
                num += 1  #Increment for gabor column label

#OTHER FEATURES
#CANNY EDGE
edges = cv2.Canny(img, 100,200).reshape(-1)
df['Canny'] = edges
#ROBERTS EDGE
edge_roberts = roberts(img).reshape(-1)
df['Roberts'] = edge_roberts
#SOBEL
edge_sobel = sobel(img).reshape(-1)
df['Sobel'] = edge_sobel
#SCHARR
edge_scharr = scharr(img).reshape(-1)
df['Scharr'] = edge_scharr
#PREWITT
edge_prewitt = prewitt(img).reshape(-1)
df['Prewitt'] = edge_prewitt
#GAUSSIAN with sigma=3
gaussian_img = nd.gaussian_filter(img, sigma=3).reshape(-1)
df['Gaussian_sig3'] = gaussian_img
#GAUSSIAN with sigma=6
gaussian_img2 = nd.gaussian_filter(img, sigma=6).reshape(-1)
df['Gaussian_sig6'] = gaussian_img2
#MEDIAN with sigma=3
median_img = nd.median_filter(img, size=3).reshape(-1)
df['Median s3'] = median_img

#Now, add a column in the data frame for the Labels
#For this, we need to import the labeled image
labeled_img = cv2.imread('image_688575878_product_57497717.jpg')
#Remember that you can load an image with partial labels
#But, drop the rows with unlabeled data

labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_BGR2GRAY)
labeled_img1 = labeled_img.reshape(-1)
df['Labels'] = labeled_img1

print(df.head())

#df.to_csv("Gabor.csv")

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

#Define the dependent variable that needs to be predicted (labels)
Y = df["Labels"].values

#Define the independent variables
X = df.drop(labels = ["Labels"], axis=1)

#Split data into train and test to verify accuracy after fitting the model.
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=20)

from sklearn.ensemble import RandomForestClassifier
# Instantiate model with n number of decision trees
model = RandomForestClassifier(n_estimators = 100, random_state = 42)

# Train the model on training data
model.fit(X_train, y_train)

# verify number of trees used. If not defined above.
print('Number of Trees used : ', model.n_estimators)
# TESTING THE MODEL BY PREDICTING ON TEST DATA
prediction_test_train = model.predict(X_train)

#Test prediction on testing data.
prediction_test = model.predict(X_test)
from sklearn import metrics
#First check the accuracy on training data. This will be higher than test data prediction accuracy.
print ("Accuracy on training data = ", metrics.accuracy_score(y_train, prediction_test_train))
#Check accuracy on test dataset. If this is too low compared to train it indicates overfitting on training data.
print ("Accuracy = ", metrics.accuracy_score(y_test, prediction_test))

#Get numerical feature importances
importances = list(model.feature_importances_)

feature_list = list(X.columns)
feature_imp = pd.Series(model.feature_importances_,index=feature_list).sort_values(ascending=False)
print(feature_imp)
import pickle
#Save the trained model as pickle string to disk for future use
filename = "rakuten_im1"
pickle.dump(model, open(filename, 'wb'))

#To test the model on future datasets
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.predict(X)

segmented = result.reshape((img.shape))

from matplotlib import pyplot as plt
plt.imshow(segmented, cmap ='jet')
plt.imsave('rakuten_estim.jpg', segmented, cmap ='jet')


# Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix.

# For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal].

def autoComplete(word, arr):
    returnArr=[]
    for i in range(0,len(arr)):
        temp = arr[i]
        if temp[0:len(word)]==word:
            returnArr.append(arr[i])
    return returnArr

arr = ['dog', 'deer', 'deal']
word='de'

print(autoComplete(word, arr))


INF = 10 ** 9

class Node:
    def __init__(self, x):
        self.key = x
        self.left = None
        self.right = None
        self.h = 1
        self.min = x
        self.max = x
        self.sum = 0

class AVLTree:

    def __init__(self):
        self.head = None

    def insert(self, x):
        if self.head is None:
            self.head = Node(x)
        else:
            self.head = self._insert(self.head, x)

    def _insert(self, v, x):
        if v is None:
            return Node(x)
        elif x < v.key:
            v.left = self._insert(v.left, x)
        elif x > v.key:
            v.right = self._insert(v.right, x)
        return self.balance(v)

    def get_height(self, v):
        if v is None:
            return 0
        return v.h

    def get_sum(self, v):
        if v is None:
            return 0
        return v.sum

    def get_min(self, v):
        if v is None:
            return INF
        return v.min

    def get_max(self, v):
        if v is None:
            return -INF
        return v.max

    def fix_height_sum_min_max(self, v):
        if not (v is None):
            v.h = max(self.get_height(v.left),
                      self.get_height(v.right)) + 1

            v.sum = self.get_sum(v.left) + self.get_sum(v.right)
            if not (v.left is None):
                v.sum += v.left.key
            if not (v.right is None):
                v.sum += v.right.key

            v.min = min(self.get_min(v.left), self.get_min(v.right), v.key)
            v.max = max(self.get_max(v.left), self.get_max(v.right), v.key)

    def small_rotate_right(self, p):
        q = p.left
        p.left = q.right
        q.right = p
        self.fix_height_sum_min_max(p)
        self.fix_height_sum_min_max(q)
        return q

    def small_rotate_left(self, q):
        p = q.right
        q.right = p.left
        p.left = q
        self.fix_height_sum_min_max(q)
        self.fix_height_sum_min_max(p)
        return p

    def get_balance(self, v):
        if not (v is None):
            return self.get_height(v.right) - self.get_height(v.left)

    def balance(self, p):
        self.fix_height_sum_min_max(p)

        if 2 == self.get_balance(p):
            if self.get_balance(p.right) < 0:
                p.right = self.small_rotate_right(p.right)
            return self.small_rotate_left(p)

        if -2 == self.get_balance(p):
            if self.get_balance(p.left) > 0:
                p.left = self.small_rotate_left(p.left)
            return self.small_rotate_right(p)

        return p

    def sum(self, l, r):
        return self._sum(self.head, l, r)

    def _sum(self, v, l, r):
        if v is None:
            return 0
        if v.key > r:
            return self._sum(v.left, l, r)
        if v.key < l:
            return self._sum(v.right, l, r)
        if v.left is None and v.right is None:
            return v.key
        if v.min >= l and v.max <= r:
            return v.sum + v.key
        return self._sum(v.left, l, r) + self._sum(v.right, l, r) + v.key

AVL = AVLTree()

n = int(input())
prev_operation_is_query = False
for _ in range(n):
    operation = input().split()
    if operation[0] == '+':
        x = int(operation[1])
        if prev_operation_is_query:
            AVL.insert((x + y) % INF)
        else:
            AVL.insert(x)
        prev_operation_is_query = False
    elif operation[0] == '?':
        l, r = int(operation[1]), int(operation[2])
        y = AVL.sum(l, r)
        print(y)
        prev_operation_is_query = True


# -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 14:49:33 2019

@author: Amr Emam
"""

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn import metrics
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import pre_processing as pp

# Loading data
data = pd.read_csv('Mobile_App_Success_Milestone_2.csv')
#data.drop([6941, 12624, 18477], inplace=True)
#data = data[~data['Size'].isin(['Varies with device'])]
data.dropna(axis=0,how='any',thresh=5,inplace=True)
data = data[pd.notnull(data['App_Rating'])]

data=pp.remove_symbols(data)
data=pp.Encode_AppRating(data)
columns_to_be_validated=['Price','Size','Reviews','Installs']
data=pp.to_float(data,columns_to_be_validated)
data=pp.replace_nan_values(data,columns_to_be_validated)
data.dropna(axis=0,how='any',inplace=True)
data=pp.delete_noise_data(data,columns_to_be_validated)
columns_to_be_transfomered = ['Category', 'Minimum Version', 'Content Rating']
#data2=pp.label_encoder_trans(data,columns_to_be_transfomered)
#plt.subplots(figsize=(10, 8))

#corr =data2.corr()
#sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns,annot=true)
#plt.show()
X = data.iloc[:,[1,2,3,4,5,6,8]]
#X=pp.label_encoder_trans(X,['Latest Version'])

Y = data['App_Rating']
# pre-processing

columns_to_be_scaled = ['Installs', 'Reviews']
#X=pp.label_encoder_trans(X,columns_to_be_transfomered)

#dummy=pp.one_hot_trans(data,['Latest Version'])

encodedFeatures =pp.one_hot_trans(X,columns_to_be_transfomered)
scaled_columns=pp.feature_scaling(X,columns_to_be_scaled)

X.drop(columns=columns_to_be_transfomered, inplace=True)
X.drop(columns=columns_to_be_scaled, inplace=True)
X = np.array(X)
features = np.concatenate((X, encodedFeatures,scaled_columns), axis=1)

features = pd.DataFrame(features)
X_train, X_test, y_train, y_test = train_test_split(features, Y, test_size=0.30, shuffle=True)
#Get the correlation between the features
x_trainPca,x_testPca,ratio=pp.apply_PCA(X_train,X_test,2)

#filename = 'ModelName.sav'
#pickle.dump(ModelName, open(filename, 'wb'))


from multiprocessing import Lock, Process, Array, Manager, Pipe
from random import randint
from time import sleep, time

from os import getpid

class Test:
	def __init__(self):
		self.ll = Lock()

	def log(self, txt):
		self.ll.acquire()
		print(txt)
		self.ll.release()

def bla(k, pids, logr, cntr):
	logr.log('hello from {0:d}'.format(getpid()))
	pids[k] = getpid()
	cntr[getpid()] = randint(0, 256)

def blockproc(pipe):
	t = time()
	d = pipe.recv()
	print('blocked for {0:.6f} and got "{1:s}"'.format(time() - t, d))
	pipe.close()

pids = Array('i', range(10))

mngr = Manager()
container = mngr.dict()

if __name__ == '__main__':
	logr = Test()

	procs = []
	for k in range(10):
		p = Process(target=bla, args=(k, pids, logr, container))
		p.start()
		procs.append(p)

	sleep(0.5)

	for p in procs:
		p.join()

	print(pids[:])
	print(container)

	# blocking mode?
	local, remote = Pipe()
	p = Process(target=blockproc, args=(remote,))
	p.start()
	sleep(1.100)
	local.send('hello there, still waiting?')
	local.close()
	p.join()


class Solution:
    def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
        graph = {x: [] for x in recipes}
        dependencies = {x: 0 for x in recipes}
        supplies = set(supplies)

        for i, recipe in enumerate(recipes):
            for ingr in ingredients[i]:
                if ingr not in supplies and ingr in graph:
                    graph[ingr].append(recipe)
                    dependencies[recipe] += 1

                elif ingr not in supplies and ingr not in graph:
                    dependencies[recipe] += 1

        frontier = deque()
        for recipe in dependencies:
            if dependencies[recipe] == 0:
                frontier.append(recipe)

        createable = []

        while frontier:
            parent = frontier.popleft()

            for child in graph[parent]:
                dependencies[child] -= 1

                if dependencies[child] == 0:
                    frontier.append(child)

            createable.append(parent)

        return createable


import copy
from typing import List, Tuple, Optional

import attr
import numpy as onp

from sim.sim_types import RenderTriangle3d
from utils.colors import BGRCuteColors
from utils.custom_types import PixelCoordArray, BGRColor, BGRImageArray
from utils.cv2_but_its_typed import cv2_fill_poly, cv2_line, cv2_circle
from utils.geometry import Arrow2d
from utils.image import get_canvas
from vslam.cam import CameraIntrinsics
from vslam.math import normalize_vector
from vslam.poses import SE3_pose_to_xytheta
from vslam.transforms import homogenize
from vslam.types import BGRImageArray, Point2d, Points2d, TransformSE3, Pose2DArray

@attr.define
class BirdseyeViewSpecifier:
    """ Parameters for rendering a birdseye view"""
    resolution: float    # how many meters per pixel
    origin: Point2d
    world_size: Tuple[float, float]     # along 2 first coordinates of world coords

    def get_pixel_size(self) -> Tuple[int, int]:
        """ Get the size of the grid in pixels """
        x, y = self.world_size
        r = self.resolution
        return int(x / r),  int(y / r)

    @classmethod
    def from_view_center(
        cls,
        view_center: Point2d,
        world_size: Tuple[float, float],
        resolution: float = 0.05,  # how many meters per pixel
    ):
        origin = view_center[0] - world_size[1] / 2, view_center[1] - world_size[0] / 2

        return cls(
            resolution=resolution,
            origin=origin,
            world_size=world_size
        )

def bev_2d_world_to_pixel(
        world_coords: Points2d,
        view_specifier: BirdseyeViewSpecifier
) -> PixelCoordArray:
    """ Convert 2d world coordinates to pixel coordinates"""

    normalized = (world_coords - view_specifier.origin) / view_specifier.resolution
    discretized = normalized.astype(dtype=onp.int32)
    return discretized

def get_view_specifier_from_scene(
        scene: List[RenderTriangle3d],
        world_origin: Optional[Point2d] = None,
        world_size: Optional[Tuple[float, float]] = None,
        resolution: float = 0.05,
) -> BirdseyeViewSpecifier:
    """ Get a view specifier from a scene """

    if world_size is None or world_origin is None:
        all_points = onp.array([triangle.points[:, :2] for triangle in scene]).reshape(-1, 2)
        min_x, min_y = all_points.min(axis=0)
        max_x, max_y = all_points.max(axis=0)

        if world_size is None:
            world_size = (max_x - min_x, max_y - min_y)

        if world_origin is None:
            world_origin = (min_x, min_y)

    assert world_size[0] > 0
    assert world_size[1] > 0

    return BirdseyeViewSpecifier(
        resolution=resolution,
        origin=world_origin,
        world_size=world_size
    )

def draw_view_cone(
    view_specifier: BirdseyeViewSpecifier,
    camera_pose: TransformSE3,
    camera_intrinsics: CameraIntrinsics,
    image: BGRImageArray,
    whiskers_length_m: float = 5.0,
    whiskers_thickness_px: int = 2,
    whiskers_color: BGRColor = BGRCuteColors.OFF_WHITE
):
    """ Draws viewport on the image """
    # TODO: draw image plane ?
    # we want to draw viewport etc
    extreme_left = - camera_intrinsics.cx / camera_intrinsics.fx
    extreme_right = (camera_intrinsics.screen_w - camera_intrinsics.cx) / camera_intrinsics.fx

    # not really cam, there is implicit coord flip here
    left_vector_in_cam = whiskers_length_m * normalize_vector(onp.array([1., extreme_right, 0.]))
    right_vector_in_cam = whiskers_length_m * normalize_vector(onp.array([1., extreme_left, 0.]))

    left_homog = camera_pose @ homogenize(left_vector_in_cam)
    right_homog = camera_pose @ homogenize(right_vector_in_cam)

    # cv2_line(image, start_point, )
    left_px = bev_2d_world_to_pixel(left_homog[:2], view_specifier)
    right_px = bev_2d_world_to_pixel(right_homog[:2], view_specifier)
    center_px = bev_2d_world_to_pixel(camera_pose[:2, -1], view_specifier)

    cv2_line(image, left_px, center_px, color=whiskers_color, thickness=whiskers_thickness_px)
    cv2_line(image, right_px, center_px, color=whiskers_color, thickness=whiskers_thickness_px)

def draw_line_on_bev(
    image: BGRImageArray,
    view_specifier: BirdseyeViewSpecifier,
    from_pt: Point2d,
    to_pt: Point2d,
    color: BGRColor,
    thickness: int = 1
):
    from_px = bev_2d_world_to_pixel(onp.array([from_pt]), view_specifier)[0]
    to_px = bev_2d_world_to_pixel(onp.array([to_pt]), view_specifier)[0]

    cv2_line(image, from_px, to_px, color=color, thickness=thickness)

def draw_circle_on_bev(
        image: BGRImageArray,
        view_specifier: BirdseyeViewSpecifier,
        pt: Point2d,
        radius: int,
        color: BGRColor,
        thickness: int = 1
):
    pt_px = bev_2d_world_to_pixel(onp.array([pt]), view_specifier)[0]
    cv2_circle(image, pt_px, radius, color, thickness)

def render_birdseye_view(
        view_specifier: BirdseyeViewSpecifier,
        camera_pose: TransformSE3,
        camera_intrinsics: CameraIntrinsics,
        triangles: List[RenderTriangle3d],
        bg_color: BGRColor
) -> BGRImageArray:
    """ Renders birdseye view of the scene"""

    x_size, y_size = view_specifier.get_pixel_size()
    canvas = get_canvas(shape=(x_size, y_size, 3), background_color=bg_color)

    all_points = onp.array([triangle.points[:, :2] for triangle in triangles])
    pixel_points = bev_2d_world_to_pixel(all_points, view_specifier)

    for triangle_pts, triangle in zip(pixel_points, triangles):
        cv2_fill_poly(triangle_pts, canvas, color=triangle.front_face_color)

    draw_view_cone(view_specifier, camera_pose, camera_intrinsics, canvas)

    return canvas

@attr.define
class DisplayBirdseyeView:
    view_specifier: BirdseyeViewSpecifier
    canvas: BGRImageArray

    @classmethod
    def from_view_specifier(
        cls,
        view_specifier: BirdseyeViewSpecifier,
        ground_color: BGRColor = tuple(x - 20 for x in BGRCuteColors.CYAN)
    ):
        x_size, y_size = view_specifier.get_pixel_size()
        canvas = get_canvas(shape=(x_size, y_size, 3), background_color=ground_color)
        return cls(view_specifier, canvas)

    def draw_view_cone(
            self,
            at_pose: TransformSE3,
            camera_intrinsics: CameraIntrinsics,   # viewport is for drawing viewports and not general poses
            whiskers_thickness_px: int = 2,
    ) -> None:
        """ Draw viewport """
        draw_view_cone(
            self.view_specifier,
            at_pose,
            camera_intrinsics,
            self.canvas,
            whiskers_thickness_px=whiskers_thickness_px
        )

    def draw_arrow(
            self,
            arrow: Arrow2d,
            color: BGRColor = BGRCuteColors.DARK_GRAY,
            thickness: int = 3
    ):
        for (from_pt, to_pt) in arrow.get_lines_to_draw():
            self.draw_line_2d(from_pt, to_pt, color, thickness)

    def draw_2d_pose(
            self,
            pose_2d: Pose2DArray,
            color: BGRColor = BGRCuteColors.DARK_GRAY,
            arrow_length: float = 0.15,
            thickness: int = 2
    ):
        arrow = Arrow2d.from_length_and_origin(origin=pose_2d[:2], length=arrow_length, orientation=pose_2d[2])
        self.draw_arrow(arrow, color, thickness)

    def draw_3d_pose(
        self,
        pose: TransformSE3,
        color: BGRColor = BGRCuteColors.DARK_GRAY,
        arrow_length: float = 0.15,
        thickness: int = 2
    ):
        pose_2d = SE3_pose_to_xytheta(pose)
        arrow = Arrow2d.from_length_and_origin(origin=pose_2d[:2], length=arrow_length, orientation=pose_2d[2])
        self.draw_arrow(arrow, color, thickness)

    def draw_line_2d(
            self,
            from_pt: Point2d,
            to_pt: Point2d,
            color: BGRColor,
            thickness: int = 1
    ):
        draw_line_on_bev(
            self.canvas,
            self.view_specifier,
            from_pt,
            to_pt,
            color,
            thickness
        )

    def draw_circle(
            self,
            pt: Point2d,
            color: BGRColor,
            radius: int = 1,
            thickness: int = 1
    ):
        draw_circle_on_bev(
            self.canvas,
            self.view_specifier,
            pt,
            radius,
            color,
            thickness
        )

    def draw_triangles(
        self,
        triangles: List[RenderTriangle3d],
    ) -> None:
        """ aka draw scene """

        all_points = onp.array([triangle.points[:, :2] for triangle in triangles])
        pixel_points = bev_2d_world_to_pixel(all_points, self.view_specifier)

        for triangle_pts, triangle in zip(pixel_points, triangles):
            cv2_fill_poly(triangle_pts, self.canvas, color=triangle.front_face_color)

    def get_image(self) -> BGRImageArray:
        return self.canvas

    def clone(self):
        return copy.deepcopy(self)


from random import randint
def roll():
    result = randint(1, 6)
    print('Значение кубика: ', result)
    if result == 3 or result == 4:
        return roll()
    return result;
def main():
    value = roll()
    if value == 5 or value == 6:
        print('Вы победили')
    elif value == 1 or value == 2:
        print('Вы проиграли')
if __name__ == '__main__':
    main()


#
# Module: kmeans_pp
# Purpose: Make up for the ground work for the main kmeans algorithm -
# get initial centroids (kmeans++) and call the c function
# Interface: 2 functions - one that finds centroids and the other calls the c implementation
#

import numpy as np
import mykmeanssp

#
# Method: k_means_pp
# Purpose: Returns initial centroids using kmeans++ algorithm
#
def k_means_pp(pts, n, k, d):
    np.random.seed(0)
    if k == 0:
        return np.array([], np.float64)
    lst = np.zeros((k, d))
    ind = [0 for i in np.arange(k)]
    ind[0] = int(np.random.choice(n, 1))
    lst[0] = pts[ind[0]]
    d_arr = np.full(n, np.inf, dtype=np.float64)
    for i in np.arange(1, k):
        tmpmat = pts - lst[i - 1]
        d_arr = np.minimum(d_arr, np.sum(np.multiply(tmpmat, tmpmat), axis=1))
        d_sum = np.sum(d_arr)
        ind[i] = int(np.random.choice(n, 1, p=np.array([d_arr[i] / d_sum for i in np.arange(0, n)], np.float64)))
        lst[i] = pts[ind[i]]
    return lst

#
# Method: kmeans_cluster
# Purpose: Returns clustering of data according to kmeans, kmeans++ algorithms.
#
def kmeans_cluster(X, n, k, d, MAX_ITER):
    cents = k_means_pp(X, n, k, d)
    return mykmeanssp.kmeans_cpython(X.tolist(), cents.tolist(), MAX_ITER)


# importing all the required dependencies
from django.http import HttpResponse,JsonResponse
import random
import requests
from io import BytesIO
import threading
import os
from reportlab.pdfgen import canvas
from lorem_text import lorem
from reportlab.lib.pagesizes import A4
from reportlab.platypus import Image
from faker import Faker
import shutil
import zipfile
from ebooklib import epub

# Set the output folders
folder_name='output'
image_folder_name = 'image'
epub_folder_name='epub_output'
epub_image_folder_name = 'epub_image'

# delete the folders after creation
def deleteFolders():
    #remove folder_name
    if os.path.exists(folder_name):
        shutil.rmtree(folder_name)

    #remove image_folder_name
    if os.path.exists(image_folder_name):
        shutil.rmtree(image_folder_name)

    #remove epub_older_name
    if os.path.exists(epub_folder_name):
        shutil.rmtree(epub_folder_name)

    #remove epub_image_folder_name
    if os.path.exists(epub_image_folder_name):
        shutil.rmtree(epub_image_folder_name)

    return
# create the pdf files
def pdfCreation(pageNo):
    output_path=f"{folder_name}/{lorem.words(1)}.pdf"
    image_path=f"{image_folder_name}/{lorem.words(1)}.jpg"

    # Create a canvas (PDF)
    c = canvas.Canvas(output_path, pagesize=A4)
    for j in range(pageNo):
        lines = random.randint(15, 100)
        if j == 0 :
            fake=Faker()
            image_url = fake.image_url()
            response_image = requests.get(image_url)
            print(image_url)
            image_data = BytesIO(response_image.content)
            image_file = open(image_path, "+wb")
            image_file.write(image_data.read())
            image_file.close()
            # Add the image to the PDF
            c.drawImage(image_path, 5, 5,width=550,height=750)
        else:
            for i in range(lines):
                no_of_words = random.randint(5, 15)
                # Set font and draw the page number
                c.setFont('Helvetica', 12)
                c.drawString(3, 800-i*10, lorem.words(no_of_words))
        c.showPage()
    # Save the canvas (PDF)
    c.save()

def hello_world(req):
    return JsonResponse({'message': 'Hello, world!'})

#download-pdf route hits this function for getting the pdfs generated
def downloadPdf(req, num):
    #Check the folder exists
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)
    if not os.path.exists(image_folder_name):
        os.makedirs(image_folder_name)

    threads = []
    for i in range(num):
        pageNo = random.randint(2, 10)
        th=threading.Thread(target=pdfCreation, args=[pageNo])
        threads.append(th)
        th.start()

    for thread in threads:
        thread.join()

    # Define the path to the folder you want to zip
    folder_path = folder_name
    # Create a temporary directory to store the zip file
    temp_dir = 'pdfDoc'
    os.makedirs(temp_dir, exist_ok=True)
    # Create a temporary zip file
    temp_zipfile = os.path.join(temp_dir, 'output.zip')
    # Zip the folder contents
    with zipfile.ZipFile(temp_zipfile, 'w') as zipf:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                arcname = os.path.relpath(file_path, folder_path)
                zipf.write(file_path, arcname=arcname)
    # Open the zip file
    with open(temp_zipfile, 'rb') as f:
        response = HttpResponse(f.read(), content_type='application/zip')
        response['Content-Disposition'] = f'attachment; filename={temp_dir}.zip'
    # Delete the temporary files and directory
    shutil.rmtree(temp_dir)
    deleteFolders()

    return response

# create the epub files
def epubCreation(pageNo):
    # Create a new EPUB book
    book = epub.EpubBook()
    # Set metadata
    book.set_identifier(lorem.words(1))
    book.set_title(lorem.words(4))
    book.set_language('en')

    # Add an author
    book.add_author(lorem.words(2))

    for i in range(1, pageNo+1):
        page_title=f'Chapter {i}'
        content = f'
Chapter {i} Content

{lorem.paragraphs(2)}
'
        # Create a page
        page=epub.EpubHtml(title=page_title, file_name=f'chapter_{i}.xhtml', content=content)
        book.add_item(page)
        book.add_item(epub.EpubNcx())
        book.spine.append(page)

    # Add the table of contents to the book
    book.add_item(epub.EpubNav())

    # Create the EPUB file
    epub.write_epub(f'{epub_folder_name}/{lorem.words(1)}.epub', book)

# download-epub route hits this function for getting the pdfs generated
def downloadEpub(req,num):
    #Check the folder exists
    if not os.path.exists(epub_folder_name):
        os.makedirs(epub_folder_name)
    if not os.path.exists(epub_image_folder_name):
        os.makedirs(epub_image_folder_name)

    #threads array that contents each thread
    threads = []
    # looping through the threads
    for i in range(num):
        pageNo = random.randint(2, 10)
        th=threading.Thread(target=epubCreation, args=[pageNo])
        threads.append(th)
        th.start()

    for thread in threads:
        thread.join()

    # Define the path to the folder you want to zip
    folder_path = epub_folder_name
    # Create a temporary directory to store the zip file
    temp_dir = 'epubDoc'
    os.makedirs(temp_dir, exist_ok=True)
    # Create a temporary zip file
    temp_zipfile = os.path.join(temp_dir, f'{temp_dir}.zip')
    # Zip the folder contents
    with zipfile.ZipFile(temp_zipfile, 'w') as zipf:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                arcname = os.path.relpath(file_path, folder_path)
                zipf.write(file_path, arcname=arcname)
    # Open the zip file
    with open(temp_zipfile, 'rb') as f:
        response = HttpResponse(f.read(), content_type='application/zip')
        response['Content-Disposition'] = f'attachment; filename={temp_dir}.zip'
    # Delete the temporary files and directory
    shutil.rmtree(temp_dir)
    deleteFolders()

    return response


s="asGdfDFfggfFffGffDooHH"
l=[]
u=[]
for i in s:
    if i.islower():
        l.append(i)
    else:
        u.append(i)
n=''.join(l+u)
print("arranging characters giving precedence to lowercase letters:")
print(n)


import pandas as pd
import numpy as np
from scipy.stats import stats
from itertools import combinations
from itertools import permutations

class Phase1:

    def __init__(self, K2, K3, V2, V3):
        self.K2 = K2
        self.K3 = K3
        self.V2 = V2
        self.V3 = V3

    def map(self):
        data = pd.read_csv (r'./Data/testInput2.csv') #TODO read path from user
        print("Start Phase1")
        self.K2 = pd.DataFrame(data, columns= ['Movie'])
        self.V2 = pd.DataFrame(data, columns= ['Userid','Rating'])

    def reduce(self):
        self.K3 = pd.DataFrame({'Userid': self.V2.Userid})
        self.V3 = pd.concat([self.K2.Movie, self.V2.Rating, self.K2.groupby(by='Movie')['Movie'].transform('count')],axis=1,keys=['Movie', 'Rating', 'NumOfRatings'])
        print("Phase1 finished")
        return(self.K3, self.V3)

class Phase2:

    def __init__(self, K3, V3):
        self.K3 = K3
        self.V3 = V3

    def map(self):
        horizontal_concat = pd.concat([self.K3, self.V3], axis=1)
        print("Starting Phase2")
        t3 = list(horizontal_concat.itertuples(index=False))
        return t3

    def sort(self, t3): #on a cluster this would send the data to diffent nodes before the reduce
        d3 = dict()
        i = 0
        while i < len(t3): #Go through the list and create a dictionary with all the values tied to the same user
            key = t3[i].Userid
            if key in d3: #if this user id is already in the dict add the values to this key
                d3[t3[i].Userid].append([t3[i].Movie,t3[i].Rating,t3[i].NumOfRatings])
            else: #Create a new key and give values to that key
                d3[t3[i].Userid] = []
                d3[t3[i].Userid].append([t3[i].Movie,t3[i].Rating,t3[i].NumOfRatings])
            i = i + 1
        return d3

    def reduce(self, d3):
        i = 0
        while i < len(d3): #Generate all unique combos of movies
            j = 0
            while j < len(d3[i])-1:
                d3[i][j][len(d3[i][j]):]=d3[i][j+1]
                if j+1 == len(d3[i])-1:
                    d3[i][j+1][len(d3[i][j+1]):]=d3[i][0]
                    del d3[i][j+1][6:8]
                j = j + 1
            i = i + 1

        #Calcuate stats for phase3
        i = 0
        while i < len(d3):
            j = 0
            print(f"Reducing...{i}/{len(d3)}")
            while j < len(d3[i]):
                ratingProduct = d3[i][j][1] * d3[i][j][4]
                d3[i][j].append(ratingProduct)
                rating1Squared = d3[i][j][1] * d3[i][j][1]
                d3[i][j].append(rating1Squared)
                rating2Squared = d3[i][j][4] * d3[i][j][4]
                d3[i][j].append(rating2Squared)
                j = j +1
            i = i +1
        print("Phase2 finished")
        return d3

class Phase3:

    def map(self, d3):
        i = 0
        K4 = pd.DataFrame([], columns=['Movie1', 'Movie2'])
        V4 = pd.DataFrame([], columns=['rating1', 'numOfRating1', 'rating2', 'numOfRating2', 'ratingProduct', 'rating1Squared', 'rating2Squared'])
        print("Starting Phase3")
        while i < len(d3):
            print(f"Mapping...{i}/{len(d3)}")
            j = 0
            while j < len(d3[i]):
                newrow = {'Movie1': d3[i][j][0], 'Movie2': d3[i][j][3]}
                K4 = K4.append(newrow, ignore_index=True)
                newrow2 = {'rating1':d3[i][j][1], 'numOfRating1':d3[i][j][2], 'rating2':d3[i][j][4], 'numOfRating2':d3[i][j][5], 'ratingProduct':d3[i][j][6], 'rating1Squared':d3[i][j][7], 'rating2Squared':d3[i][j][8]}
                V4 = V4.append(newrow2, ignore_index=True)
                j = j + 1
            i = i + 1
        final = pd.concat([K4, V4], axis=1)
        return(final)

    def reduce(self, final):
        results = pd.DataFrame([], columns=['Movie1', 'Movie2', 'Similarity'])
        i = 0
        while i < len(final):
            print(f"Reducing...{i}/{len(final)}")
            similarity = final.loc[i,"ratingProduct"] / final.loc[i, "numOfRating1"] * final.loc[i, "numOfRating2"]
            newrow = {'Movie1':final.loc[i, "Movie1"], 'Movie2':final.loc[i, "Movie2"], 'Similarity':similarity}
            results = results.append(newrow, ignore_index=True)
            i = i + 1

        results.to_csv(r'./out.csv', header=None, index=None, sep=' ', mode='w')
        print(results)


import requests
import os
import pandas as pd
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Cloudflare API endpoint
endpoint = "https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records"

# Get Cloudflare details from environment variables
zone_id = os.getenv("CLOUDFLARE_ZONE_ID")
email = os.getenv("CLOUDFLARE_EMAIL")
api_key = os.getenv("CLOUDFLARE_GLOBAL_API_KEY")
record_name = os.getenv("DOMAIN_NAME")

headers = {
    "X-Auth-Email": email,
    "X-Auth-Key": api_key,
    "Content-Type": "application/json"
}

response = requests.get(endpoint.format(zone_id=zone_id), headers=headers)
data = response.json()

# Convert the 'result' key values into a pandas DataFrame
df = pd.DataFrame(data['result'])

# Export the DataFrame to a CSV file with column names
df.to_csv("data/cloudflare_"+ record_name +"_data.csv", index=False)

# Find and print the recordID for the specified record
"""filtered_df = df[df['name'] == record_name]
if not filtered_df.empty:
    record_id = filtered_df['id'].values[0]
    print(f"The recordID for {record_name} is: {record_id}")
else:
    print(f"No records found for {record_name}")
"""


# --------------------------------------------------------------------------
# Name:        Distribute Candies to People
# Author(s):   Phu Tran
# --------------------------------------------------------------------------
"""
    We distribute some number of candies, to a row of n = num_people people
    in the following way:

    We then give 1 candy to the first person, 2 candies to the second person,
    and so on until we give n candies to the last person.

    Then, we go back to the start of the row, giving n + 1 candies to the
    first person, n + 2 candies to the second person, and so on until we
    give 2 * n candies to the last person.

    This process repeats (with us giving one more candy each time, and moving
    to the start of the row after we reach the end) until we run out of candies.
    The last person will receive all of our remaining candies
    (not necessarily one more than the previous gift).

    Return an array (of length num_people and sum candies) that represents
    the final distribution of candies.

    Example 1:
      Input: candies = 7, num_people = 4
      Output: [1,2,3,1]
      Explanation:
        On the first turn, ans[0] += 1, and the array is [1,0,0,0].
        On the second turn, ans[1] += 2, and the array is [1,2,0,0].
        On the third turn, ans[2] += 3, and the array is [1,2,3,0].
        On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].

    Example 2:
      Input: candies = 10, num_people = 3
      Output: [5,2,3]
      Explanation:
        On the first turn, ans[0] += 1, and the array is [1,0,0].
        On the second turn, ans[1] += 2, and the array is [1,2,0].
        On the third turn, ans[2] += 3, and the array is [1,2,3].
        On the fourth turn, ans[0] += 4, and the final array is [5,2,3].

    Constraints:
      1. 1 <= candies <= 10^9
      2. 1 <= num_people <= 1000

    Hint:
      1. Give candy to everyone each "turn" first [until you can't],
         then give candy to one person per turn.
"""

class Solution(object):
    def distributeCandies(self, candies, num_people):
        """
        :type candies: int
        :type num_people: int
        :rtype: List[int]
        """
        result = [0]*num_people
        give = 1
        index = 0

        while candies > 0:
            # if candies still more than give
            if candies >= give:
                result[index] += give
                candies -= give
                give += 1
                index += 1
                if index == num_people:
                    index = 0
            else:
                result[index] += candies
                candies = 0
        return result

'''other faster methods (from other submissions)
##################################################
def distributeCandies(self, candies, num_people):
        """
        :type candies: int
        :type num_people: int
        :rtype: List[int]
        """
        res = [0 for i in range(num_people)]

        candy_to_give = 1
        i = 0
        while(candies>0):
            if candies < candy_to_give:
                res[i%num_people] += candies
                return res
            res[i%num_people] += candy_to_give
            i += 1
            candies -= candy_to_give
            candy_to_give += 1
        return res
##################################################
def distributeCandies(self, candies, num_people):
        """
        :type candies: int
        :type num_people: int
        :rtype: List[int]
        """
        ppl = [0]*num_people
        n = 0
        while candies >= 0:
            for i in range(len(ppl)):
                if candies - (n + i + 1) > 0:
                    ppl[i] += n + i + 1
                    candies -= n + i + 1
                else:
                    ppl[i] += candies
                    candies -= n + i + 1
                    break
            n += len(ppl)
        return ppl
##################################################
def distributeCandies(self, candies, num_people):
        """
        :type candies: int
        :type num_people: int
        :rtype: List[int]
        """

        distribution = []
        n = candies

        for person in range(1,num_people+1):
            if n > person:
                distribution.append(person)
                n -= person
            else:
                distribution.append(n)
                n = 0

        incrementer = len(distribution) + 1

        while n > 0:
            i = 0
            for x in distribution:
                if n > 0:
                    if n >= incrementer:
                        distribution[i] += incrementer
                    else:
                        distribution[i] += n

                    n -= incrementer
                    i += 1
                    incrementer += 1

        return distribution
'''


class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        dic = {')': '(', ']': '[', '}': '{'}
        for it in s:
            if it in dic:
                if not stack or dic[it] is not stack.pop():
                    return False
            else: stack.append(it)
        return not stack


from queue import Queue
import logging
from PyQt5 import QtWidgets
from PyQt5.QtCore import QObject, QThread, Qt, pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QDialogButtonBox

LOGGER=logging.getLogger('default_logger')

class Worker(QObject):

    worker_jobdone_signal=pyqtSignal(int) # jobid

    def __init__(self, id, func, jobqueue, outqueue):
        super(Worker,self).__init__()
        '''Worker used for separate thread.

        NOTE: args for func is assumed to have the format (jobid,jobargs)
        return of func is assumed to have the format (return_code, jobid,\
                other_results)
        '''

        self.id=id
        self.func=func
        self.jobqueue=jobqueue
        self.outqueue=outqueue
        self.abort=False

    @pyqtSlot()
    def processJob(self):
        while self.jobqueue.qsize():
            QtWidgets.QApplication.processEvents()
            if self.abort:
                return

            args=self.jobqueue.get()
            jobid=args[0]
            try:
                rec=self.func(*args)
                print('# <Worker>: Job %d done. Remaining queue size: %d.'\
                    %(jobid, self.jobqueue.qsize()))
            except:
                rec=(1,jobid,None)
                print('# <Worker>: Job %d failed. Remaining queue size: %d.'\
                    %(jobid, self.jobqueue.qsize()))
            self.jobqueue.task_done()
            self.outqueue.put(rec)
            self.worker_jobdone_signal.emit(jobid)

        return

class Master(QObject):

    all_done_signal=pyqtSignal()
    donejobs_count_signal=pyqtSignal(int) # NO. of finshed jobs

    def __init__(self, func, joblist, max_threads=4):
        super(Master,self).__init__()

        self.func=func
        self.joblist=joblist
        self.max_threads=max_threads
        self.all_done_signal.connect(self.onAllJobsDone)

    def run(self):

        self.threads=[]
        self.results=[]
        n_threads=min(self.max_threads,len(self.joblist))
        self.finished=0
        self.finished_jobs=[]

        self.jobqueue=Queue()
        self.outqueue=Queue()
        # populate job queue
        for ii,jobii in enumerate(self.joblist):
            self.jobqueue.put(jobii)

        # start worker threads
        for ii in range(n_threads):
            print('# <run>: create thread',ii)
            tii=QThread()
            wii=Worker(ii,self.func,self.jobqueue,self.outqueue)
            self.threads.append((tii,wii)) # need to keep record of both!

            wii.moveToThread(tii)
            wii.worker_jobdone_signal.connect(self.countJobDone)
            tii.started.connect(wii.processJob)
            tii.start()

        return

    @pyqtSlot(int)
    def countJobDone(self,jobid):
        self.finished+=1
        self.finished_jobs.append(jobid)
        self.donejobs_count_signal.emit(self.finished)
        while self.outqueue.qsize():
            resii=self.outqueue.get()
            self.results.append(resii)

        print('# <countJobDone>: Finished job id=%d. Finished jobs=%d'\
                %(jobid, self.finished))

        if self.finished==len(self.joblist):
            self.all_done_signal.emit()

        return

    @pyqtSlot()
    def onAllJobsDone(self):
        while self.outqueue.qsize():
            resii=self.outqueue.get()
            self.results.append(resii)

        for tii,wii in self.threads:
            tii.quit()
            tii.wait()
        return

    @pyqtSlot()
    def abortJobs(self):
        for tii,wii in self.threads:
            wii.abort=True
            tii.quit()
            tii.wait()

class ThreadRunDialog(QtWidgets.QDialog):

    def __init__(self,func,joblist,show_message='',max_threads=3,
            get_results=False,close_on_finish=True,parent=None):
        super(ThreadRunDialog,self).__init__(parent=parent)

        self.func=func
        self.joblist=joblist
        self.show_message=show_message
        self.max_threads=max_threads
        self.get_results=get_results
        self.close_on_finish=close_on_finish
        self.parent=parent

        self.setWindowModality(Qt.ApplicationModal)
        self.setWindowTitle('Processing ...')
        self.resize(500,100)

        va=QtWidgets.QVBoxLayout(self)

        va.addWidget(QtWidgets.QLabel(show_message))

        self.progressbar=QtWidgets.QProgressBar(self)
        self.progressbar.setMaximum(len(joblist))
        self.progressbar.setValue(0)

        self.buttons=QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)

        va.addWidget(self.progressbar)
        va.addWidget(self.buttons)

        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.abortJobs)

        self.master=Master(func,joblist,self.max_threads)
        self.master.donejobs_count_signal.connect(self.updatePB)
        self.ok_button=self.buttons.button(QDialogButtonBox.Ok)
        self.ok_button.setEnabled(False)
        self.cancel_button=self.buttons.button(QDialogButtonBox.Cancel)
        self.master.all_done_signal.connect(self.allJobsDone)

        self.master.run()
        self.exec_()

    @pyqtSlot()
    def allJobsDone(self):
        self.cancel_button.setEnabled(False)
        self.ok_button.setEnabled(True)
        if self.close_on_finish:
            self.accept()
        return

    @pyqtSlot(int)
    def updatePB(self,value):
        self.progressbar.setValue(value)
        return

    @pyqtSlot()
    def abortJobs(self):
        self.master.abortJobs()
        if self.get_results:
            self.results=self.master.results
        self.reject()
        return

    @pyqtSlot()
    def accept(self):
        print('# <accept>: get result?',self.get_results)
        if self.get_results:
            self.results=self.master.results
            print('# <accept>: self.results',self.results)
        super(ThreadRunDialog,self).accept()
        return


from globals import *

__all__ = ['light_up_room', 'light_passage', 'darken_room', 'get_room_char',
           'get_rand_row_col', 'get_rand_room', 'fill_room_with_objects',
           'get_room_number', 'shell']

def light_up_room():
    if g.blind: return
    r = rooms[g.current_room]
    for i in range(r.top_row, r.bottom_row + 1):
        for j in range(r.left_col, r.right_col + 1):
            mvaddch(i, j, get_room_char(screen[i][j], i, j))
    mvaddch(rogue.row, rogue.col, rogue.fchar)

def light_passage(row, col):
    if g.blind: return
    i_end = 1 if row < LINES - 2 else 0
    j_end = 1 if col < COLS - 1 else 0

    for i in range(-1 if row > MIN_ROW else 0, i_end + 1):
        for j in range(-1 if col > 0 else 0, j_end + 1):
            if is_passable(row + i, col + j):
                r = row + i
                c = col + j
                mvaddch(r, c, get_room_char(screen[r][c], r, c))

def darken_room(rn):
    if g.blind: return
    r = rooms[rn]
    for i in range(r.top_row + 1, r.bottom_row):
        for j in range(r.left_col + 1, r.right_col):
            if not is_object(i, j) and not (g.detect_monster and screen[i][j] & MONSTER):
                if not hiding_xeroc(i, j):
                    mvaddch(i, j, ' ')

def get_room_char(mask, row, col):
    if mask & MONSTER:
        return get_monster_char_row_col(row, col)
    if mask & SCROLL:
        return '?'
    if mask & POTION:
        return '!'
    if mask & FOOD:
        return ':'
    if mask & WAND:
        return '/'
    if mask & ARMOR:
        return ']'
    if mask & WEAPON:
        return ')'
    if mask & GOLD:
        return '*'
    if mask & TUNNEL:
        return '#'
    if mask & HORWALL:
        return '-'
    if mask & VERTWALL:
        return '|'
    if mask & AMULET:
        return ','
    if mask & FLOOR:
        return '.'
    if mask & DOOR:
        return '+'
    if mask & STAIRS:
        return '%'
    return ' '

def get_rand_row_col(mask):
    while True:
        row = get_rand(MIN_ROW, SROWS - 2)
        col = get_rand(0, SCOLS - 1)
        rn = get_room_number(row, col)
        if screen[row][col] & mask and not screen[row][col] & ~mask and rn != NO_ROOM: break
    return row, col

def get_rand_room():
    while True:
        i = get_rand(0, MAXROOMS - 1)
        if rooms[i].is_room: break
    return i

def fill_room_with_objects(rn):
    r = rooms[rn]
    N = (r.bottom_row - r.top_row - 1) * (r.right_col - r.left_col - 1)
    n = get_rand(5, 10)
    if n > N: n = N - 2

    for i in range(n):
        while True:
            row = get_rand(r.top_row + 1, r.bottom_row - 1)
            col = get_rand(r.left_col + 1, r.right_col - 1)
            if screen[row][col] == FLOOR: break
        obj = get_rand_object()
        put_object_at(obj, row, col)

    return n

def get_room_number(row, col):
    for i in range(MAXROOMS):
        r = rooms[i]
        if r.top_row <= row <= r.bottom_row and r.left_col <= col <= r.right_col:
            return i
    return NO_ROOM

def shell():
    raise


#!/usr/bin/env python
import sys

if 'develop' in sys.argv:
    # use setuptools for develop, but nothing else
    from setuptools import setup
else:
    from distutils.core import setup

with open('README.rst') as file:
    long_description = file.read()

with open('CHANGES') as file:
    long_description += file.read()

__version__='0.1.4'

setup(name='agpy',
      version=__version__,
      description='agpy, Adam Ginsburg\'s Python Code (in 0.1 for perpetuity - it won\'t bump up until I release something)',
      long_description=long_description,
      author='Adam Ginsburg',
      author_email='adam.g.ginsburg@gmail.com',
      data_files=[('h2fit',['h2fit_support/atran.txt',
        'h2fit_support/atran2000.fits',
        'h2fit_support/atran_arcturus.txt',
        'h2fit_support/atran_raw_arcturus.txt',
        'h2fit_support/atran_solar.txt',
        'h2fit_support/atran_tran.txt',
        'h2fit_support/dalgarno1984_table5.txt',
        'h2fit_support/h2pars.txt',
        'h2fit_support/linelist.txt'])],
      url='http://code.google.com/p/agpy/',
      packages=['agpy','agpy/mpfit','AG_fft_tools','AG_image_tools','agpy/contributed','radex'],
     )


import sys
import pygame
import random

from setting import Settings
from game_status import GameStats
from background import Background
from button import Button

class Game2048:
    """游戏资源类"""
    def __init__(self):
        # 游戏界面初始化
        pygame.init()
        self.settings = Settings()
        self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.scree_height))

        # 标题
        pygame.display.set_caption("2048")

        # 游戏列表
        self.game_list = [[0, 0, 0, 0],
                          [0, 0, 0, 0],
                          [0, 0, 0, 0],
                          [0, 0, 0, 0]]

        # 游戏状态
        self.status = GameStats(self)
        self.status.load_high_score()

        # 背景
        self.background = Background(self)

        # 按钮
        self.new_game_button = Button(self, "New Game")

    def run_game(self):
        """主循环"""
        self._random()
        while True:
            self._check_event()
            self._check_game_status()
            self._update_screen()
            if self.status.is_win or self.status.is_over:
                self.status.save_high_score()

    def _check_event(self):
        """相应鼠标和键盘输入"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_key_down_event(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_button(mouse_pos)

    def _check_key_down_event(self, event):
        """检查键盘输入"""
        if event.key == pygame.K_LEFT:
            self._move_left()
        elif event.key == pygame.K_RIGHT:
            self._move_right()
        elif event.key == pygame.K_UP:
            self._move_up()
        elif event.key == pygame.K_DOWN:
            self._move_down()

        # 如果游戏没有结束就继续随机生成数字
        if not(self.status.is_win or self.status.is_over):
            self._random()

    def combination(self, temp_list):
        """结合一行或一列相同方块
           将行或列中的数字按顺序存储在temp_list列表中
           然后根据不同情况进行合并
        """
        nums = []
        ans = [0, 0, 0, 0]
        for i in temp_list:
            if i != 0:
                nums.append(i)
        length = len(nums)

        # 没有数字
        if length == 0:
            return ans
        # 只有一个数字
        elif length == 1:
            ans[0] = nums[0]
            return ans
        # 有两个数字
        elif length == 2:
            # case 1
            if nums[0] == nums[1]:
                ans[0] = nums[0] + nums[1]
                self.status.score += ans[0]
                return ans
            # case 2
            else:
                ans[0] = nums[0]
                ans[1] = nums[1]
                return ans
        # 有三个数字
        elif length == 3:
            # case 1
            if nums[0] == nums[1]:
                ans[0] = nums[0] + nums[1]
                ans[1] = nums[2]
                self.status.score += ans[0]
                return ans
            # case 2
            elif nums[1] == nums[2]:
                ans[0] = nums[0]
                ans[1] = nums[1] + nums[2]
                self.status.score += ans[1]
                return ans
            # case 3
            else:
                nums.append(0)
                return nums
        # 有四个数字
        else:
            # case 1
            if nums[0] == nums[1]:
                ans[0] = nums[0] + nums[1]
                self.status.score += ans[0]
                # 1 2和3 4位置的数字分别相等
                if nums[2] == nums[3]:
                    ans[1] = nums[2] + nums[3]
                    self.status.score += ans[1]
                    return ans
                # 只有1 2位置相等
                else:
                    ans[1] = nums[2]
                    ans[2] = nums[3]
                    return ans
            # case 2
            # 中间两个数字相等
            elif nums[1] == nums[2]:
                ans[0] = nums[0]
                ans[1] = nums[1] + nums[2]
                ans[2] = nums[3]
                self.status.score += ans[1]
                return ans
            # case 3
            # 3 4两个数字相等
            elif nums[2] == nums[3]:
                ans[0] = nums[0]
                ans[1] = nums[1]
                ans[2] = nums[2] + nums[3]
                self.status.score += ans[2]
                return ans
            # case 4
            # 四个数字都不相等
            else:
                return nums

    def _move_left(self):
        """左移操作"""
        for i in range(4):
            temp = self.combination(self.game_list[i])
            for j in range(4):
                self.game_list[i][j] = temp[j]

    def _move_right(self):
        """右移操作"""
        for i in range(4):
            temp = self.combination(self.game_list[i][::-1])
            for j in range(4):
                self.game_list[i][3 - j] = temp[j]

    def _move_up(self):
        """上移操作"""
        for i in range(4):
            temp = []
            for j in range(4):
                temp.append(self.game_list[j][i])
            temp = self.combination(temp)
            for k in range(4):
                self.game_list[k][i] = temp[k]

    def _move_down(self):
        """下移操作"""
        for i in range(4):
            temp = []
            for j in range(4):
                temp.append(self.game_list[3 - j][i])
            temp = self.combination(temp)
            for k in range(4):
                self.game_list[3 - k][i] = temp[k]

    def _check_game_status(self):
        """检查游戏状态"""
        # 判断游戏是否胜利，同时将没有数字的位置存在empty_pos列表中
        empty_pos = []
        for i in range(4):
            for j in range(4):
                if self.game_list[i][j] == 2048:
                    self.status.is_win = True
                if self.game_list[i][j] == 0:
                    empty_pos.append([i, j])

        # empty_list为空则说明方格全部填满，判断相邻方块是否有相同，没有则游戏失败
        if len(empty_pos) == 0:
            flag = True
            for i in range(4):
                for j in range(3):
                    if self.game_list[i][j] == self.game_list[i][j + 1]:
                        flag = False
            for i in range(4):
                for j in range(3):
                    if self.game_list[j][i] == self.game_list[j + 1][i]:
                        flag = False
            if flag:
                self.status.is_over = True

    def _random(self):
        """随机位置生成2或4"""
        # 列表empty_list存储没有数字的位置
        empty_pos = []
        for i in range(4):
            for j in range(4):
                if self.game_list[i][j] == 0:
                    empty_pos.append([i, j])

        # empty_list非空则继续随机生成
        if len(empty_pos) != 0:
            i_pos, j_pos = random.choice(empty_pos)
            num = random.randint(1, 2)
            self.game_list[i_pos][j_pos] = num * 2

    def _check_button(self, mouse_pos):
        """确定点击按钮"""
        # 点击New Game按钮
        button_clicked = self.new_game_button.rect.collidepoint(mouse_pos)
        if button_clicked:
            # 将游戏重置，同时随机生成一个2或4
            self.game_list = [[0, 0, 0, 0],
                              [0, 0, 0, 0],
                              [0, 0, 0, 0],
                              [0, 0, 0, 0]]
            self._random()
            self.status.reset_stats()

    def _show_game(self):
        """绘制4×4数字方块"""
        for i in range(4):
            for j in range(4):
                rect_color = self.settings.colors[self.game_list[i][j]]
                rect_pos = [(j + 1) * self.settings.grid_width + j * self.settings.size,
                            self.settings.score_height + (i + 1) * self.settings.grid_width + i * self.settings.size]
                pygame.draw.rect(self.screen, rect_color, (rect_pos, (self.settings.size, self.settings.size)), 0)

                # 如果数字是0就不绘制
                if self.game_list[i][j] != 0:
                    num_image = self.settings.num_font.render(str(self.game_list[i][j]), True,
                                                              self.settings.num_color,
                                                              rect_color)
                    num_image_rect = num_image.get_rect()
                    num_rect_pos = [(j + 1) * self.settings.grid_width + (j + 0.5) * self.settings.size,
                                    self.settings.score_height + (i + 1) * self.settings.grid_width +
                                    (i + 0.5) * self.settings.size]
                    num_image_rect.center = tuple(num_rect_pos)
                    self.screen.blit(num_image, num_image_rect)

    def _update_screen(self):
        """更新游戏屏幕"""
        self.screen.fill(self.settings.bg_color)
        self.new_game_button.draw_button()
        self.background.draw_line()
        self._show_game()

        # 判断当前得分是否大于最高分
        if self.status.score > self.status.high_score:
            self.status.high_score = self.status.score
        self.background.draw_score()

        # 判断游戏是否结束
        if self.status.is_win:
            self.background.draw_win()
        if self.status.is_over:
            self.background.draw_over()

        pygame.display.flip()

if __name__ == '__main__':
    ai = Game2048()
    ai.run_game()


import random

def play():
    user= input("'r' for rock, 'p' for paper, 's' for scissors:")
    computer=random.choice(['r','p','s'])

    if user==computer:
        return'DRAW!'

    if win(user,computer):
        return'You won'

    return 'You lost'

#r>s,s>p,p>r
def win(player,opp):
    if (player=='r' and opp=='s'or player=='s' and opp=='p' or player=='p' and opp=='r'):
        return True

print(play())


import random
import tkinter as tk
from matplotlib.pyplot import style

try:
    from src.modules.gui.parent.canvas import MyCanvas
except:
    from modules.gui.parent.canvas import MyCanvas

class Controller(MyCanvas):
    """Draws PCB on canvas"""

    def __init__(self, frame: tk.Tk) -> None:
        super().__init__(frame)

    def __call__(
        self,
        coords: dict,
        mTime: dict,
        sTime: dict,
        numParts: int,
        randomInterupt: tuple = (0, 0),
        prodName: str = "",
    ) -> None:
        """Creates the summary with the provided data.

        Args:
            coords (dict): PCB Coordinates for plotting.
            mTime (dict): Time from assembly calculations.
            sTime (dict): Time from setup calculations.
            numParts (int): Number of created PCBs.
            randomInterupt (tuple, optional): The random interrupt values. (Min, Max). Defaults to (0, 0).
            prodName (str, optional): The Product name. Defaults to "".
        """
        self.figure.clear()
        plot = self.figure.add_subplot(121)
        ax = self.figure.add_subplot(122)
        runtime = sum(list(mTime.values()))
        # setupTime = sum(list(sTime.values()))
        ax.axis("off")
        sumtime = []
        for i in range(numParts):
            sumtime.append(
                runtime + random.randint(randomInterupt[0], randomInterupt[1])
            )

        textstr = "\n".join(
            (
                f"Product: {prodName} ",
                "",
                f"Overall time needed: {round(sum(sumtime), 2)} Seconds",
                f"Average Time: {round(sum(sumtime) / numParts, 2)} Seconds ",
                f"Highest time: {round(max(sumtime), 2)} Seconds",
                "",
                "Machines",
            )
        )
        substr = ""
        for key in mTime:
            substr = (
                substr
                + f"\n{key} Ideal: {round(mTime[key], 2)} Seconds \n{key} Setup Time: {round(sTime[key], 2)} Seconds\n"
            )
        textstr = textstr + substr
        props = dict(boxstyle="round", alpha=0.5)

        ax.text(
            0.05,
            0.95,
            textstr,
            transform=ax.transAxes,
            fontsize=14,
            verticalalignment="top",
            wrap=True,
        )
        for key in coords:
            plot.scatter(coords[key]["X"], coords[key]["Y"])
        plot.legend(tuple(coords.keys()), loc="upper left")
        self.canvas.draw()

    def wait(self) -> any:
        """Function that displays a loading screen."""
        self.figure.clear()
        waitPlot = self.figure.add_subplot(111)

        style.use("ggplot")
        waitPlot.axis("off")
        # waitPlot.set_title("Loading...", color="green")
        waitPlot.text(
            0.5,
            0.5,
            "Loading...",
            fontsize=14,
            verticalalignment="center",
            horizontalalignment="center",
            color="green",
            wrap=True,
        )
        self.canvas.draw()

    def error(self, error: str) -> None:
        """Function that displays an error message.

        Args:
            error (str): The current error message.
        """
        self.figure.clear()
        errorPlot = self.figure.add_subplot(111)

        style.use("ggplot")
        errorPlot.axis("off")
        # errorPlot.set_title(f"An error occured: {error} ", color="red")
        errorPlot.text(
            0.5,
            0.5,
            error,
            fontsize=14,
            verticalalignment="center",
            horizontalalignment="center",
            color="red",
            wrap=True,
        )
        self.canvas.draw()


#!/usr/bin/python3.4
# coding: utf-8

"""
Programme : test_random_unittest.py       version 1.1
Date : 30-11-2017
Auteur : Hervé Dugast
Source : https://openclassrooms.com/courses/apprenez-a-programmer-en-python/les-tests-unitaires-
    avec-unittest
Fonctionnement :
   Ce programme réalise 3 tests unitaires sur certaines méthodes du module random : random.choice,
   random.shuffle et random.sample. Le résultat est forcément un succès car random est un module
   officiel de python.
   Ce test unitaire doit être lancé dans une console : python3 -m unittest

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++ Affichage console en cas de succès ++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
pi@raspi3btssn:~ $ cd prog/test_unitaire/openclassroom/
pi@raspi3btssn:~/prog/test_unitaire/openclassroom $ python3 -m unittest         ...
----------------------------------------------------------------------
Ran 3 tests in 0.007s

OK
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++ Affichage console en cas d'échec ++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
pi@raspi3btssn:~/prog/test_unitaire/openclassroom $ python3 -m unittest
FE.
======================================================================
ERROR: test_sample (test_random_unittest.RandomTest)
Test le fonctionnement de la fonction 'random.sample'.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/pi/prog/test_unitaire/openclassroom/test_random_unittest.py", line 103, in test_sample
    extrait = random.sample(self.liste, 1000)  # provoque une erreur volontairement
  File "/usr/lib/python3.4/random.py", line 315, in sample
    raise ValueError("Sample larger than population")
ValueError: Sample larger than population

======================================================================
FAIL: test_choice (test_random_unittest.RandomTest)
Test le fonctionnement de la fonction 'random.choice'.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/pi/prog/test_unitaire/openclassroom/test_random_unittest.py", line 89, in test_choice
    self.assertIn(elt, ["a","b","c"])   # provoque un échec volontairement
AssertionError: 1 not found in ['a', 'b', 'c']

----------------------------------------------------------------------
Ran 3 tests in 0.005s

FAILED (failures=1, errors=1)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
"""

# Ajout des chemins d'accès aux bibliothèques et modules dans le python PATH
# chemin absolu de l'exécutable
import sys
import os
chemin = os.path.dirname(os.path.abspath(__file__))
while not chemin.endswith('test_unitaire'):
    chemin = os.path.dirname(chemin)
chemin = os.path.dirname(chemin)
if chemin not in sys.path:
    sys.path.insert(0, chemin)
#print(sys.path)   #pour afficher le python PATH

import random
import unittest

class RandomTest(unittest.TestCase):
    """Test case utilisé pour tester les fonctions du module 'random'."""

    def setUp(self):
        """Initialisation des tests."""
        self.liste = list(range(10))

    def test_choice(self):
        """Test le fonctionnement de la fonction 'random.choice'."""
        elt = random.choice(self.liste)
        # instructions pour faire réussir ou échouer le test.
        #    succès : décommenter self.assertIn(elt, self.liste) et commenter instruction qui la suit
        #    échec  : décommenter self.assertIn(elt, ["a","b","c"]) et commenter instruction qui la précède
        #self.assertIn(elt, self.liste)
        self.assertIn(elt, ["a","b","c"])   # provoque un échec volontairement

    def test_shuffle(self):
        """Test le fonctionnement de la fonction 'random.shuffle'."""
        random.shuffle(self.liste)
        self.liste.sort()
        self.assertEqual(self.liste, list(range(10)))

    def test_sample(self):
        """Test le fonctionnement de la fonction 'random.sample'."""
        # instructions pour faire réussir ou échouer le test.
        #    succès : décommenter extrait = random.sample(self.liste, 5) et commenter l'autre instruction
        #    échec  : décommenter extrait = random.sample(self.liste, 1000) et commenter l'autre instruction
        #extrait = random.sample(self.liste, 5)
        extrait = random.sample(self.liste, 1000)  # provoque une erreur volontairement
        for element in extrait:
            self.assertIn(element, self.liste)

        with self.assertRaises(ValueError):
            random.sample(self.liste, 20)


"""
Module for KwikSortAbs. This module contains an abstract class about KwikSort algorithm for rank aggregation. This
algorithm is based on QuickSort: a pivot is chosen, and the elements that should be placed before (resp. tied with,
resp. after) the pivot are placed before (resp. tied with, resp. after) the pivot, and this process is done recursively.
Complexity (mean): m * n * log(n) with n = nb of elements, m = nb of rankings.
A class that implements the abstract class must implement the choice of the pivot.
"""

from typing import List, Dict
from numpy import ndarray, asarray
from corankco.algorithms.rank_aggregation_algorithm import RankAggAlgorithm
from corankco.dataset import Dataset
from corankco.scoringscheme import ScoringScheme
from corankco.consensus import Consensus, ConsensusFeature
from corankco.element import Element
from corankco.ranking import Ranking

class KwikSortAbs(RankAggAlgorithm):
    """
    Interface for KwikSort algorithms. KwikSort is a heuristics designed for Kemeny-Young method.
    QuickSort based algorithm: pick a pivot, find the set of elements shat should be ranked after pivot,
    then before pivot, then tied with pivot, and recursively go on with the before and after sets
    complexity: mean: O(nb_rankings * nb_elements * log2(nb_elements)) if choice of pivot is O(1)
    complexity: worst: 0(nb_ranking * nb_elements²) if pivot divides elements in groups of size 1 and n-1
    """

    def compute_consensus_rankings(
            self,
            dataset: Dataset,
            scoring_scheme: ScoringScheme,
            return_at_most_one_ranking: bool = True,
            bench_mode: bool = False
    ) -> Consensus:
        """
        Calculate and return the consensus rankings based on the given dataset and scoring scheme.

        :param dataset: The dataset of rankings to be aggregated.
        :type dataset: Dataset
        :param scoring_scheme: The scoring scheme to be used for calculating consensus.
        :type scoring_scheme: ScoringScheme
        :param return_at_most_one_ranking: If True, the algorithm should return at most one ranking.
        :type return_at_most_one_ranking: bool
        :param bench_mode: If True, the algorithm may return additional information for benchmarking purposes.
        :type bench_mode: bool
        :return: Consensus rankings. If the algorithm is unable to provide multiple consensuses or
        return_at_most_one_ranking is True, a single consensus ranking is returned.
        :raise ScoringSchemeNotHandledException: When the algorithm cannot compute the consensus because the
        implementation does not support the given scoring scheme.
        """

        scoring_scheme_numpy: ndarray = asarray(scoring_scheme.penalty_vectors)

        consensus_list: List[List[Element]] = []
        mapping_elements_id: Dict[Element, int] = dataset.mapping_elem_id
        positions = dataset.get_positions()

        self._kwik_sort(consensus_list, list(dataset.universe), mapping_elements_id, positions, scoring_scheme_numpy)
        return Consensus(
            consensus_rankings=[Ranking([set(bucket) for bucket in consensus_list])], dataset=dataset,
            scoring_scheme=scoring_scheme, att={ConsensusFeature.ASSOCIATED_ALGORITHM: self.get_full_name()})

    def _get_pivot(self, mapping_elements_id: Dict[Element, int], elements: List[Element], positions: ndarray,
                   scoring_scheme: ndarray) -> Element:
        """
        Private function, returns the pivot. The choice of the pivot is set by the programmer in daughter classes
        :param mapping_elements_id: the dictionary whose keys are the elements and the values their unique int ID
        :param elements: the list of remaining elements to put in the consensus
        :param positions: ndarray where positions[i][j] is the position of element i in ranking j. Missing: element: -1
        :param scoring_scheme: the scoring scheme that may be used (or not) to choose a pivot
        :return: an Element as pivot
        """
        raise NotImplementedError("The method not implemented")

    # public abstract V getPivot(List < V > elements, U var);

    def _where_should_it_be(self, pos_pivot_rankings: ndarray, pos_other_element_rankings: ndarray,
                            scoring_scheme_numpy: ndarray) -> int:
        """
        Private method. Given the pivot defined by its ranks in the input rankings as a ndarray and another element
        defined by the same way, returns -1, 1, 0 if the element should be respectively before, after or tied with
        the pivot in the consensus
        :param pos_pivot_rankings: the nb_rankings positions of the pivot in a ndarray
        :param pos_other_element_rankings: the nb_rankings positions of the target element in a ndarray
        :param scoring_scheme_numpy: the ScoringScheme
        :return: returns -1, 1, 0 if the element should be respectively before, after or tied with the pivot
        in the consensus
        """
        raise NotImplementedError("The method not implemented")

    def _kwik_sort(self, consensus: List[List[Element]], remaining_elements: List[Element],
                   mapping_element_id: Dict[Element, int], positions: ndarray, scoring_scheme: ndarray):
        after: List[Element] = []
        before: List[Element] = []
        pivot: Element = Element(-1)
        if len(mapping_element_id) > 0:
            pivot = self._get_pivot(mapping_element_id, remaining_elements, positions, scoring_scheme)
        same: List[Element] = [pivot]
        positions_pivot = positions[mapping_element_id.get(pivot)]

        # compare pivot with all remaining elements to separate between "left", "center", "right"
        for element in remaining_elements:
            if element != pivot:
                positions_element = positions[mapping_element_id.get(element)]
                pos = self._where_should_it_be(positions_pivot, positions_element, scoring_scheme)
                if pos < 0:
                    before.append(element)
                elif pos > 0:
                    after.append(element)
                else:
                    same.append(element)

        if len(before) == 1:
            consensus.append(before)
        elif len(before) > 0:
            self._kwik_sort(consensus, before, mapping_element_id, positions, scoring_scheme)
        if len(same) > 0:
            consensus.append(same)
        if len(after) == 1:
            consensus.append(after)
        elif len(after) > 0:
            self._kwik_sort(consensus, after, mapping_element_id, positions, scoring_scheme)

    def get_full_name(self) -> str:
        """
        Return the full name of the algorithm.

        :return: name of the algorithm, must be defined in daughter classes.
        :rtype: str
        """
        raise NotImplementedError("The method not implemented")

    def is_scoring_scheme_relevant_when_incomplete_rankings(self, scoring_scheme: ndarray) -> bool:
        """
        Check if the scoring scheme is relevant when the rankings are incomplete.

        :param scoring_scheme: The scoring scheme to be checked.
        :type scoring_scheme: ScoringScheme
        :return: True as KwikSort can handle any ScoringScheme
        :rtype: bool
        """
        raise NotImplementedError("The method not implemented")