from flask import Flask, Blueprint, request
from flask_login import login_required, current_user
from app.models import db, League, User, LeaguesTournament
from app.forms import LeagueForm

#  url_prefix="/api/leagues
league_routes = Blueprint("leagues", __name__)

# GET ALL LEAGUES
@league_routes.route("/")
@login_required
def leagues():
    leagues = League.query.all()
    return {"leagues": [league.to_dict() for league in leagues]}, 201

# GET USER'S LEAGUES
@league_routes.route("/user")
@login_required
def leagues_user():
    leagues = current_user.leagues
    return {"leagues": [league.to_dict() for league in leagues]}, 201

# GET LEAGUES WHICH ARE PUBLIC AND USER'S
@league_routes.route("/public")
@login_required
def leagues_public():
    league1 = League.query.filter_by(is_private=False).all()
    if current_user:
        user_leagues = current_user.leagues
        leagues = list(set(league1).union(set(user_leagues)))
        return {"leagues": [league.to_dict() for league in leagues]}, 201
    else:
        return {"leagues": [league.to_dict() for league in league1]}, 201

# CREATE LEAGUE
@league_routes.route("/new", methods=["POST"])
@login_required
def create_league():
    userId = int(current_user.id)
    res = request.get_json()
    form = LeagueForm()
    form["csrf_token"].data = request.cookies["csrf_token"]
    tournaments = res["tournaments"]
    if tournaments == None:
        return {"error": ["League must choose atleast one tournament"]}, 403

    if len(tournaments) < 1:
        return {"error": ["League must choose atleast one tournament"]}, 403

    if form.validate_on_submit():
        league = League (
            owner_id=userId,
            name=res["name"],
            display_pic=res["display_pic"],
            team_budget=res["team_budget"],
            is_private=res["is_private"],
        )
        db.session.add(league)
        db.session.commit()
        for tournament in tournaments:
            league_tournament = LeaguesTournament(
                league_id=league.id,
                tournament_id=tournament
            )
            db.session.add(league_tournament)
            db.session.commit()

        return {"league": league.to_dict()}, 201

# EDIT LEAGUE
@league_routes.route("/<int:id>", methods=["PUT"])
@login_required
def edit_league(id):
    userId = int(current_user.id)
    league = League.query.get(id)
    if (league == None):
        return {"errors": ["League does not exist"]}, 404
    if (league.owner_id != userId):
        return {"errors": ["This league doesn't belong to this user"]}, 403

    res = request.get_json()
    form = LeagueForm()
    form["csrf_token"].data = request.cookies["csrf_token"]
    if form.validate_on_submit():
        league.name = res["name"]
        league.display_pic = res["display_pic"]
        league.is_private = res["is_private"]
        db.session.commit()

        print("LEAGUE -------->", league.to_dict())
        return {"league": league.to_dict()}, 200

    return form.errors

# DELETE LEAGUE
@league_routes.route("/<int:league_id>", methods=["DELETE"])
@login_required
def delete_league(league_id):
    userId = int(current_user.id)
    league = League.query.get(league_id)
    if (league == None):
        return {"errors": ["League does not exist"]}, 404
    if (league.owner_id != userId):
        return {"errors": ["This league doesn't belong to this user"]}, 403

    db.session.delete(league)
    db.session.commit()

    return {"league": league_id}


"""
Created on Thu Jun  4 19:23:29 2020

@author: Aditya
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor as RF
from sklearn.metrics import r2_score

dataset=pd.read_csv("./Position_Salary.csv")
X=dataset.iloc[:,1].values        #input
Y=dataset.iloc[:,2].values          #output

X=X.reshape(-1,1)
#Y=Y.reshape(-1,1)
plt.scatter(X,Y,color="blue")
print(X)
print(Y)

reg=RF(n_estimators=200,max_leaf_nodes=9,random_state=1)
reg.fit(X,Y)

print(reg.estimator_[5].predict([[7.5]]))

grid=np.arange(min(X),max(X),0.1)
grid=grid.reshape(-1,1)
plt.plot(grid,reg.predict(grid),color="green")
#plt.plot(X,Y,color="red")
plt.show()

print(r2_score(Y, reg.predict(X)))


from django.shortcuts import render, redirect
from django.views import generic
from .models import Pregunta, Persona
from .forms import PreguntaForm, PersonaForm
from django.contrib.auth.decorators import login_required, permission_required

# Create your views here.
@login_required
def eliminar_persona(request, id):
    persona = Persona.objects.get(id=id)
    persona.delete()

    return redirect(to="listar_persona")
@login_required
def modificar_persona(request, id):
    persona = Persona.objects.get(id=id)
    data = {
        'form': PersonaForm(instance=persona)
    }
    if request.method =='POST':
        formulario = PersonaForm(data=request.POST, instance=persona, files=request.FILES )
        if formulario.is_valid():
            formulario.save()
            data['mensaje'] = "Persona Modificada Correctamente"
            data['form'] = formulario
    return render(request,'modificar_persona.html', data)
@login_required
def persona_list(request):
    preguntas = Pregunta.objects.all()
    data = {
        'preguntas':preguntas
    }
    return render(request, 'persona_list.html', data)
@permission_required('agregar_pre')
def nueva_pregunta(request):
    data = {
        'form':PreguntaForm()
    }
    if request.method == 'POST':
        formulario = PreguntaForm(request.POST)
        if formulario.is_valid():
            formulario.save()
            data['mensaje'] = "Enviado Correctamente"
    return render(request, 'agregar_pre.html',data)
@login_required
def modificar_pregunta(request, id):
    pregunta = Pregunta.objects.get(id=id)
    data = {
        'form': PreguntaForm(instance=pregunta)
    }
    if request.method =='POST':
        formulario = PreguntaForm(data=request.POST, instance=pregunta)
        if formulario.is_valid():
            formulario.save()
            data['mensaje'] = "Pregunta Modificada Correctamente"
            data['form'] = formulario

    return render(request,'modificar_pre.html', data)
@login_required
def eliminar_pregunta(request, id):
    pregunta = Pregunta.objects.get(id=id)
    pregunta.delete()

    return redirect(to="persona_list")
@permission_required('nueva_persona')
def nueva_persona(request):
    data = {
        'form':PersonaForm()

    }
    if request.method == 'POST':
        formulario = PersonaForm(request.POST, files=request.FILES)
        if formulario.is_valid():
            formulario.save()
            data['mensaje']= "Guardado correctamente"

    return render(request, 'nueva_persona.html', data)

def home(request):

    return render(request, 'home.html')

def registro(request):
    return render(request, 'registro.html')

def login(request):
	return render(request, 'login.html')

def preguntasyrespuestas(request):
    return render(request, 'preguntasyrespuestas.html')

def listar_persona(request):
    personas= Persona.objects.all()
    data = {
        'personas': personas
    }
    return render(request, 'listar_persona.html', data)

class PersonaListView(generic.ListView):
	model = Persona

class PersonaDetailView(generic.DetailView):
	model = Persona


import json

class Course:
    def __init__(self,semesters,weight,title,department,coursecode,description,restrictions,prereqs):
        self.semesters = semesters
        self.weight = weight
        self.title = title
        self.department = department
        self.coursecode = coursecode
        self.description = description
        self.restrictions = restrictions
        self.prereqs = prereqs
        self.webKey = None

    def __str__(self):
        return("Course Title: " + self.title + "\nCourse Code: " + self.coursecode + "\nSemesters Offered: " + self.semesters + "\nCourse Weight: " + self.weight + "\nDepartment: " + self.department + "\nDescription: " + self.description + "\nRestrictions: " +  self.restrictions + "\nPrerequisites: " + self.prereqs)

    #Course code on the txt file is formatted ex: CIS*2750
    def to_hash(self):
        keyValues = self.coursecode.replace(',', '').split("*")
        text = keyValues[0] + "-" + keyValues[1] + "-" + self.semesters + "-" + self.weight
        return text

    #Convert Course Data to dict
    def to_dict(self, webData):

        courseData = {}
        courseData['semesters'] = self.semesters
        courseData['weight'] = self.weight
        courseData['title'] = self.title
        courseData['department'] = self.department
        courseData['coursecode'] = self.coursecode
        courseData['description'] = self.description
        courseData['restrictions'] = self.restrictions
        courseData['prereqs'] = self.prereqs
        courseData['status'] = 'Not Available Winter (NAW)'

        if (self.webKey != None):
            courseData['status'] =  webData[self.webKey].get_status()
            courseData['availability'] =  webData[self.webKey].get_availability()
            courseData['capacity'] =  webData[self.webKey].get_capacity()
            courseData['faculty'] =  webData[self.webKey].get_faculty()

        return courseData

    @staticmethod
    def Find(coursecode, courses_dict):
        for _, course in courses_dict.items():
            if course.coursecode.replace(',', '') == coursecode.replace('-', '*'):
                return course
        return None


from functools import wraps
import importlib
from json import dumps, loads
import os
from platform import architecture, release
from pprint import pformat as pf
from subprocess import Popen, PIPE
import sys
from time import time_ns
from typing import Any, Callable, Dict, List

from typeguard import typechecked
from wenv import EnvConfig, PythonVersion

from .cmd import run_cmd
from .const import ARCHITECTURE, ARCHS, CONVENTIONS, PLATFORM, PYTHONBUILDS_FN
from .names import get_benchmark_fld
from .pythonversion import read_python_builds

# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ROUTINES
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

@typechecked
def _permutations(fn: str):
    """
    Provides all permutations on calling convention, arch, ctypes/Python version

    Args:
        - fn: File name of Python source file
    Yields:
        Tuple containing arch, convention, ctypes, dll handle
    """

    from .ctypes import CTYPES, get_dll_handle

    fn = os.path.basename(fn)
    fld = get_benchmark_fld()

    for convention in CONVENTIONS:
        for arch in ARCHS:
            for ctypes_build in CTYPES.get(arch, tuple()):
                if PLATFORM == "unix" or arch[3:] == ARCHITECTURE:
                    yield (
                        arch,
                        convention,
                        ctypes_build,
                        get_dll_handle(
                            arch,
                            ctypes_build,
                            convention,
                            fld,
                            fn,
                        ),
                    )

@typechecked
def benchmark(fn: str, initializer: Callable) -> Any:
    """
    Decorator for benchmark functions

    Args:
        - fn: File name of Python source file
    Yields:
        DLL handles per calling convention, architecture and wenv Python version
    """

    def outer(func: Callable) -> Callable:

        @wraps(func)
        def inner() -> List[Dict]:

            reports = []

            for arch, convention, ctypes, dll_handle in _permutations(fn):

                print(f'Benchmark ...')

                func_handle = initializer(
                    ctypes = ctypes,
                    dll_handle = dll_handle,
                    conv = convention,
                )
                min_runtime = None
                benchmark_start = time_ns()
                counter = 0

                while 1_000_000_000 > time_ns() - benchmark_start:  # at least one sec

                    iteration_start = time_ns()

                    func(ctypes, func_handle)

                    runtime = time_ns() - iteration_start
                    if min_runtime is None or min_runtime > runtime:
                        min_runtime = runtime

                    counter += 1

                server = None
                if PLATFORM == 'unix':
                    server = '.'.join(str(ctypes.zb_get_parameter('pythonversion')).split('.')[:3])

                report = dict(
                    platform = PLATFORM,
                    arch = arch,
                    convention = convention,
                    name = func.__name__,
                    runtime = min_runtime,
                    runs = counter,
                    server = server,
                    client = sys.version.split(' ')[0],
                )
                reports.append(report)

                print(pf(report))

            return reports

        inner.is_benchmark = None
        return inner

    return outer

@typechecked
def _get_benchmarks() -> List[Callable]:
    """
    auto-detects benchmarks
    """

    benchmarks = []

    for item in os.listdir('benchmark'):

        if item.startswith("_") or not item.lower().endswith(".py"):
            continue

        try:
            mod = importlib.import_module(f"benchmark.{item[:-3]:s}")
        except ModuleNotFoundError:  # likely no gui support
            continue

        for attr in dir(mod):
            entry = getattr(mod, attr)
            if not hasattr(entry, 'is_benchmark'):
                continue
            benchmarks.append(entry)

    return benchmarks

@typechecked
def _group_data(data: List) -> Dict:
    """
    Group parsed raw data by benchmark, arch, version and calling convention
    """

    by_benchmark = {}
    for entry in data:
        name = entry['name']
        try:
            group = by_benchmark[name]
        except KeyError:
            group = []
            by_benchmark[name] = group
        group.append(entry)

    by_archverconv = {name: {} for name in by_benchmark.keys()}
    for name, group in by_benchmark.items():
        for entry in group:
            archver = (
                entry['server'] if entry['server'] is not None else entry['client'],
                entry['arch'],
                entry['convention']
            )
            try:
                subgroup = by_archverconv[name][archver]
            except KeyError:
                subgroup = []
                by_archverconv[name][archver] = subgroup
            subgroup.append(entry)

    return by_archverconv

@typechecked
def _make_table(name: str, group: Dict, doc: str):
    """
    Write on RST table from parsed and grouped data
    """

    keys = sorted(
        group.keys(),
        key = (lambda item: (PythonVersion.from_config(item[1], item[0]), item[1], item[2])),
    )

    with open(os.path.join('docs', 'source', f'benchmark_{name}.rst'), mode = 'w', encoding="utf-8") as f:

        f.write(f'.. csv-table:: "{name:s}" benchmark, CPython {sys.version.split(" ")[0]:s} on {sys.platform:s}, versions of CPython on Wine\n')
        f.write('    :header: "version", "arch", "convention", "ctypes [µs]", "zugbruecke [µs]", "overhead [µs]"\n')
        f.write('    :delim: 0x0003B\n')
        f.write('\n')

        for version, arch, conv in keys:
            unix, wine = group[(version, arch, conv)]
            if unix['server'] is None:
                unix, wine = wine, unix
            unix, wine = round(unix['runtime'] / 1e3, 1), round(wine['runtime'] / 1e3, 1)
            f.write(f'    "{version:s}"; "{arch:s}"; "{conv:s}"; {wine:,.01f}; {unix:,.01f}; {unix-wine:,.01f}\n')

        f.write('\n')
        for line in doc.split('\n'):
            f.write(f'{line[4:]:s}\n')

@typechecked
def _make_inventory(names: List[str]):

    with open(os.path.join('docs', 'source', 'benchmarks_all.rst'), mode = 'w', encoding="utf-8") as f:
        for name in names:
            f.write(f'.. include:: benchmark_{name:s}.rst\n')

def _make_sysinfo():

    with open('/proc/cpuinfo', mode='r', encoding='utf-8') as f:
        cpuinfo = f.read()
    cpuinfo = [line for line in cpuinfo.split('\n') if 'model name' in line][0].split(':')[1].strip()

    proc = Popen(['wine', '--version'], stdout = PIPE)
    wine, _ = proc.communicate()
    wine = wine.decode('utf-8').strip().split('-')[1]

    with open(os.path.join('docs', 'source', 'benchmarks_sysinfo.rst'), mode = 'w', encoding="utf-8") as f:
        f.write('Benchmarks were performed on an ')
        f.write(f'"{cpuinfo:s}" CPU, ')
        f.write(f'Linux {release():s} {architecture()[0]}, ')
        f.write(f'and Wine {wine:s}')
        f.write('.\n')

def _make_tables():
    """
    Write RST table from raw benchmark data
    """

    benchmarks = {
        entry.__name__: entry.__doc__
        for entry in _get_benchmarks()
    }

    data = []
    with open(os.path.join('benchmark', 'data.raw'), mode = 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if len(line) == 0:
                continue
            data.extend(loads(line))

    for name, group in _group_data(data).items():
        _make_table(name, group, benchmarks[name])

    _make_inventory(list(benchmarks.keys()))
    _make_sysinfo()

def _run_wenv():
    """
    Run benchmarks on Wine from Unix
    """

    cfg = EnvConfig()
    builds = read_python_builds(fn = os.path.join(cfg['prefix'], PYTHONBUILDS_FN))

    for arch, _builds in builds.items():
        for build in _builds:
            run_cmd(
                cmd = ['make', '_clean_py'],
            )
            run_cmd(
                cmd = [
                    'wenv', 'python', '-m', 'tests.lib.benchmark'
                ],
                env = {
                    'WENV_DEBUG': '0',
                    'WENV_ARCH': arch,
                    'WENV_PYTHONVERSION': str(build),
                    'WENV_NO_PTH_FILE': 'true' if build.minor >= 11 else 'false',  # CPython PR #31542
                },
            )
    run_cmd(
        cmd = ['make', '_clean_py'],
    )

def main():
    """
    Run all benchmarks both on Unix and Wine
    """

    if len(sys.argv) > 1 and sys.argv[1] == 'wine':
        _run_wenv()
        return
    if len(sys.argv) > 1 and sys.argv[1] == 'table':
        _make_tables()
        return
    if len(sys.argv) > 1 and sys.argv[1] != 'unix':
        raise SystemError(f'unknown parameter "{sys.argv[1]:s}"')

    fn = os.path.join('benchmark', 'data.raw')

    if not os.path.exists(fn):
        with open(fn, mode = 'w', encoding='utf-8') as f:
            f.write("")

    for item in _get_benchmarks():
        reports = item()
        with open(fn, mode = "a", encoding='utf-8') as f:
            f.write(f'{dumps(reports):s}\n')

# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# MODULE ENTRY POINT
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

if __name__ == "__main__":

    main()


from django.db.models import Manager, Q
from django.utils.translation import ugettext_lazy as _
from django.db.models.query import QuerySet
from django.utils.translation import get_language, activate
from django.conf import settings

from hvad.manager import TranslationManager

from datetime import datetime

def isvalidlanguage(lang):
	found = False
	for k,v in settings.LANGUAGES:
		if k == lang:
			found = True
			break
	return found

if settings.LANGUAGE_CODE != get_language() and not isvalidlanguage(get_language()):
	activate(settings.LANGUAGE_CODE)

class BaseManager(TranslationManager):
	def translated(self):
		qs = self.model.objects
		try:
			getattr(self.model.objects, 'language')
			lang = get_language()
			if not isvalidlanguage(lang):
				lang = settings.LANGUAGE_CODE
			if not isvalidlanguage(lang) and len(settings.LANGUAGES) > 0:
				lang = settings.LANGUAGES[0][0]
			qs = qs.language(lang)
		except AttributeError:
			pass
		return qs

class PublishableManager(BaseManager):

	STATUS_DRAFT = 1
	STATUS_PUBLISHED = 2
	STATUS_DISABLED = 3
	STATUS_CHOICES = (
		(STATUS_DRAFT, _("Draft")),
		(STATUS_PUBLISHED, _("Published")),
		(STATUS_DISABLED, _("Disabled")),
	)

	def published(self, request=None):
		# allow staff users to preview pages
		allow_unpublished  = (request and hasattr(request, 'user') and request.user.is_authenticated() and request.user.is_staff)
		if allow_unpublished:
			return self.translated()
		else:
			return self.translated().filter(
				Q(expiry_date__gte=datetime.now()) | Q(expiry_date__isnull=True),
				publish_date__lte=datetime.now(),
				status=PublishableManager.STATUS_PUBLISHED
			)

class PromotableManager(PublishableManager):
	def promoted(self):
		return self.published().filter(promoted=True)


# number = int(input("Please enter your number : "))
# number = str(number)
# count1 = 0
# count2 = 1
# str1 = ""
# if len(number) % 2 == 0 and len(number) != 0:
#     for i in range(int(len(number) / 2)):
#         str1 += int(number[count1]) * number[count2]      #THIS SOLUTİON WİTH NORMAL METHODS
#         count1 += 2
#         count2 += 2
#     print(str1)
# else:
#     print("invalid")

def look_and_say(number):
    count1 = 0
    count2 = 1
    str1 = ""
    if len(number) % 2 == 0 and len(number) != 0:
        for i in range(int(len(number) / 2)):
            str1 += int(number[count1]) * number[count2]                                          #THIS SOLUTİON WİTH FUNCTİON
            count1 += 2
            count2 += 2
        return str1
    else:
        return "invalid"

print(look_and_say("1213141516171819"))


import sys

# setting path
sys.path.append('../weighing')

from views.product_view import ProductView
from models.product import ProductModel, ProductLocationModel
from models.stock_location import StockLocationModel

class ProductController():
    def __init__(self, view_master= None, db=None, api=None, columns= None, refresh_db_function=None):
        self.columns= columns
        self.api = api
        self.model= ProductModel(db=db)
        self.stock_location_model = StockLocationModel(db=db)
        self.product_location_model = ProductLocationModel(db=db)
        self.view_master= view_master
        self.location_values_id = {}
        self.product_frame = self.get_view()
        self.refresh_db_function = refresh_db_function

    def refresh(self):
        self.refresh_db_function()
        self.initialize_view(self.product_frame)

    def location_callback(self, location):
        self.initialize_view(self.product_frame)

    def location_load(self, product_view):
        location_id = self.stock_location_model.select_query(columns=['ODOO_ID','LOCATION'])
        self.location_values_id = { location[1]:location[0] for location in location_id }
        locations = list(self.location_values_id.keys())

        product_view.location.configure(values=locations)

        if locations:
            product_view.location.set(locations[0])

    def get_view(self):
        product_view = ProductView(master=self.view_master, fg_color='white')
        product_view.refresh_button.configure(command=self.refresh)
        self.location_load(product_view)
        product_view.location.configure(command=self.location_callback)
        self.initialize_view(product_view)
        return product_view

    def initialize_view(self, product_view):
        for rec in product_view.product_list.frame_list:
            rec.destroy()
        product_view.product_list.frame_list = []
        location_id = self.location_values_id.get(product_view.location.get())

        data = None
        if location_id:
            data = self.model.get_data(location_id)
        if data:
            for idx,instance in enumerate(data):
                instance_dict = {'id': instance[0],'ODOO_ID': instance[1], 'PRODUCT':instance[2]}
                color, fg_color = ('green','#e0e0e0') if idx%2 == 1 else ('blue violet', '#C0C0C0')
                product_view.product_list.create_elements(instance_dict, color, fg_color)


# -*- coding: utf-8 -*-
"""
Created on Sat Feb 13 14:35:03 2021

@author: Feyza
"""

# Kart sınıfı

# Kart sınıfından türetilen her bir nesne bir kart türünü temsil edecek.
# Kart sınıfının tip ve deger isminde 2 instance özelliği olsun. (tip:sinek deger:5)

# sinek5 = Kart("sinek","5")
# karoAs = Kart("karo","A")

# Kart sınıfının kartıGetir() ismindeki instance metodu kart bilgilerini yazdırsın.

# sinek5.kartıGetir() => sinek 5

# Deste sınıfı

# deste1 = Deste()

# kart tipleri   => karo,sinek,kupa,maça
# kart değerleri => A,2,3,4,5,6,7,8,9,10,J,Q,K

# Deste sınıfındaki kartlar listesine 52 kartı for ve list comphension ile ekleyiniz.
# Destede kalan kart sayısı için kartSayisi() isminde bir metot.
# Destedeki kartları karıştırmak için KartlariKaristir() isminde bir metot.
# kartDagit() ismindeki metot belirtilen adet kadar kartı dağıtmalıdır. Destedeki kalan kart sayısına dikkat.
# kartAt() ismindeki metot elden bir kart atmak için kullanılsın.

# class Quiz:
#     def __init__(self,questions):  # Soruları burda set etmiş olduk
#         self.questions = random.sample(questions, len(questions))
#         self.questionIndex = 0
#         self.score = 0
from random import shuffle
class Kart:

    def __init__(self,tip,deger):
        self.tip=tip
        self.deger=deger

    def kartıGetir(self): #Instance Method: Kart bilgilerini yazdırıcak..
          return f"Kart Bilgileri:{self.tip} {self.deger}"

    def __repr__(self):  # Repr Methodu
        return f"{self.tip} {self.deger}"

class Deste:
      tipler=["karo","sinek","kupa","maça"]
      degerler=["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
      def __init__(self):
          self.kartlar=[Kart(tip,deger) for tip in Deste.tipler for deger in Deste.degerler]  #Kart nesnesine gönderiyoruz Kart(tip,deger)
          print(self.kartlar)

      def KartSayisi(self):
          return len(self.kartlar)

      def KartlariKaristir(self):
          if (self.KartSayisi()<52):
              raise ValueError("Deste Bozulmadan kartları karıştırabilirsiniz..")
          shuffle(self.kartlar)

      def KartDagit(self,adet):
          kartSayisi=self.KartSayisi() #Fonksiyon çağırılıcak
          if kartSayisi==0:
              raise ValueError("Bütün Kartlar Dağıtıldı...")
          adet=min([kartSayisi,adet])
          kartlar= self.kartlar[-adet:]
          self.kartlar=self.kartlar[:adet]
          return kartlar

deste1=Deste()

deste1.KartlariKaristir()
print("--------------------------------------------------------------------------------")

print(deste1.KartSayisi())

print("--------------------------------------------------------------------------------")

print(deste1.KartDagit(2))

print("--------------------------------------------------------------------------------")

print(deste1.KartSayisi())


"""
Obtenemos los seguidores del usuario que pasamos como parámetro.
"""
import sys
import tweepy
import credentials  # las credenciales para la conexión están aquí

if len(sys.argv) != 2:
    print("Número de argumentos erróneo", file=sys.stderr)
    sys.exit(-1)

client = tweepy.Client(bearer_token=credentials.BEARER_TOKEN, wait_on_rate_limit=True)

user_query = client.get_user(username=sys.argv[1])
for user in tweepy.Paginator(client.get_users_followers, id=user_query.data.id, max_results=1000).flatten():
    print(user.username)


# -*- coding:utf-8 -*-
import inspect
import json
import logging

import yaml
from appium.webdriver import WebElement
from appium.webdriver.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from appium.webdriver import Remote
from appium_xueqiu.page.wrapper import handle_alert

class BasePage:
	logging.basicConfig(level=logging.INFO)
	_driver:WebDriver
	_params = dict()

	def __init__(self, driver:WebDriver = None):
		self._driver = driver

	def set_implicitly(self, time):
		self._driver.implicitly_wait(time)

	def wait_element_visible(self, time, locator):
		'''等待元素出现'''
		return WebDriverWait(self._driver, time).until(expected_conditions.visibility_of_element_located(locator))

	def finds(self, locator, value:str = None):
		elements: list
		if isinstance(locator, tuple):
			elements = self._driver.find_elements(*locator)
		else:
			elements = self._driver.find_elements(locator, value)
		return elements

	# @handle_alert
	def find(self,locator, value: str = None):
		element: WebElement
		if isinstance(locator, tuple):
			element = self._driver.find_element(*locator)
		else:
			element = self._driver.find_element(locator, value)
		return element

	def steps(self, path):
		''' 解析 yaml 文件，yaml格式：
		方法：
			- 定位方式
			  定位元素
			  操作方式
		:param path: yaml 文件路径
		:param func: 待执行的函数名： func = inspect.stack()[1].function 通过过这个方式获取
		:return:
		'''
		with open(path, encoding='utf-8') as fr:
			logging.info(f'1、读取 {path} 文件')
			func = inspect.stack()[1].function # [0] -> steps, [1] -> 调用steps的方法名
			logging.info(f'正在获取方法 【{func}】 的yaml数据')
			steps = yaml.safe_load(fr)[func]
			logging.info('2、解析文件')

			# 将外部参数传入yaml文件，将 dict 转成 str, 用 str的replace方法，将 参数 替换成值，再转回dict
			# if self._params:
			steps_str = json.dumps(steps)
			for key, value in self._params.items():
				steps_str = steps_str.replace('${' + key + '}', value)
			steps = json.loads(steps_str)

			for step in steps:
				if "action" in step.keys():
					logging.info('3、多个动作解析')
					action = step['action']
					if action == 'click':
						logging.info('3.1、click 点击操作')
						self.find(step['by'], step['locator']).click()
					if action == 'send':
						logging.info('3.2、输入操作')
						if 'value' in step.keys():
							value = step['value']
							self.find(step['by'], step['locator']).send_keys(value)
						else:
							logging.info(f'文件[{path}]中定位元素[{step["locator"]}]缺少输入值 value')
					if action == 'len > 1':
						logging.info('3.3 验证操作')
						eles = self.finds(step['by'], step['locator'])
						logging.info('len(eles) > 0: ', len(eles) > 0)
						return len(eles) > 0

	'''---------------------------------------------'''
	''' 模拟键盘操作                                  '''
	'''---------------------------------------------'''
	def enter(self):
		'''回车，KEYCODE_ENTER -> 66'''
		self._driver.keyevent = 66


from vpython import *

run = False
def runbutton(b):
    global run
    if run: b.text = "Run"
    else: b.text = 'Pause'
    run = not run
button(text = "Run", color=color.blue, bind=runbutton)

floor = box(pos=vector(0, -5, 0), size=vector(10, 0.2, 10), texture=textures.wood)
ball = sphere(pos=vector(-5, 5, 0), radius=0.6, color=color.blue, make_trail=True, emissive=True)

ball.m = 0.5
ball.p = ball.m*vector(1, 4, 0) #Projectile of the ball
ball_weight = 0.8
g = 9.8
t = 0
dt = 0.01

graph(height=200, title='Graph for momentum', fast=False, xtitle='t, s', ytitle='vy, m')
y = gcurve(color=color.red)
l = local_light(pos=ball.pos, color=ball.color)

while ball.pos.x < 8:
    rate(200)
    if run:
        f = vector(0, -ball.m*g, 0)
        ball.p = ball.p + f * dt
        ball.pos = ball.pos + (ball.p/ball.m) * dt
        l.pos = ball.pos
        if ball.pos.y < floor.pos.y + ball.radius:
            ball.p.y = abs(ball.p.y) * ball_weight
        t += dt
        y.plot(t, ball.p.y/ball.m)


n = int(input())
serial = [input().rstrip() for _ in range(n)]

def sum(ser):
    cnt = 0
    for i in ser:
        if i.isdigit():
            cnt += int(i)
    return cnt

serial.sort(key=lambda x: (len(x), sum(x), x))
for i in serial:
    print(i)


'''
for know more about exception handling see
documentation Or W3school(Exception_handling)
**syntax:
      "try:
          probable error statement
      except error_type:
         message_statement....
      except error_type:
         message_statement....
         .
         .
      finaly:
        exact/right statement....
      "
'''
try:
    list = [20, 0, 30]
    result = list[0] / list[3]
    print(result,"done")
except ZeroDivisionError:
    print("Dividing by zero is not possible")
except IndexError:
    print("Index Error")
finally:
    print("successful")


from django.conf.urls import url

from . import views

app_name = 'invest'

urlpatterns = [
        # ex: /invest/
        url(r'^$', views.index, name='index'),
        url(r'^adddb/$', views.adddb, name='adddb'),
        url(r'^compare/$', views.compare, name='compare'),
        url(r'^data/$', views.dataoperation, name='dataoperation'),
        url(r'^insert/$', views.insert, name='insert'),
        url(r'^delete/$', views.delete, name='delete'),
        url(r'^deleteid/$', views.deleteid, name='deleteid'),
        url(r'^deleteidbatch/$', views.deleteidbatch, name='deleteidbatch'),

        # ex: /polls/5/
        #url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
        # ex: /polls/5/results/
        #url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
        # ex: /polls/5/vote/
        #url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
            ]


import json

import torch
from torch import nn, optim
from torch.nn.parameter import Parameter

class InsensitiveLoss(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, y_pred, y, w):
        diff = torch.abs(y_pred - y)
        diff[diff < 0.5] = 0.0
        return (diff * w).sum() / w.sum()

class Prot1(nn.Module):
    def __init__(self):
        super().__init__()
        self.c = Parameter(torch.tensor(1.0, dtype=torch.float64), requires_grad=True)

    def forward(self, x):
        max_score, max_pods, max_time, score_per_pod, ms, pr, pods_collected = torch.tensor_split(x, 7, dim=1)
        return (pods_collected * pr * torch.exp(ms - 1) + self.c) / max_pods - .5

def get_data():
    with open('data/merged_scores.json') as r:
        score_dict = json.load(r)

    with open('data/params.json') as r:
        params = json.load(r)

    sym_data = []
    sym_target = []
    sym_weights = []

    mss = {o['iz_name']: o['MS Multiplier'] for o in params}
    prs = {o['iz_name']: o['PR Multiplier'] for o in params}

    for k, score_info in score_dict.items():
        objs = [v for v in score_info['scores'] if 'fm' in v]
        max_score = score_info['max_score']
        max_pods = score_info['max_pods']
        max_time = score_info['max_time']

        sym_data.append([
            float(max_score),
            float(max_pods),
            float(max_time),
            max_score / max_pods,
            mss[k],
            prs[k],
            0.0,
        ])
        sym_target.append(0.0)
        sym_weights.append(1.0)

        for o in objs:
            sym_data.append([
                float(max_score),
                float(max_pods),
                float(max_time),
                max_score / max_pods,
                mss[k],
                prs[k],
                float(o['pods']),
            ])
            sym_target.append(float(o['fm']))
            sym_weights.append(1.0)

    sym_data = torch.DoubleTensor(sym_data)
    sym_target = torch.DoubleTensor(sym_target)
    sym_weights = torch.DoubleTensor(sym_weights)

    return sym_data, sym_target, sym_weights

def main():
    model = Prot1()

    sym_data, sym_target, sym_weights = get_data()

    optimizer = optim.Adam(model.parameters(), lr=1e-3)
    sched = optim.lr_scheduler.StepLR(optimizer, step_size=7000, gamma=0.01)
    crit = InsensitiveLoss()

    model.eval()
    with torch.no_grad():
        optimizer.zero_grad()

        y_pred = model(sym_data).squeeze(-1).detach().cpu()
        y = sym_target.detach().cpu()
        w = sym_weights.detach().cpu()

    print('Prev Loss:', crit(y_pred, y, w).item())

    model.train()
    for epoch in range(10000):
        optimizer.zero_grad()

        pred = model(sym_data).squeeze(-1)
        loss = crit(pred, sym_target, sym_weights)

        print(f'Epoch: {epoch + 1:6d} Loss {loss.detach().cpu().item():.7f}', end='\r')

        loss.backward()
        optimizer.step()
        sched.step()

    model.eval()
    with torch.no_grad():
        optimizer.zero_grad()

        y_pred = model(sym_data).squeeze(-1).detach().cpu()
        y = sym_target.detach().cpu()
        w = sym_weights.detach().cpu()

    print()
    print([abs(a - b) for a, b in zip(y_pred.numpy(), y.numpy()) if abs(round(a - b)) > 0])
    print('Errors', sum([abs(round(a - b)) > 0 for a, b in zip(y_pred.numpy(), y.numpy())]), 'out of', y_pred.shape[0])
    print('Loss:', crit(y_pred, y, w).item())
    print('Coef:', model.c.item())

if __name__ == '__main__':
    main()


import logging

from helpers.config import CONFIG
from helpers.odoo_api import OdooAPI
from update_meal_voucher_products.categories import MEAL_VOUCHER_CATEGORIES

def get_produts_that_should_be_mv(odoo_api):
    entities = odoo_api.search_read(
        entity="product.template",
        cond=[
            ["sale_ok", "=", True],
            ["meal_voucher_ok", "=", False],
            ["categ_id", "in", MEAL_VOUCHER_CATEGORIES],
        ],
        fields=["id", "name"],
    )
    return entities

def set_products_mv(odoo_api, entities):
    odoo_api.update(
        entity="product.template",
        ids=[p["id"] for p in entities],
        fields={"meal_voucher_ok": True},
    )

def main():
    config = CONFIG.get(__name__)
    odoo_api = OdooAPI(
        config.odoo.url,
        config.odoo.db,
        config.odoo.user,
        config.odoo.password,
    )
    entities = get_produts_that_should_be_mv(odoo_api)
    if entities:
        set_products_mv(odoo_api, entities)
        logging.info(f"{len(entities)} products have been updated")
    else:
        logging.info("No product to update")


import os

basedir = os.path.abspath(os.path.dirname(__file__))
DATABASE = os.path.join(basedir, 'app.db')

MAX_CONTENT_LENGTH = 1024 * 1024

UPLOADS_DEFAULT_DEST = os.path.join(basedir, 'upload/')

SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE

SECRET_KEY = 'you-will-never-guess'

FLASKY_ADMIN = 'root@gmail.com'

SQLALCHEMY_TRACK_MODIFICATIONS = False


import category_encoders as ce
from .base import EncoderWrapper

class HashingEncoder(EncoderWrapper):
    def __init__(self, cat_vars, *args, **kwargs):
        super().__init__(
            cat_vars=cat_vars,
            encoder_class=ce.hashing.HashingEncoder,
            suffix='hse',
            *args, **kwargs
        )