from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response
from api.models import RideOffer
from api.models import RideSeek
from api.models import Search
from api.models import Filter
from api.serializers import RideOfferSerializer
from api.serializers import RideSeekSerializer
from api.serializers import SearchSerializer
from api.serializers import FilterSerializer
from django_filters import rest_framework as filters

# Create your views here.

class RideOfferFilter(filters.FilterSet):
    class Meta:
        model = RideOffer
        fields = {
            'from_u' : ['icontains'],
            'to_u' : ['icontains'],
            'when_u' : ['lte', 'gte'],
            'cost_u' : ['lte'],
        }

class RideOfferViewSet(viewsets.ModelViewSet):
    queryset = RideOffer.objects.all()
    serializer_class = RideOfferSerializer
    filterset_class = RideOfferFilter
    #def list(self, request):   inherets this from modelviewset

class RideSeekFilter(filters.FilterSet):
    class Meta:
        model = RideSeek
        fields = {
            'from_u' : ['icontains'],
            'to_u' : ['icontains'],
            'when_u' : ['lte', 'gte'],
        }

class RideSeekViewSet(viewsets.ModelViewSet):
    queryset = RideSeek.objects.all()
    serializer_class = RideSeekSerializer
    filterset_class = RideSeekFilter

class SearchViewSet(viewsets.ModelViewSet):
    queryset = Search.objects.all()
    serializer_class = SearchSerializer

class FilterViewSet(viewsets.ModelViewSet):
    queryset = Filter.objects.all()
    serializer_class = FilterSerializer


import glob
import os
import warnings
import textract
from flask import (Flask, json, Blueprint, jsonify, redirect, render_template, request,
                   url_for)
from gensim.summarization import summarize
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.neighbors import NearestNeighbors
from werkzeug import secure_filename

import pdf2text as pdf
import PyPDF2

class ResultElement:
    def __init__(self, rank, filename):
        self.rank = rank
        self.filename = filename

def getfilepath(loc):
    temp = str(loc)
    temp = temp.replace('\\', '/')
    return temp

def res(jobfile):
    Resume_Vector = []
    Ordered_list_Resume = []
    Ordered_list_Resume_Score = []
    LIST_OF_FILES = []
    LIST_OF_FILES_PDF = []
    LIST_OF_FILES_DOC = []
    LIST_OF_FILES_DOCX = []
    Resumes = []
    Temp_pdf = []
    os.chdir('./Original_Resumes')
    for file in glob.glob('**/*.pdf', recursive=True):
        LIST_OF_FILES_PDF.append(file)
    for file in glob.glob('**/*.doc', recursive=True):
        LIST_OF_FILES_DOC.append(file)
    for file in glob.glob('**/*.docx', recursive=True):
        LIST_OF_FILES_DOCX.append(file)

    LIST_OF_FILES = LIST_OF_FILES_DOC + LIST_OF_FILES_DOCX + LIST_OF_FILES_PDF


#!/usr/bin/env python3

import re
import os

SERIES_PAIRS = [
  ["throw_exception", False],
  ["throw_struct", False],
  ["throw_val", False],
  ["stripped.outcome_std_error", "outcome_std_error"],
  ["stripped.outcome_struct", "outcome_struct"],
  ["stripped.outcome_val", "outcome_val"],
  ["stripped.tls_error_struct", "tls_error_struct"],
  ["stripped.tls_error_val", "tls_error_val"],
  ["stripped.expected_struct", "expected_struct"],
  ["stripped.expected_val", "expected_val"],
  ["stripped.ref_struct", "ref_struct"],
  ["stripped.return_struct", "return_struct"],
  ["stripped.ref_val", "ref_val"],
  ["stripped.return_val", "return_val"],
  ["noexcept_abort", False],
  ["stripped.abort", "abort"],
]

COLOR_PAIRS = [
  ["1b9e77", "5EC2A4"],
  ["d95f02", "FF9F55"],
  ["7570b3", "CFCDEA"],
  ["e7298a", "F27DB9"],
  ["66a61e", "A6DE66"],
  ["e6ab02", "FFD45B"],
  ["a6761d", "E6B965"],
  ["666666", "C4C3C3"],
]

def pair_idx_to_color_pair(pair_idx):
    color_idx = pair_idx % len(COLOR_PAIRS)
    return COLOR_PAIRS[color_idx]

def build_property_mapping():
    ord = 0
    pair_idx = 0
    mapping = {}
    for pair in SERIES_PAIRS:
        color_pair = pair_idx_to_color_pair(pair_idx)
        mapping[pair[0]] = [ord, color_pair[0]]
        ord = ord + 1
        if pair[1]:
            mapping[pair[1]] = [ord, color_pair[1]]
            ord = ord + 1
        pair_idx = pair_idx + 1
    return mapping

PROPERTY_MAPPING = build_property_mapping()

class SeriesData(object):
    def __init__(self, elt_map):
        self.plat = elt_map["plat"]
        self.type = elt_map["type"]
        self.ord = PROPERTY_MAPPING[self.type][0]
        self.color = PROPERTY_MAPPING[self.type][1]
        self.eltMap = elt_map
        self.cmpTerm = elt_map["CmpTerm"]
        self.cost2ndNeutral = elt_map["Cost2ndNeutral"]
        self.cost1stError = elt_map["Cost1stError"]
        self.cost2ndError = elt_map["Cost2ndError"]
        self.cost1stCatch = elt_map["Cost1stCatch"]
        if "Cost2ndCatch" not in elt_map:
            print(elt_map)
            raise elt_map
        self.cost2ndCatch = elt_map["Cost2ndCatch"]

class SeriesTypeData(object):
    def __init__(self, seriesData):
        self.type = seriesData.type
        self.stack_type = seriesData.type.replace("stripped.","")
        self.ord = seriesData.ord
        self.color = seriesData.color
        self.plat_map = {seriesData.plat: seriesData}

def is_all_zeroes(series_type_data, case):
    return \
        (series_type_data.plat_map["Clang/x64"].eltMap[case] == "0") and \
        (series_type_data.plat_map["GCC/x64"].eltMap[case] == "0"  ) and \
        (series_type_data.plat_map["MSVC/x64"].eltMap[case] == "0" ) and \
        (series_type_data.plat_map["MSVC/x86"].eltMap[case] == "0" )

def make_graphs(tsv_name, out_name):
    data = {}
    with open(tsv_name, 'r') as fin:
        first = True
        for line in fin:
            if first:
                first = False
                headers = line.split(',')
                continue
            tmp = line.split(',')
            elt = {}
            for i in range(len(tmp)):
                elt[headers[i]] = tmp[i]
            seriesData = SeriesData(elt)
            if seriesData.ord not in data:
                data[seriesData.ord] = SeriesTypeData(seriesData)
            else:
                data[seriesData.ord].plat_map[seriesData.plat] = seriesData

    with open(out_name, 'w') as fout:
        spaces = "  "

        cases = [
            "CmpTerm",
            "Cost2ndNeutral",
            "Cost1stError",
            "Cost2ndError",
            "Cost1stCatch",
            "Cost2ndCatch",
        ]

        for case in cases:
            fout.write("var data_" + case + " = [\n")
            first = True
            for ord in sorted(data.keys()):
                if is_all_zeroes(data[ord], case):
                    continue
                if not first:
                    fout.write(spaces + "},\n")
                else:
                    first = False
                fout.write(spaces + "{\n")
                fout.write(spaces + "  type: 'bar',\n")
                fout.write(spaces + "  name: '" + data[ord].type + "',\n")
                fout.write(spaces + "  stack: '" + data[ord].stack_type + "',\n")
                fout.write(spaces + "  itemStyle: {color: '#" + data[ord].color + "'},\n"),
                if ord == len(data) - 1:
                    fout.write(spaces + "  barCategoryGap: '10%',\n")
                fout.write(spaces + "  data: [" +
                    data[ord].plat_map["Clang/x64"].eltMap[case] + "," +
                    data[ord].plat_map["GCC/x64"].eltMap[case] + "," +
                    data[ord].plat_map["MSVC/x64"].eltMap[case] + "," +
                    data[ord].plat_map["MSVC/x86"].eltMap[case] + "]\n")
            fout.write(spaces + "}\n")
            fout.write("];\n\n");

def main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        'tsv', help='name of tab seperated value file to analyze')
    parser.add_argument(
        'outputFile', help='output file to create that will hold graph snippets')
    args = parser.parse_args()
    make_graphs(args.tsv, args.outputFile)

if __name__ == '__main__':
    import sys
    if sys.version_info[0] < 3:
        raise Error("Must be using Python 3")
    exit(main())


#Acessar cd Projeto-integrador\Code paraa rodar o programa

import pygame, sys
from config import *
from level import Level
from game_data import levels
from overworld import Overworld
from UI import UI
from menu import *
from text import *
from UI import Screen_Text

pygame.init() #Necessário para inicializar o pygame
screen = pygame.display.set_mode((screen_width,screen_height)) #Permite a tela aparecer
pygame.display.set_caption("The Decay of Boros")
clock = pygame.time.Clock() #Inicializa a contagem dos quadros

class Game:
    def __init__(self):
        self.max_level = 3
        self.max_health = 100
        self.cur_health = 100
        self.overworld = Overworld(3,self.max_level,screen,self.create_level,self.create_text,self.display_text)
        self.status = 'overworld'

        self.ui = UI(screen)
        self.text_over = Screen_Text(screen)

    def create_level(self,current_level):
        self.level = Level(current_level,screen,self.create_overworld,self.change_health)
        self.status = 'level'

    def create_overworld(self,current_level,new_max_level):
        if new_max_level > self.max_level:
            self.max_level = new_max_level
        self.overworld = Overworld(current_level,self.max_level,screen,self.create_level,self.create_text,self.display_text)
        self.status = 'overworld'

    def create_text(self,current_level):
        self.text = Text(current_level,screen,self.create_level)
        self.status = 'text'

    def display_text(self):
        self.display = Text(self.display_surface)

    def change_health(self,amount):
        self.cur_health += amount

    def check_game_over(self):
        if self.cur_health <= 0:
            self.cur_health = 100
            self.max_level = 0
            self.overworld = Overworld(0,self.max_level,screen,self.create_level,self.create_text,self.display_text)
            self.status = 'overworld'

    def run(self):
        if self.status == 'overworld':
            self.overworld.run()
            self.text_over.show_text()
        elif self.status == 'text':
            self.text.run()
        else:
            self.level.run()
            self.ui.show_health(self.cur_health,self.max_health)
            self.check_game_over()

game = Game()

class menu():
    def __init__(self):
        self.running, self.playing = True, False
        self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False
        self.DISPLAY_W, self.DISPLAY_H = screen_width, screen_height
        self.display = pygame.Surface((self.DISPLAY_W,self.DISPLAY_H))
        self.window = pygame.display.set_mode(((self.DISPLAY_W,self.DISPLAY_H)))
        self.font_name = '8-BIT WONDER.TTF'
        #self.font_name = pygame.font.get_default_font()
        self.BLACK, self.WHITE = (0, 0, 0), (255, 255, 255)
        self.main_menu = MainMenu(self)
        self.options = OptionsMenu(self)
        self.credits = CreditsMenu(self)
        self.curr_menu = self.main_menu

    def game_loop(self):
        while self.playing:
            self.check_events()
            if self.BACK_KEY:
                self.playing= False
            self.display.fill(self.BLACK)
            game.run() #A função .run() permite a execução de outras funções, neste caso a função Level

            pygame.display.update()#Faz com que a tela apareça
            clock.tick(60) #Taxa de fps (quadros por segundo)
            self.reset_keys()

    def check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running, self.playing = False, False
                self.curr_menu.run_display = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    self.START_KEY = True
                if event.key == pygame.K_ESCAPE:
                    self.BACK_KEY = True
                if event.key == pygame.K_DOWN:
                    self.DOWN_KEY = True
                if event.key == pygame.K_UP:
                    self.UP_KEY = True

    def reset_keys(self):
            self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False

    def draw_text(self, text, size, x, y ):
        font = pygame.font.Font(self.font_name,size)
        text_surface = font.render(text, True, self.WHITE)
        text_rect = text_surface.get_rect()
        text_rect.center = (x,y)
        self.display.blit(text_surface,text_rect)

m = menu()

while m.running:# inicializa o processo do jogo e mantém ele rodando

    m.curr_menu.display_menu()
    m.game_loop()


print("Task 4.1")
from fractions import Fraction
a,b = 5,8
c,d = 9,6
ir_fr = Fraction(Fraction(a,b), Fraction(c,d))
print("irreducible fraction: ", ir_fr)
def gcd(a, b):
    if a > b: s = b
    else: s = a
    for i in range(1, s + 1):
        if((a%i==0)and(b%i==0)):
            gcd = i
    print(gcd)
gcd(ir_fr.numerator, ir_fr.denominator)

print("Task 4.2")
x = 1;
y = 1;
p1,p2 = 1,2
f1,f2 = 3,4
n1,n2 = 1,2
radius = 3
def point_in(px, py, radius, x, y):
    if ((x-px)**2+(y-py)**2)<=radius**2:
        print("POINT IS INSIDE")
    else:
        print("POINT IS OUTSIDE")
point_in(p1,p2,radius,x,y)
point_in(f1,f2,radius,x,y)
point_in(n1,n2,radius,x,y)

print("Task 5.1")
from fractions import Fraction
a,b = 5,4
c,d = 7,8
ir_f = Fraction(Fraction(a,b) - Fraction(c,d))
print("irreducible fraction: ", ir_f)
def gcd(a, b):
    if a > b: s = b
    else: s = a
    for i in range(1, s + 1):
        if((a%i==0)and(b%i==0)):
            gcd = i
    print(gcd)
gcd(ir_f.numerator, ir_f.denominator)

print("Task 5.2")
def div(a):
    for i in range(1, a+1):
        if a%i==0:
            print(i, end=" ")
        else: continue
n = int(input("Enter the number: "))
div(n)

print("\nTask 6.1")
def gcd(a, b):
    if a > b: s = b
    else: s = a
    for i in range(1, s + 1):
        if((a%i==0)and(b%i==0)):
            gcd = i
    return gcd
def lcm(a, b):
    lcm = (a*b)/gcd(a,b)
    print(lcm)
a = int(input("Enter the 1st number: "))
b = int(input("Enter the 2nd number: "))
print(gcd(a,b))
lcm(a,b)
print("\nTask 6.2")
a = float(input("First side: "))
b = float(input("Second side: "))
c = float(input("Third side: "))
d = float(input("Fourth side: "))
dia = float(input("Diagonal: "))
def quadl(a,b,c,d,dia):
    def heron_f(a,b,c):
        p=0.5*(a+b+c)
        return (p*(p-a)*(p-b)*(p-c))**0.5
    return heron_f(a,b,dia) + heron_f(c,d,dia)
print("The area of a quadliteral : ", quadl(a,b,c,d,dia))

print("\n Task7.1")
a = int(input("long base: "))
b = int(input("short base: "))
h = int(input("height: "))
t = int(input("leg: "))

print("Area:", triangleArea(a-b,h) + rectangleArea(b,h))

print("\nTask7.2")
def decToOct(n):
    return '{:010o}'.format(n)

a = int(input())
print(decToOct(a))

print("\nTask8.1")
def divByTheirD(n):
    ans = []
    for i in range(1,n+1):
        s = str(i)
        temp = True
        for j in s:
            if int(j) == 0:
                temp = False
            elif i % int(j) != 0:
                temp = False
        if temp:
            ans.append(i)
    return ans

n = int(input("n: "))
print(divByTheirD(n))

print("\nTask8.2")
def swapFirstLast(a):
    a[0],a[len(a)-1] = a[len(a)-1],a[0]
    return a

m = int(input("length of array: "))
A = []
for i in range(m):
    n = int(input("element of array: "))
    A.append(n)

print(A)
print(swapFirstLast(A))

print("\ntask9.1")
def sumOfDigits(n):
    s = str(n)
    sum = 0
    for i in s:
        sum += int(i)
    return sum

n = int(input("N: "))
sub = sumOfDigits(n)
ans = 0
while n > 0:
    ans += 1
    n -= sub

print(ans)

print("n\Taskl9.2")
def prdArr(n):
    prd = 1
    for i in n:
        prd *= i
    return prd

for i in range(3):
    a = random.sample(range(100), 15)
    print(a)
    print(prdArr(a))
    print(meanArr(a,sumArr(a)))

print("\nTask11.1")
def Twins(n):
    print([[i, i+2] for i in range(n, 2*n - 1)])

Twins(int(input()))

print("\n Task11.2")
B = int(input())
C = [[random.randrange(10) for i in range(A)] for j in range(B)]
for i, row in enumerate(C):
    max = min = 0
    for j, elem in enumerate(row):
        if elem > row[max]:
            max = j
        if elem < row[min]:
            min = j
    row[max], row[0] = row[0], row[max]
    row[min], row[-1] = row[-1], row[min]
print(C)

print("\n Task12.1")
def getSum(value):
    res = 1
    for i in range(2, int(value**0.5) + 1):
        if value % i == 0:
            res += i + value // i
    return res

for i in range(10, 10000):
    sum1 = getSum(i)
    sum2 = getSum(sum1)
    if sum2 == i and sum1 != sum2:
        print(i, sum1)

print("\n Task12.2")
def m(a, b, c):
    return 1/2(sqrt(2*b**2+2*c**2-a**2))

print("\nTask13.1")
num=int(input("enter number: "))
for num in range(num, 1000):
    sum1=0
    numcp=num
    if(num>=10 and num<100):
        while(num>0):
            digit=int(num%10)
            d2=digit*digit
            sum1=sum1+d2
            num=int(num/10)

    if(num>=100 and num<1000):
        while(num>0):
            digit=int(num%10)
            d2=digit*digit*digit
            sum1=sum1+d2
            num=int(num/10)
    if(numcp==sum1):
        print("angstrong number: ", sum1)


"""
The model definitions for the social app
"""

from pathlib import Path

from playhouse.dataset import DataSet

HERE = Path(__file__).parent

DEFAULT_DB_NAME = HERE / "social.db"

def get_dataset(filename=None, clear=False):
    """
    setup and return a database to use for the models

    :param filename: name of DB file, or ":memory:" for in=memory temp DB

    :param clear=False: Whether to clear out the old db and return an
                        empty one.

    :returns: PeeWee Dataset object
    """

    if filename == ":memory:":
        dataset = DataSet('sqlite:///:memory:')
    else:  # pragma: no cover (not used in tests)
        if filename is None:
            filename = DEFAULT_DB_NAME
        if clear:
            Path(filename).unlink(missing_ok=True)
        dataset = DataSet(f'sqlite:///{filename}')

    # note: limitations not implimented yet

    # * The ``Users`` table will have the following fields:
    #     * user_id (Primary Key, limited to 30 characters).
    #     * user_name (Limited to 30 characters).
    #     * user_last_name (Limited to 100 characters).
    #     * user_email.
    # * The ``Status`` table will have these fields:
    #     * status_id (Primary Key).
    #     * user_id (Foreign Key from the ``Users`` table).
    #     * status_text.

    # set up the user's table
    users = dataset['users']
    # insert a dummy record to get the table set up
    users.insert(user_id='temp',
                 user_name='ausername',
                 user_last_name='Example',
                 user_email='example@nothing.com')
    # create index to make user_id unique
    users.create_index(['user_id'], unique=True)
    # Delete the dummy record afterwards.
    users.delete(user_id='temp')

    statuses = dataset['statuses']
    # insert a dummy record to get the table set up
    statuses.insert(status_id='temp',
                    user_id='xxx',
                    status_text='an example status message')
    # create index to make status_id unique
    statuses.create_index(['status_id'], unique=True)
    # Delete the dummy record afterwards.
    statuses.delete(status_id='temp')

    return dataset

# class User(BaseModel):
#     """
#     Model for the users in the socialnetwork
#     """
#     user_id = pw.CharField(primary_key=True, max_length=30)
#     user_name = pw.CharField(max_length=30)
#     user_last_name = pw.CharField(max_length=100)
#     user_email = pw.CharField()

# class UserStatus(BaseModel):
#     """
#     Model for the status messages
#     """
#     status_id = pw.CharField(primary_key=True, max_length=30)
#     user_id = pw.ForeignKeyField(model=User,
#                                  field='user_id',
#                                  backref='status_messages',
#                                  on_delete='CASCADE',
#                                  )
#     status_text = pw.TextField()


# Author - Dylan Butterfield, CSE 111, 3:15PM Class

import random  # <- global

def main():
    make_sentence(0, "past")

# 1. Return a randomly chosen determiner based on quantity
def get_determiner(quantity):  # <- parameter
    if quantity == 1:
        words = ["a", "one", "the"]  # <- arguments
    else:
        words = ["some", "many", "the"]
    return random.choice(words)

# 2. Return a randomly chosen noun based on quantity
def get_noun(quantity):  # <- parameter
    if quantity == 1:
        words = ["bird", "boy", "car", "cat", "child",  # <- arguments
                 "dog", "girl", "man", "rabbit", "woman"]
    else:
        words = ["birds", "boys", "cars", "cats", "children",
                 "dogs", "girls", "men", "rabbits", "women"]
    return random.choice(words)

# 3. Return a randomly chosen verb based on quantity and tense
def get_verb(quantity, tense):  # <- parameter
    if tense == "past":
        if quantity == 1:
            words = ["laughed", "ate", "drank",  # <- arguments
                     "ran", "walked", "thought", "wrote"]
        else:
            words = ["laughed", "ate", "drank",
                     "ran", "walked", "thought", "wrote"]
    elif tense == "present":
        if quantity == 1:
            words = ["laughs", "eats", "drinks",
                     "runs", "walks", "thinks", "writes"]
        else:
            words = ["laugh", "eat", "drink", "run", "walk", "think", "write"]
    elif tense == "future":
        if quantity == 1:
            words = ["will laugh", "will eat", "will drink",
                     "will run", "will walk", "will think", "will write"]
        else:
            words = ["will laugh", "will eat", "will drink",
                     "will run", "will walk", "will think", "will write"]
    else:
        words = []
    return random.choice(words)

# 4. Build and return a sentence - helps create sentence
def make_sentence():  # <- parameter
    quantity = random.choice([1, 2])  # <- arguments
    noun = get_noun(quantity)
    verb_tense = random.choice(["past", "present", "future"])
    verb = get_verb(quantity, verb_tense)
    determiner = get_determiner(quantity)
    sentence = (f"{determiner.capitalize()} {noun} {verb}.")
    return sentence

# 5. Generates and prints six sentences
def main():  # <- parameter
    for i in range(6):
        print(make_sentence())

# 6. gets a preposition to use
def get_preposition(quantity):  # <- parameter
    if quantity == 1:
        words = ["about", "above", "across", "after", "along",  # <- arguments
                 "around", "at", "before", "behind", "below",
                 "beyond", "by", "despite", "except", "for",
                 "from", "in", "into", "near", "of",
                 "off", "on", "onto", "out", "over",
                 "past", "to", "under", "with", "without"]
    return random.choice(words)

# 7. builds a prepositional phrase
def get_prepositional_phrase(quantity):  # <- parameter
    get_preposition()
    get_determiner(quantity)
    get_noun(quantity)
    return '[prepositional phrase]'

# 8. Allows main to be called so 6 results can be printed
if __name__ == '__main__':
    main()

# CODE MAP
"""
1. Return a randomly chosen determiner based on quantity
2. Return a randomly chosen noun based on quantity
3. Return a randomly chosen verb based on quantity and tense
4. Build and return a sentence - helps create sentence
5. Generates and prints six sentence
6. Gets a preposition to use
7. Builds a prepositional phrase
8. Allows main to be called so 6 results can be printed
"""


import stripe
from django.conf import settings
# Create your views here.
from django.shortcuts import redirect, render

def home(request):
    template_name = 'payments/pages/home.html'
    stripe.api_key = settings.STRIPE_SECRET_KEY
    return render(request, template_name)

def charge(request):
    if request.method == 'POST':
        checkout_session = stripe.checkout.Session.create(
            line_items=[
                {
                    'price': 'price_1MCqakASQv92CGV2YGc5bOYM',
                    'quantity': 1,
                },
            ],
            mode='payment',
            success_url='http://localhost:8000',
            cancel_url='http://localhost:8000',
        )
        return redirect(checkout_session.url, code=303)


import json
from pathlib import Path

class PathEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Path):
            return str(obj)
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, obj)


#!/usr/bin/env python

import os

from flask_script import Manager, Shell, Server
from flask_script.commands import ShowUrls, Clean
from strabo.app import create_app
from strabo.models import db, User

# default to dev config
env = os.environ.get('STRABO_ENV', 'dev')
app = create_app('strabo.settings.%sConfig' % env.capitalize())

HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')

manager = Manager(app)

def _make_context():
    """Return context dict for a shell session so you can access
       app, db, and the User model by default.
    """
    return {'app': app, 'db': db, 'User': User}

@manager.command
def test():
    """Run the tests."""
    import pytest
    exit_code = pytest.main([TEST_PATH, '--verbose'])
    return exit_code

@manager.command
def createdb():
    """ Creates a database with all of the tables defined in
        your SQLAlchemy models
    """
    db.create_all()

manager.add_command("server", Server())
manager.add_command("urls", ShowUrls())
manager.add_command("clean", Clean())
# Creates a python REPL with several default imports in the context of the app
manager.add_command('shell', Shell(make_context=_make_context))

if __name__ == "__main__":
    manager.run()


#!/usr/bin/env python

from fabric.api import run
from cloudify import ctx

def retrieve_file_content(file_name):
    ctx.logger.info("In retrieve_file_content file_name is {0} ...".format(file_name))
    command = "cat {0}".format(file_name)
    ctx.logger.info("Command is {0}".format(command))
    curr_output = run(command)
    ctx.logger.info("Command output is {0}".format(curr_output))
    ctx.instance.runtime_properties[file_name] = curr_output
    ctx.logger.info("Command output is stored in rt.{0} {1}".format(file_name, curr_output))
    ctx.logger.info("End of retrieve_file_content ...")

# https://github.com/cloudify-examples/clearwater-nfv-blueprint/blob/e004a11122398f1b38f3e5187362b25059dd4aa2/types/clearwater.yaml
#https://github.com/cloudify-examples/simple-kubernetes-blueprint/blob/a5ea7c3a81241f0350d7c25112bdfe930b7c5384/imports/kubernetes.yaml

#ssh -i ~/.ssh/nec_aws15_11.pem -o 'IdentitiesOnly yes' centos@13.125.3.21

#cfy exe start execute_operation -d $dep -p operation=utils.get_file_content --allow-custom-parameters -p node_ids=CentOS7
#cfy exe start execute_operation -d $dep -p operation=utils.get_file_content --allow-custom-parameters -p node_ids=CentOS7 -p "{'operation_kwargs':{'task_properties':{'file_name':'/home/centos/111.222'}}}" -p allow_kwargs_override=true
#export file_name=/home/centos/111.222
#cfy exe start execute_operation -d $dep -p operation=utils.get_file_content --allow-custom-parameters -p node_ids=CentOS7 -p "{'operation_kwargs':{'task_properties':{'file_name':'${file_name}'}}}" -p allow_kwargs_override=true


# multiAgents.py
# --------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
#
# Authors: Danny Lu, Shohei Etzel
# Class: University of Oregon, CIS 471/571: Introduction to Artificial Intelligence

from util import manhattanDistance
from game import Directions
import random
import util

from game import Agent

class ReflexAgent(Agent):
    """
    A reflex agent chooses an action at each choice point by examining
    its alternatives via a state evaluation function.

    The code below is provided as a guide.  You are welcome to change
    it in any way you see fit, so long as you don't touch our method
    headers.
    """

    def getAction(self, gameState):
        """
        You do not need to change this method, but you're welcome to.

        getAction chooses among the best options according to the evaluation function.

        Just like in the previous project, getAction takes a GameState and returns
        some Directions.X for some X in the set {NORTH, SOUTH, WEST, EAST, STOP}
        """
        # Collect legal moves and successor states
        legalMoves = gameState.getLegalActions()

        # Choose one of the best actions
        scores = [self.evaluationFunction(
            gameState, action) for action in legalMoves]
        bestScore = max(scores)
        bestIndices = [index for index in range(
            len(scores)) if scores[index] == bestScore]
        # Pick randomly among the best
        chosenIndex = random.choice(bestIndices)

        "Add more of your code here if you want to"

        return legalMoves[chosenIndex]

    def evaluationFunction(self, currentGameState, action):
        """
        Design a better evaluation function here.

        The evaluation function takes in the current and proposed successor
        GameStates (pacman.py) and returns a number, where higher numbers are better.

        The code below extracts some useful information from the state, like the
        remaining food (newFood) and Pacman position after moving (newPos).
        newScaredTimes holds the number of moves that each ghost will remain
        scared because of Pacman having eaten a power pellet.

        Print out these variables to see what you're getting, then combine them
        to create a masterful evaluation function.
        """
        # Useful information you can extract from a GameState (pacman.py)
        successorGameState = currentGameState.generatePacmanSuccessor(action)
        newPos = successorGameState.getPacmanPosition()
        newFood = successorGameState.getFood()
        newGhostStates = successorGameState.getGhostStates()
        newScaredTimes = [
            ghostState.scaredTimer for ghostState in newGhostStates]

        "*** YOUR CODE HERE ***"

        distList = []
        foodList = currentGameState.getFood().asList()
        posList = list(successorGameState.getPacmanPosition())
        negINF = -float("inf")

        # trivial case: action is stop
        if action == 'Stop':
            return negINF

        # otherwise, check states for if a "not scared" ghost is at the same position as Pac-Man
        for state in newGhostStates:
            if state.getPosition() == tuple(posList) and state.scaredTimer is 0:
                return negINF

        # if not, use manhattan heuristic to determine closest food pellet
        for dot in foodList:
            distList.append(-1 * manhattanDistance(
                (dot[0], dot[1]), (posList[0], posList[1])))
        return max(distList)
        # return successorGameState.getScore()

def scoreEvaluationFunction(currentGameState):
    """
    This default evaluation function just returns the score of the state.
    The score is the same one displayed in the Pacman GUI.

    This evaluation function is meant for use with adversarial search agents
    (not reflex agents).
    """
    return currentGameState.getScore()

class MultiAgentSearchAgent(Agent):
    """
    This class provides some common elements to all of your
    multi-agent searchers.  Any methods defined here will be available
    to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.

    You *do not* need to make any changes here, but you can if you want to
    add functionality to all your adversarial search agents.  Please do not
    remove anything, however.

    Note: this is an abstract class: one that should not be instantiated.  It's
    only partially specified, and designed to be extended.  Agent (game.py)
    is another abstract class.
    """

    def __init__(self, evalFn='scoreEvaluationFunction', depth='2'):
        self.index = 0  # Pacman is always agent index 0
        self.evaluationFunction = util.lookup(evalFn, globals())
        self.depth = int(depth)

class MinimaxAgent(MultiAgentSearchAgent):
    """
    Your minimax agent (question 2)
    """

    def getAction(self, gameState):
        """
        Returns the minimax action from the current gameState using self.depth
        and self.evaluationFunction.

        Here are some method calls that might be useful when implementing minimax.

        gameState.getLegalActions(agentIndex):
        Returns a list of legal actions for an agent
        agentIndex=0 means Pacman, ghosts are >= 1

        gameState.generateSuccessor(agentIndex, action):
        Returns the successor game state after an agent takes an action

        gameState.getNumAgents():
        Returns the total number of agents in the game

        gameState.isWin():
        Returns whether or not the game state is a winning state

        gameState.isLose():
        Returns whether or not the game state is a losing state
        """
        "*** YOUR CODE HERE ***"

        # PACMAN AGENT
        def max_agent(gameState, current_depth, agent):
            pacman_moves = gameState.getLegalActions(agent)
            if pacman_moves == None: # No more possible moves for PACMAN
                return self.evaluationFunction(gameState)

            max_value = [float("-inf"), 'Stop'] # Initialize max_value

            for move in pacman_moves:

                temp_value = dispatch(gameState.generateSuccessor(agent, move), current_depth, agent+1)

                if type(temp_value) == list:
                    temp_value = temp_value[0]
                elif type(temp_value) != list:
                    temp_value = temp_value
                if temp_value > max_value[0]:
                    max_value = [temp_value, move]

            return max_value

        # GHOST AGENT
        def min_agent(gameState, current_depth, agent):
            ghost_moves = gameState.getLegalActions(agent)
            if ghost_moves == None: # No more possible moves for GHOST
                return self.evaluationFunction(gameState)

            min_value = [float("inf"),'Stop'] # Initialize min_value

            for move in ghost_moves:

                temp_value = dispatch(gameState.generateSuccessor(agent, move), current_depth, agent + 1)

                if type(temp_value) == list:
                    temp_value = temp_value[0]
                elif type(temp_value) != list:
                    temp_value = temp_value
                if temp_value < min_value[0]:
                    min_value = [temp_value, move]

            return min_value

        # DISPATCH FUNCTION: Calls min_agent, and max_agent
        def dispatch(gameState, current_depth, agent):
            agents = gameState.getNumAgents()
            if agent >= agents:
                current_depth -= 1
                agent = 0
            if current_depth == 0 or gameState.isWin() or gameState.isLose():
                return self.evaluationFunction(gameState)
            elif agent == 0:
                return max_agent(gameState, current_depth, agent)
            else:
                return min_agent(gameState, current_depth, agent)

        return dispatch(gameState, self.depth, 0)[1]

class AlphaBetaAgent(MultiAgentSearchAgent):
    """
    Your minimax agent with alpha-beta pruning (question 3)
    """

    def getAction(self, gameState):
        """
        Returns the minimax action using self.depth and self.evaluationFunction
        """
        "*** YOUR CODE HERE ***"
        # PACMAN AGENT
        def max_agent(gameState, current_depth, agent, alpha, beta):
            pacman_moves = gameState.getLegalActions(agent)
            if pacman_moves == None: # No more possible moves for PACMAN
                return self.evaluationFunction(gameState)

            max_value = [float("-inf"), 'Stop']

            for move in pacman_moves:

                temp_value = dispatch(gameState.generateSuccessor(agent, move), current_depth, agent + 1, alpha, beta)

                if type(temp_value) == list:
                    temp_value = temp_value[0]
                elif type(temp_value) != list:
                    temp_value = temp_value
                if temp_value > max_value[0]:
                    max_value = [temp_value, move]
                if temp_value > beta:
                    return [temp_value, move]
                alpha = max(temp_value, alpha)

            return max_value

        # GHOST AGENT
        def min_agent(gameState, current_depth, agent, alpha, beta):
            ghost_moves = gameState.getLegalActions(agent)
            if ghost_moves == None: # No more possible moves for GHOST
                return self.evaluationFunction(gameState)

            min_value = [float("inf"), 'Stop']

            for move in ghost_moves:

                temp_value = dispatch(gameState.generateSuccessor(agent, move), current_depth, agent + 1, alpha, beta)

                if type(temp_value) == list:
                    temp_value = temp_value[0]
                elif type(temp_value) != list:
                    temp_value = temp_value
                if temp_value < min_value[0]:
                    min_value = [temp_value, move]
                if temp_value < alpha:
                    return [temp_value, move]
                beta = min(temp_value, beta)

            return min_value

        # DISPATCH FUNCTION: Calls min_agent, and max_agent
        def dispatch(gameState, current_depth, agent, alpha, beta):
            agents = gameState.getNumAgents()
            if agent >= agents:
                current_depth -= 1
                agent = 0
            if current_depth == 0 or gameState.isWin() or gameState.isLose():
                return self.evaluationFunction(gameState)
            elif agent == 0:
                return max_agent(gameState, current_depth, agent, alpha, beta)
            else:
                return min_agent(gameState, current_depth, agent, alpha, beta)

        return dispatch(gameState, self.depth, 0, float("-inf"), float("inf"))[1]

class ExpectimaxAgent(MultiAgentSearchAgent):
    """
      Your expectimax agent (question 4)
    """

    def getAction(self, gameState):
        """
        Returns the expectimax action using self.depth and self.evaluationFunction

        All ghosts should be modeled as choosing uniformly at random from their
        legal moves.
        """
        "*** YOUR CODE HERE ***"
        curDepth, curIndex = 0, 0
        retAction = self.value(gameState, curIndex, curDepth)
        return retAction[0]

    def value(self, gameState, curIndex, curDepth):
        # trivial checks
        if curIndex >= gameState.getNumAgents():
            curIndex = 0
            curDepth += 1

        if curDepth == self.depth:
            return self.evaluationFunction(gameState)

        # if Pac-Man node, want to find Max; if not, want to find probabilities
        if curIndex == self.index:
            # isMax == True
            return self.expMax(True, gameState, curIndex, curDepth)
        else:
            # isMax == False
            return self.expMax(False, gameState, curIndex, curDepth)

    def expMax(self, isMax, gameState, curIndex, curDepth):
        if not gameState.getLegalActions(curIndex):
            return self.evaluationFunction(gameState)

        # set initial value
        # empty action; 0 for exp and negative infinity for Max
        v = ["", 0] if isMax is False else ("", -float("inf"))

        # set probabilities (for use in exp)
        expProb = 1.0 / len(gameState.getLegalActions(curIndex))

        # recursively update v values for legal action available
        for action in gameState.getLegalActions(curIndex):
            retVal = self.value(gameState.generateSuccessor(
                curIndex, action), curIndex + 1, curDepth)
            if type(retVal) is tuple:
                retVal = retVal[1]
            if isMax == False:
                v[0] = action
                v[1] += retVal * expProb
            elif isMax == True:
                vMax = max(v[1], retVal)

                if vMax is not v[1]:
                    v = (action, vMax)

        retVal = tuple(v) if isMax == False else v

        return retVal

def betterEvaluationFunction(currentGameState):
    """
    Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
    evaluation function (question 5).

    DESCRIPTION:
    FACTORS WE CONSIDERED (for each state):
     - Current game score
     - Number of food dots left
     - Distance to ghosts and their state (scared, not scared)
     - Distance to closest and second closest food

    WHY:
     - CURRENT GAME SCORE is useful for implicitly incentivizing PacMan (to not bump into ghosts, to eat food, to eat scared ghosts). A times 10 multiplier was added to this baseline value to increase its importance.

     - From there, we added incentizes and multipliers to prioritize certain things:
        - FOOD LEFT: A negative incentive was added for the amount of food left, incentivizing Pac-Man to eat food whenever possibe. A times 10 multiplier was added to this value as well.

        - GHOSTS 3 blocks or closer are a large threat and should be avoided at all costs; increasingly larger negative incentives were added to ensure Pac-Man would not die.

        - SCARED GHOSTS 3 blocks or closer are a great opportunity to gain points; a set positive incentive was added for Pac-Man to go chase scared ghosts.

        - CLOSEST FOOD: The two closest foods were both considered to incentivize Pac-Man to travel towards food. We originally only considered the closest food, but ran into problems when one food dot was isolated. In this case, Pac-Man would not eat it, as it would greatly increase the closestFood distance if he did. There was a larger incentive to sit right next to the dot than there was to eat it! Therefore, we decided to add the second closest food as well, to help decrease the effects of a single isolated food dot on the overall evaluation.
    """
    "*** YOUR CODE HERE ***"
    ghostList = currentGameState.getGhostStates()
    foodList = currentGameState.getFood().asList()
    posList = list(currentGameState.getPacmanPosition())

    distToFoodList = []
    ghostInfo = []                          # 2D array: [dist, isScared]
    distToCapsuleList = []
    score = 0

    for state in ghostList:                 # get info for all ghosts
        if state.scaredTimer is not 0:      # scared ghost
            ghostInfo.append([0, 1])
        else:                               # not scared ghost
            ghostXY = state.getPosition()
            manDist = manhattanDistance(
                (ghostXY[0], ghostXY[1]), (posList[0], posList[1]))
            ghostInfo.append([manDist, 0])

    for dot in foodList:                    # get manhattan dist for all food dots
        distToFoodList.append(-1 * manhattanDistance(
            (dot[0], dot[1]), (posList[0], posList[1])))

    # scoring logic
    closestFood = 0
    closestFood2 = 0
    closestFood3 = 0
    ghostScore = 0
    curScore = currentGameState.getScore()
    # incentivize with manhattan distance values for two closest food dots

    temp = distToFoodList
    if temp:
        closestFood = max(temp)
        temp.remove(closestFood)
        if temp:
            closestFood2 = max(temp)

    # positive scores for scared ghosts nearby, (increasing) negative scores for regular ghosts nearby

    for ghost in ghostInfo:
        if ghost[0] == 3 and ghost[1] == 0:  # ghost within 3 spots = get away!
            ghostScore -= 25
        elif ghost[0] == 2 and ghost[1] == 0:
            ghostScore -= 50
        elif ghost[0] <= 1 and ghost[1] == 0:
            ghostScore -= 100
        elif ghost[0] <= 1 and ghost[1] == 1:
            ghostScore += 100

    return closestFood + 2 * closestFood2 + ghostScore + 10 * curScore - 10 * len(foodList)

# Abbreviation
better = betterEvaluationFunction


'''
< 성적이 낮은 순서로 학생 출력하기 >
'''
n = int(input())
arr = []
for _ in range(n):
    name, score = input().split()
    arr.append((name, int(score)))

arr.sort(key = lambda student : student[1])
for student in arr:
    print(student[0], end = " ")


from self_stack import *
import re

def calcualte_postfix_string(string): # no parentheses in the string
    '''
    :param string: e.g. '2 3 + 5 *'
    :return: the calculation value
    '''
    operator_library={
        '+':lambda x,y:x+y,
        '-':lambda x,y:y-x,
        '*':lambda x,y:x*y,
        '/':lambda x,y:y/x,
        '//': lambda x,y:y//x,
        '%':lambda x,y:y%x
    }
    string=string.strip()
    string=re.sub(' +',' ',string)
    op_list=string.split(' ')
    stack=Stack()
    while op_list:
        current_char=op_list.pop(0)
        if current_char in operator_library.keys():
            temp1=stack.pop()
            temp2=stack.pop()
            stack.push(operator_library[current_char](temp1,temp2))
            # print(f'{current_char},{temp1},{temp2}')
        else:
            current_char=int(current_char)
            stack.push(current_char)
    if len(stack)!=1:
        print('Length of the stack is not 1.')
    return stack.pop()

def calcualte_infix_string(string): # include the parentheses and others
                                    # spaces needed
    separator_library={
        ')':'(',
        ']':'[',
        '}':'{'
    }
    operator_library = {
        '+': lambda x, y: x + y,
        '-': lambda x, y: y - x,
        '*': lambda x, y: x * y,
        '/': lambda x, y: y / x,
        '//': lambda x, y: y // x,
        '%': lambda x, y: y % x
    }
    string=string.strip()
    string=re.sub(' +',' ',string)
    op_list=string.split(' ')
    # print(op_list)
    stack=Stack()
    while op_list:
        current_char=op_list.pop(0)
        # print(current_char)
        if current_char in separator_library.keys():
            target_char=separator_library[current_char]
            temp_list=[]
            operator=None
            while stack.peek() != target_char:
                temp=stack.pop()
                if temp in operator_library.keys():
                    operator=temp
                else:
                    temp_list.append(temp)
            stack.pop()
            stack.push(operator_library[operator](temp_list[0],temp_list[-1]))
            # print(f'{operator},{temp_list}')
        else:
            try:
                stack.push(int(current_char))
            except:
                stack.push(current_char)
    if len(stack)>1:
        temp_list = []
        operator = None
        while not stack.is_empty():
            temp = stack.pop()
            if temp in operator_library.keys():
                operator = temp
            else:
                temp_list.append(temp)
        return operator_library[operator](temp_list[0],temp_list[-1])
    elif stack.is_empty():
        return 0
    else:
        return stack.pop()

def calcualte_infix_string_without_spaces(string):
    number_list=[str(i) for i in range(0,10)]
    new_string=''
    for each_char_index in range(len(string)-1):
        if string[each_char_index] in number_list and string[each_char_index+1] in number_list:
            new_string+=string[each_char_index]
        elif string[each_char_index]=='/' and string[each_char_index+1]=='/':
            new_string+=string[each_char_index]
        else:
            new_string+=string[each_char_index]
            new_string+=' '
    new_string+=string[-1]
    return calcualte_infix_string(new_string)

# TESTING
# string=' 12   13 4 5 + + 10 -  7 8 * / +'
# print(calcualte_postfix_string(string))
# string='[ ( { 2 // 1 } + 5 )  * ( 5 - 3 ) ] * 3'
# print(calcualte_infix_string(string))
string= '[({2//1}+5)*(5-3)]*3'
print(calcualte_infix_string_without_spaces(string))


import os
import sys
from loggermodule import logger_test
import DriveFunctions as DF
from ConfigParser import RawConfigParser

def CreateClientDictionary():
       interim_dict=configparse()
       text=interim_dict.values().pop()

       text=text.split(":{")
       testtext="{"+text[1]
       testtext=eval(testtext)
       dictionary={}

       dictionary[text[0]]=testtext
       logger_test.info("url of sheet which we are hitting %s"%dictionary)
       return dictionary
def configparse():

             parser = RawConfigParser()
             parser.read('accounts_config.ini')
             account_details={}
             for section_name in parser.sections():
                   k=parser.items(section_name)
                   adder_part=":{'NOMBRE':'%s'}"%section_name
                   url=str(k[0][1])+adder_part
                   client_name=section_name
                   account_details[client_name]=url
             return account_details
def client():
     ClientDictionary = CreateClientDictionary()
     logger_test.info("URL from which we are getting list of accounts:%s"%ClientDictionary)
     diclient_temp = {}
     for client in ClientDictionary:
        gc = DF.ConnectToDrive()
        logger_test.info("Connected to google drive\n")
        libro = gc.open_by_url(client)
        sheet=libro.worksheet(ClientDictionary[client]['NOMBRE'])
        diclient_temp= sheet.get_all_records()
        Destino_temp = client
     return Destino_temp,diclient_temp
def creator():
      current_dir=os.getcwd()
      parser = RawConfigParser()
      parser.read('accounts_config.ini')
      client_name=parser.sections().pop()
      v,k=client()
      k=[i['ACCOUNT_ID'] for i in k]
      m=parser.items(client_name)

      os.system("mkdir -p YamlFiles")
      #os.chdir("YamlFiles/")
      for i in k:
          f=open("YamlFiles/googleads_%s.yaml"%i,'w+')
          f.write("adwords:\n")
          f.write("  developer_token: %s\n"%m[1][1])
          f.write("  user_agent: %s\n"%m[2][1])
          f.write("  client_id: %s\n"%m[3][1])
          f.write("  client_secret: %s\n"%m[4][1])
          f.write("  refresh_token: %s\n"%m[5][1])
          f.write("  client_customer_id: %s"%i)
          f.close()

if __name__=="__main__":
      creator()


import fnmatch
import os
import py_compile
from os.path import join as _j

from RoundBox.conf.project_settings import settings
from RoundBox.core.cliparser.base import BaseCommand, CommandError
from RoundBox.core.cliparser.utils import signalcommand

class Command(BaseCommand):
    help = "Compile python bytecode files for the project."

    requires_system_checks = []

    def add_arguments(self, parser) -> None:
        """

        :param parser:
        :return:
        """
        parser.add_argument(
            '--path',
            '-p',
            action='store',
            dest='path',
            help='Specify path to recurse into',
        )

    @signalcommand
    def handle(self, *args, **options) -> None:
        """

        :param args:
        :param options:
        :return:
        """
        project_root = options["path"]
        if not project_root:
            project_root = getattr(settings, 'BASE_DIR', None)

        verbosity = options["verbosity"]
        if not project_root:
            raise CommandError(
                "No --path specified and settings.py does not contain BASE_DIR"
            )

        for root, dirs, filenames in os.walk(project_root):
            for filename in fnmatch.filter(filenames, '*.py'):
                full_path = _j(root, filename)
                if verbosity > 1:
                    self.stdout.write("Compiling %s...\n" % full_path)
                py_compile.compile(full_path)


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

from django.db import models, migrations
import sorl.thumbnail.fields
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('profiles', '0002_auto_20150812_1453'),
    ]

    operations = [
        migrations.CreateModel(
            name='Module',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=128)),
                ('tag', models.CharField(max_length=10)),
                ('description', models.TextField(max_length=1000)),
                ('start', models.DateField(default=datetime.date.today)),
                ('accommodation', models.TextField(max_length=1000, blank=True)),
                ('module_map', models.TextField(max_length=1000, blank=True)),
                ('pic', sorl.thumbnail.fields.ImageField(default=b'module_img/default.jpg', upload_to=b'module_img')),
                ('coordinator', models.OneToOneField(to='profiles.Academic')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


#! /usr/bin/env python
#-*- coding: UTF-8 -*-
from math import atan2

import rospy
import tf
# ros include
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist, Pose, Point, PoseStamped, TwistStamped, TwistWithCovarianceStamped
from gazebo_msgs.srv import SetModelState, GetModelState, GetModelStateRequest, GetModelStateResponse
from gazebo_msgs.msg import ModelState
from tf.transformations import euler_from_quaternion, quaternion_from_euler
from turbot_rl.msg import Reward, Acc
from nav_msgs.msg import Odometry
# from common.world import World
from world import World
import random
import numpy as np
import math
import angles

# from pykalman import KalmanFilter

class Game:

    def __init__(self, model_name, game_name):
        """
            initialize
        """

        # self.talker_node = rospy.init_node('talker', anonymous=True)
        self.model_name = model_name
        self.game_name = game_name

        self.odom = Odometry()
        self.pose = Pose()
        self.scan = LaserScan()

        self.crash_limit = 0.2

        self.start_flag = False

        self.target_x = 10
        self.target_y = 10

        self.height = 0.0

        self.step_count = 0

        self.rate = rospy.Rate(10)

        ## env.space
        self.state_num = 40
        self.action_num = 2
        self.observation_space = np.empty(self.state_num)
        self.action_space = np.empty(self.action_num)
        ##

        # initialize world
        if (game_name == "EMPTY"):
            self.safe_space = [[0, 0], [8, 0]]
            self.safe_radius = [1.0, 0.8]
            self.target_distance = 8
            self.wall_rate = 0
            self.cylinder_num = [0, 0]

        if (game_name == "TRAIN"):
            self.safe_space = [[0, 0], [8, 0]]
            self.safe_radius = [1.0, 0.8]
            self.target_distance = 8
            self.wall_rate = 0.8
            self.cylinder_num = [70, 100]

        if (game_name == "TEST1"):
            self.safe_space = [[0, 0], [8, 0]]
            self.safe_radius = [1.0, 0.8]
            self.target_distance = 8
            self.wall_rate = 0.5
            self.cylinder_num = [5, 50]

        if (game_name == "TEST2"):
            self.safe_space = [[0, 0], [8, 0]]
            self.safe_radius = [1.0, 0.8]
            self.target_distance = 8
            self.wall_rate = 0.8
            self.cylinder_num = [50, 100]

        if (game_name == "TEST3"):
            self.safe_space = [[0, 0], [8, 0]]
            self.safe_radius = [1.0, 0.8]
            self.target_distance = 8
            self.wall_rate = 0.8
            self.cylinder_num = [100, 150]

        if (game_name == "TEST4"):
            self.safe_space = [[0, 0], [8, 0]]
            self.safe_radius = [1.0, 0.8]
            self.target_distance = 8
            self.wall_rate = 0.8
            self.cylinder_num = [150, 200]

        if (game_name == "CUSTOMIZED"):
            self.safe_space = [[0, 0], [8, 0]]
            self.safe_radius = [1.0, 0.8]
            self.target_distance = 8
            self.wall_rate = 0.8
            self.cylinder_num = [150, 200]

        self.world = World(self.safe_space, self.safe_radius, wall_rate=self.wall_rate, cylinder_num=self.cylinder_num)

        # subscriber
        self.scanSub = rospy.Subscriber("/scan_downsampled", LaserScan, self._scanCB)
        self.odomSub = rospy.Subscriber("/odom", Odometry, self._odomCB)

        # publisher
        self.cmdPub = rospy.Publisher("/cmd_vel", Twist, queue_size=1)
        self.rewardPub = rospy.Publisher("reward", Reward, queue_size=1)
        # self.accPub = rospy.Publisher("accel_body", Acc, queue_size=1)
        self.setModelStatePub = rospy.Publisher("/gazebo/set_model_state", ModelState, queue_size=1)

        # service client
        self.modelStateClient = rospy.ServiceProxy("/gazebo/get_model_state", GetModelState)

        self.tf_listener = tf.TransformListener()
        self.odom_frame = "odom"
        try:
            self.tf_listener.waitForTransform(self.odom_frame, 'base_footprint', rospy.Time(), rospy.Duration(1.0))
            self.base_frame = 'base_footprint'
        except (tf.Exception, tf.ConnectivityException, tf.LookupException):
            try:
                self.tf_listener.waitForTransform(self.odom_frame, 'base_link', rospy.Time(), rospy.Duration(1.0))
                self.base_frame = 'base_link'
            except (tf.Exception, tf.ConnectivityException, tf.LookupException):
                rospy.loginfo("Can not find transform")
                rospy.signal_shutdown("tf_Exception")
        (self.position, self.rotation) = self.get_odom()

    def reset(self, trial):
        """
            reset uav and target
        """

        if trial % 1 == 0:
            if self.start_flag:
                self.world.clear()
                rospy.loginfo("clear world.")
            else:
                self.start_flag = True

            self.world.reset()
            rospy.loginfo("reset_world.")

        # stop
        self.target_x = self.target_distance
        self.target_y = 0

        self.world.set_target(self.target_x, self.target_y)

        rospy.loginfo("initialize target position.")

        begin_time = rospy.Time.now()
        while (rospy.Time.now() - begin_time) < rospy.Duration(1):
            msg = Twist()
            self.cmdPub.publish(msg)
            self.rate.sleep()

        # reset turbot position
        msg = ModelState()
        msg.model_name = self.model_name

        home_yaw = random.uniform(-math.pi, math.pi)
        qtr =  quaternion_from_euler(0, 0, home_yaw)

        msg.pose.orientation.x = qtr[0]
        msg.pose.orientation.y = qtr[1]
        msg.pose.orientation.z = qtr[2]
        msg.pose.orientation.w = qtr[3]

        self.setModelStatePub.publish(msg)

        rospy.loginfo("initialize turbot position.")

        # clear world
        # if self.start_flag:
        #     self.world.clear()
        #     self.start_flag = False
        #     rospy.loginfo("clear world.")

        # initialize target point

        # reset world

        # print("step_count ", self.step_count)
        # if self.step_count % 10 == 0:
        self.step_count = 0
        # self.start_flag = True

        return self.cur_state()

    def is_crashed(self):
        """
            determine if the uav is crashed.
            return:
                - True if it was crashed.
                - crash reward
                - relative laser index (to check the direction)
        """
        self.laser_crashed_flag = False
        self.laser_crashed_reward = 0
        self.crash_index = -1

        for i in range(len(self.scan.ranges)):
            if self.scan.ranges[i] < 3*self.crash_limit:
                self.laser_crashed_reward = min(-10, self.laser_crashed_reward)
            if self.scan.ranges[i] < 2*self.crash_limit:
                self.laser_crashed_reward = min(-25.0, self.laser_crashed_reward)
            if self.scan.ranges[i] < self.crash_limit:
                self.laser_crashed_reward = -100.0
                self.laser_crashed_flag = True
                self.crash_index = i
                break

        return self.laser_crashed_flag, self.laser_crashed_reward, self.crash_index

    def step(self, time_step=0.1, vx=0.1, vy=0.1, yaw_rate=0.1, step = 0):
        """
            game step
        """
        self.step_count += 1
        time_begin = rospy.Time.now()

        self.hold_able = False
        (self.position, self.rotation) = self.get_odom()
        # record last x and y
        # last_pos_x_uav = self.pose.position.x
        # last_pos_y_uav = self.pose.position.y
        last_pos_x_uav = self.position.x
        last_pos_y_uav = self.position.y
        # print("last_x", last_pos_x_uav ,"last_y" ,last_pos_y_uav )
        last_distance = math.sqrt((self.target_x - last_pos_x_uav)**2 + (self.target_y - last_pos_y_uav)**2)

        # send control command
        msg = Twist()
        msg.linear.x = vx
        msg.angular.z = yaw_rate
        self.cmdPub.publish(msg)
        rospy.sleep(rospy.Duration(time_step))
        # record current x and y
        (self.position, self.rotation) = self.get_odom()

        # cur_pos_x_uav = self.pose.position.x
        # cur_pos_y_uav = self.pose.position.y
        cur_pos_x_uav = self.position.x
        cur_pos_y_uav = self.position.y

        # print("now_x", cur_pos_x_uav ,"now_y" ,cur_pos_y_uav )
        cur_distance = math.sqrt((self.target_x - cur_pos_x_uav)**2 + (self.target_y - cur_pos_y_uav)**2)

        # distance reward
        distance_reward = (last_distance - cur_distance)*(5/time_step)*3.0*7

        self.done = False

        # arrive reward
        self.arrive_reward = 0
        if cur_distance < 0.3:
            self.arrive_reward = 100
            self.done = True

        # crash reward
        crash_indicator, crash_reward, _ = self.is_crashed()
        if crash_indicator == True:
            self.done = True

        # laser reward
        state = np.array(self.scan.ranges) / float(self.scan.range_max)
        # print("state is ", state)
        for j in range(36):
                if state[j] > 1:
                    state[j] = 1.
        laser_reward = -1.0*np.abs(np.sum((state - 1)**4))

        # linear punish reward (abandan)
        self.linear_punish_reward_x = 0
        # if self.body_v.twist.linear.x < 0.1:
        #     self.linear_punish_reward_x = -1

        # angular punish reward
        self.angular_punish_reward = 0
        if abs(self.odom.twist.twist.angular.z) > 0.4:
            self.angular_punish_reward = -1
        elif abs(self.odom.twist.twist.angular.z) > 0.7:
            self.angular_punish_reward = -2

        # step punish reward
        self.step_punish_reward = -self.step_count * 0.08
        # self.step_punish_reward = 0

        # acc punish
        self.acc_x_punish_reward = 0
        self.acc_yaw_punish_reward = 0
        # self.acc_x_punish_reward = -4.0*abs(self.acc_x)
        # self.acc_yaw_punish_reward = -2.0*abs(self.acc_yaw)

        # right turing reward
        right_turning_reward = 0    # to break balance of turning
        # if self.odom.twist.twist.angular.z < 0:
            # right_turning_reward = 0.3*abs(self.odom.twist.twist.angular.z)
        # print("distance_reward ", distance_reward)
        # print("arrive_reward ", self.arrive_reward)
        # print("crash_reward ", crash_reward )
        # print("laser_reward", laser_reward)
        # print("angular_punish_reward", self.angular_punish_reward)
        # print("step_punish_reward", self.step_punish_reward)
        total_reward = distance_reward \
                        + self.arrive_reward \
                        + crash_reward \
                        + laser_reward \
                        + self.angular_punish_reward \
                        + self.step_punish_reward \
                        + self.acc_x_punish_reward \
                        + self.acc_yaw_punish_reward \
                        + right_turning_reward \

        msg = Reward()
        msg.header.stamp = rospy.Time.now()
        msg.distance_reward = distance_reward
        msg.arrive_reward = self.arrive_reward
        msg.crash_reward = crash_reward
        msg.laser_reward = laser_reward
        msg.linear_punish_reward = self.linear_punish_reward_x
        msg.angular_punish_reward = self.angular_punish_reward
        msg.step_punish_reward = self.step_punish_reward
        msg.acc_x_punish_reward = self.acc_x_punish_reward
        msg.acc_yaw_punish_reward = self.acc_yaw_punish_reward
        msg.right_turning_reward = right_turning_reward
        msg.total_reward = total_reward
        self.rewardPub.publish(msg)

        # out of limit
        if self.position.x < -10 or self.position.x > 12:
            self.done = True
        if self.position.y < -10 or self.position.y > 10:
            self.done = True

        # sleep

        return self.cur_state(), total_reward/20.0, self.done

    def cur_state(self):
        """
            36 laser
            1  vx
            1  yaw_rate
            1  distance
            1  angle_diff
        """
        # ranges msg
        state = [ (i - self.scan.range_max/2)/(self.scan.range_max/2) for i in self.scan.ranges]
        for j in range(36):
                if state[j] > 1:
                    state[j] = 1.
        # pose msg
        (self.position, self.rotation) = self.get_odom()
        state.append(self.odom.twist.twist.linear.x/0.2)
        state.append(self.odom.twist.twist.angular.z)

        # relative distance and normalize
        # distance_uav_target =  math.sqrt((self.target_x - self.pose.position.x)**2 + (self.target_y - self.pose.position.y)**2)/10
        distance_uav_target =  math.sqrt((self.target_x - self.position.x)**2 + (self.target_y - self.position.y)**2)/3.0

        angle_uav_targer = atan2(self.target_y - self.position.y, self.target_x - self.position.x)
        # (_, _, angle_uav) = euler_from_quaternion([
        #                                         self.pose.orientation.x,
        #                                         self.pose.orientation.y,
        #                                         self.pose.orientation.z,
        #                                         self.pose.orientation.w
        #                                         ])
        angle_uav = self.rotation
        angle_diff = angles.shortest_angular_distance(angle_uav, angle_uav_targer)/math.pi
        state.append(distance_uav_target)
        state.append(angle_diff)

        return np.array(state)

    # tool funciton

    def _scanCB(self, msg):
        self.scan = msg

    def _odomCB(self, msg):
        self.odom = msg

    def _is_arrived(self, x, y, z, limit=0.1):
        # return (self.pose.position.x - x)**2 < limit and \
        #         (self.pose.position.y - y)**2 < limit and \
        #             (self.pose.position.z - z)**2 < limit
        (self.position, self.rotation) = self.get_odom()

        return (self.position.x - x)**2 < limit and \
                (self.position.y - y)**2 < limit and \
                    (self.position.z - z)**2 < limit

    def is_arrived(self):
        (self.position, self.rotation) = self.get_odom()
        cur_pos_x_uav = self.position.x
        cur_pos_y_uav = self.position.y
        cur_distance = math.sqrt((self.target_x - cur_pos_x_uav)**2 + (self.target_y - cur_pos_y_uav)**2)
        if cur_distance < 0.3:
            return True
        return False

    def get_odom(self):
        try:
            (trans, angular) = self.tf_listener.lookupTransform(self.odom_frame, self.base_frame, rospy.Time(0))
            rotation = euler_from_quaternion(angular)
        except (tf.Exception, tf.ConnectivityException, tf.LookupException):
            rospy.loginfo("tf Exception Error")
            return

        return (Point(*trans), rotation[2])

if __name__ == '__main__':

    rospy.init_node("test")

    game = Game("turtlebot3_burger", "empty_3m")

    game.reset()

    rospy.sleep(rospy.Duration(3.0))

    begin_time = rospy.Time.now()

    while (rospy.Time.now() - begin_time) < rospy.Duration(3):
        game.step(0.1, 0.1, 0, 0.2)

    game.reset()

    rospy.sleep(rospy.Duration(3.0))

    begin_time = rospy.Time.now()

    while (rospy.Time.now() - begin_time) < rospy.Duration(3):
        game.step(0.1, 0.1, 0, 0.2)


from typing import List, Dict, Tuple
from enum import Enum
from dataclasses import dataclass, field

class Operation(Enum):
    NONE = 1
    AND = 2
    OR = 3
    LSHIFT = 4
    RSHIFT = 5
    NOT = 6

    @staticmethod
    def from_string(token: str):
        if token == "AND":
            return Operation.AND
        elif token == "OR":
            return Operation.OR
        elif token == "LSHIFT":
            return Operation.LSHIFT
        elif token == "RSHIFT":
            return Operation.RSHIFT
        elif token == "NOT":
            return Operation.NOT
        else:
            raise Exception("bad operation: %s" % token)

class TokenType(Enum):
    NUMBER = 1
    WIRE = 2
    OPERATION = 3

@dataclass
class Operand:
    operation: Operation = Operation.NONE
    number: int = 0
    wire: str = ""

@dataclass
class Token:
    type: TokenType
    operand: Operand

def tokenize(string: str) -> List[Token]:
    tokens = []
    stop = False
    for token in string.split(' '):
        char = token[0]
        if char.isdigit():
            tokens.append(Token(TokenType.NUMBER,
                                Operand(number=int(token))))
        elif char.islower():
            tokens.append(Token(TokenType.WIRE,
                                Operand(wire=token)))
        elif char.isupper():
            tokens.append(Token(TokenType.OPERATION,
                                Operand(operation=Operation.from_string(token))))
    return tokens

@dataclass
class Wire:
    value: int = -1
    tokens: List[Token] = field(default_factory=lambda: [])

Wires = Dict[str, Wire]

def token_value(token: Token, wires: Wires) -> int:
    v: int = 0
    if token.type == TokenType.NUMBER:
        v = token.operand.number
    elif token.type == TokenType.WIRE:
        v = wire_eval(token.operand.wire, wires)
    else:
        assert False
    return v

def wire_eval(wire: str, wires: Wires) -> int:
    if wires[wire].value != -1:
        return wires[wire].value

    tokens: List[Token] = wires[wire].tokens

    # SIGNAL or WIRE
    if len(tokens) == 1:
        wires[wire].value = token_value(tokens[0], wires)
        return wires[wire].value

    # NOT
    if len(tokens) == 2 and tokens[0].type == TokenType.OPERATION:
        wires[wire].value = ~wire_eval(tokens[1].operand.wire, wires)
        return wires[wire].value

    # other operations
    if len(tokens) == 3 and tokens[1].type == TokenType.OPERATION:
        v1: int = token_value(tokens[0], wires)
        v2: int = token_value(tokens[2], wires)
        op: Operation = tokens[1].operand.operation

        v: int = 0
        if op == Operation.AND:
            v = v1 & v2
        elif op == Operation.OR:
            v = v1 | v2
        elif op == Operation.LSHIFT:
            v = v1 << v2
        elif op == Operation.RSHIFT:
            v = v1 >> v2
        else:
            assert False

        wires[wire].value = v
        return v
    return 0


'''
无重复字符的最长子串
给定一个字符串 s ，请你找出其中不含有重复字符的 最长子串 的长度。

输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc"，所以其长度为 3。
'''

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        '''方法二：滑动窗口'''
        maxLength = 0
        dict = {}
        index_left = 0
        for i in range(len(s)):
            if s[i] in dict and dict[s[i]] >= index_left:
                index_left = dict[s[i]] + 1
                dict[s[i]] = i
            else:
                dict[s[i]] = i
            maxLength = max(maxLength, i - index_left + 1)
        return maxLength
        '''方法一：暴力解法'''
        # def longestSubstring(s: str, index):
        #     length = 0
        #     m = collections.Counter()
        #     i = 0
        #     while index + i < len(s) and m[s[index + i]] < 1:
        #         m[s[index + i]] += 1
        #         length += 1
        #         i += 1
        #     return length
        #
        # maxLength = 0
        # for i in range(len(s)):
        #     cur_length = longestSubstring(s, i)
        #     if maxLength < cur_length:
        #         maxLength = cur_length
        #     i += 1
        # return maxLength

if __name__ == '__main__':
    solution = Solution()
    print(solution.lengthOfLongestSubstring("abba"))

code/数据结构/线性表/数组和字符串/2022-03-14_3-无重复字符的最长子串.py


from typing import KeysView
from flask import Flask, render_template, request, jsonify
import pandas as pd
from csv import writer
from animalia import app
import random

@app.route("/")
def home():
    return render_template("Home.html")

@app.route("/fetch", methods=["GET", "POST"])
def fetch():                              #Request specific animal data
    if request.method == "POST":
        jsonData = request.get_json()
        print(jsonData)
        data = pd.read_csv(".\\animalia\\database\\animal_locations.csv")
        key = jsonData["key"]
        return {
            'species' : data["species"][key],
            'type' : data["type"][key],
            'extra_info' : data["info"][key],
            'date' : data["date"][key],
            'long' : data["longitude"][key],
            'lat' : data["latitude"][key]
        }
    return render_template("Home.html")

@app.route("/all_data", methods=["GET", "POST"])
def all_data():                              #Request specific animal data
    if request.method == "POST":
        data = pd.read_csv(".\\animalia\\database\\animal_locations.csv")
        data.drop("info", axis = 1, inplace = True)
        data_json = data.to_json(None, indent = 1, orient = 'records')
        #print(data_json)
        return data_json
    return render_template("Home.html")

@app.route("/submit", methods=["GET", "POST"])
def submit():                              #Request specific animal data
    if request.method == "POST":
        print("Arrived")
        data = pd.read_csv(".\\animalia\\database\\animal_locations.csv")
        with open(".\\animalia\\database\\animal_locations.csv", 'a', newline="") as f_object:
            writer_object = writer(f_object)
            jsonData = request.get_json()
            print(jsonData)
            data_list = [len(data["key"]),jsonData["species"],jsonData["lat"],jsonData["long"],jsonData["type"],jsonData["date"],jsonData["description"]]
            writer_object.writerow(data_list)
            f_object.close()

        return "success"
    return render_template("Home.html")

@app.route("/search", methods=["GET", "POST"])
def search():                              #Search for all occurences of animal
    if request.method == "POST":
        lat_list = []
        long_list = []
        species_list = []
        jsonData = request.get_json()
        csv_data = pd.read_csv(".\\animalia\\database\\animal_locations.csv")
        for x in range(len(csv_data["key"])):
            if jsonData["species_search"] in csv_data["species"][x]:
                lat_list.append(csv_data["latitude"][x])
                long_list.append(csv_data["longitude"][x])
                species_list.append(csv_data["species"][x])
        #keys_list.to_json(None, indent = 1, orient = 'records')
        if len(lat_list) > 21: #If the list is too large, get random values
            combined = list(zip(lat_list, long_list, species_list))
            random.shuffle(combined)
            lat_list, long_list, species_list = zip(*combined)
        return {
            'species' : species_list,
            'lats' : lat_list,
            'longs' : long_list
        }
    return render_template("Home.html")


# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-

def build(bld):
    if not bld.env['ENABLE_EXAMPLES']:
        return;

    obj = bld.create_ns3_program('example-udp-group-echo',
                                 ['psc'])
    obj.source = 'example-udp-group-echo.cc'

    obj = bld.create_ns3_program('uav-mobility-energy-example',
                                 ['core', 'energy', 'mobility', 'psc'])
    obj.source = 'uav-mobility-energy-example.cc'

    obj = bld.create_ns3_program('example-intel-http',
                                 ['psc'])
    obj.source = 'example-intel-http.cc'

    obj = bld.create_ns3_program('example-psc-application',
                                 ['psc'])
    obj.source = 'example-psc-application.cc'

    obj = bld.create_ns3_program('camad-2019-communication',
                                 ['core', 'lte', 'network','mobility', 'internet', 'applications', 'psc'])
    obj.source = [
        'camad-2019/camad-2019-communication.cc',
        'camad-2019/lte-sl-ue-controller-camad-2019.cc',
    ]

    obj = bld.create_ns3_program('camad-2019-connection',
                                 ['core', 'lte', 'network','mobility', 'internet', 'applications', 'psc'])
    obj.source = [
        'camad-2019/camad-2019-connection.cc',
        'camad-2019/lte-sl-ue-controller-camad-2019.cc',
    ]

    obj = bld.create_ns3_program('camad-2019-discovery',
                                 ['core', 'lte', 'network','mobility', 'internet', 'applications', 'psc'])
    obj.source = [
        'camad-2019/camad-2019-discovery.cc',
        'camad-2019/lte-sl-ue-controller-camad-2019.cc',
    ]

    psc_schoolshooting_modules = ['psc', 'netanim']
    if 'HAS_NETSIMULYZER' in bld.env:
        psc_schoolshooting_modules.append('netsimulyzer')

    obj = bld.create_ns3_program('psc-schoolshooting',
                                 psc_schoolshooting_modules)
    obj.source = [
        'schoolshooting/psc-schoolshooting.cc',
        'schoolshooting/schoolshooting-definition-helper.cc',
        'schoolshooting/schoolshooting-lte-helper.cc',
        'schoolshooting/schoolshooting-network-technology-helper.cc',
        'schoolshooting/schoolshooting-application-helper.cc',
        'schoolshooting/schoolshooting-application-trace-helper.cc',
        'schoolshooting/schoolshooting-lte-vis-helper.cc',
    ]

    obj = bld.create_ns3_program('example-video-streaming',
                                 ['psc'])
    obj.source = 'example-video-streaming.cc'

    obj = bld.create_ns3_program('example-mcptt-wifi-adhoc',
                                 ['psc', 'wifi'])
    obj.source = 'example-mcptt-wifi-adhoc.cc'

    obj = bld.create_ns3_program('example-mcptt-pusher-orchestrator',
                                 ['psc', 'wifi'])
    obj.source = 'example-mcptt-pusher-orchestrator.cc'

    obj = bld.create_ns3_program('mcptt-lte-sl-out-of-covrg-comm',
                                 ['core', 'lte', 'network','mobility', 'internet', 'applications', 'psc'])
    obj.source = 'mcptt-lte-sl-out-of-covrg-comm.cc'

    obj = bld.create_ns3_program('example-mcptt-on-network-floor-control-csma',
                                 ['core', 'csma', 'network','mobility', 'internet', 'applications', 'psc'])
    obj.source = 'example-mcptt-on-network-floor-control-csma.cc'

    obj = bld.create_ns3_program('example-mcptt-on-network-floor-control-lte',
                                 ['core', 'lte', 'network','mobility', 'internet', 'applications', 'psc'])
    obj.source = 'example-mcptt-on-network-floor-control-lte.cc'

    obj = bld.create_ns3_program('example-mcptt-on-network-two-calls',
                                 ['core', 'point-to-point', 'lte', 'network', 'mobility', 'internet', 'applications', 'psc'])
    obj.source = 'example-mcptt-on-network-two-calls.cc'

    obj = bld.create_ns3_program('example-mcptt-on-network-two-simultaneous-calls',
                                 ['core', 'point-to-point', 'lte', 'network', 'mobility', 'internet', 'applications', 'psc'])
    obj.source = 'example-mcptt-on-network-two-simultaneous-calls.cc'

    obj = bld.create_ns3_program('mcptt-operational-modes-static',
                                 ['core', 'point-to-point', 'lte', 'network', 'mobility', 'internet', 'applications', 'psc', 'buildings'])
    obj.source = 'mcptt-operational-modes-static.cc'

    mcptt_operational_modes_mobility_linked_modules = ['core', 'point-to-point', 'lte', 'network',
                                                       'mobility', 'internet', 'applications', 'psc', 'buildings']
    if 'HAS_NETSIMULYZER' in bld.env:
        mcptt_operational_modes_mobility_linked_modules.append('netsimulyzer')

    obj = bld.create_ns3_program('mcptt-operational-modes-mobility',
                                 mcptt_operational_modes_mobility_linked_modules)
    obj.source = 'mcptt-operational-modes-mobility.cc'


import pandas
import os
directory = "english"

english_xlsx = pandas.read_excel("english_chinese.xlsx", header=None)
for i in range (25,26):
    index_start = (i-1)*10000+1
    index_end = i * 10000
    english_xlsx[index_start-1:index_end][0].to_excel("2_englishSplits/english_"+str(index_start)+"_"+str(index_end)+".xlsx"
                                                     , index=False, header=False)


#!/usr/bin/env python
"""Fully-connected neural network example using MNIST dataset

This code is a custom loop version of train_mnist.py. That is, we train
models without using the Trainer class in chainer and instead write a
training loop that manually computes the loss of minibatches and
applies an optimizer to update the model.
"""
from __future__ import print_function

import argparse, os

import chainer
from chainer import cuda
from chainer.dataset import concat_examples
from chainer.datasets import tuple_dataset
import chainer.links as L
import chainer.functions as F
from chainer import serializers
from chainer import training
from chainer.training import extensions
import numpy as np
from data_loader import DataSet, load_data, DataSetOnLine
from models import *

def main():
    parser = argparse.ArgumentParser(description='Chainer example: MNIST')
    parser.add_argument('--batchsize', '-b', type=int, default=20,
                        help='Number of images in each mini-batch')
    parser.add_argument('--epoch', '-e', type=int, default=100,
                        help='Number of sweeps over the dataset to train')
    parser.add_argument('--lr', '-l', type=float, default=1e-5,
                        help='learning rate')
    parser.add_argument('--gpu', '-g', type=int, default=0,
                        help='GPU ID (negative value indicates CPU)')
    parser.add_argument('--out', '-o', default='dnn',
                        help='Directory to output the result')
    parser.add_argument('--resume', '-r', default='',
                        help='Resume the training from snapshot')
    parser.add_argument('--unit', '-u', type=int, default=1024,
                        help='Number of units')
    parser.add_argument('--noplot', dest='plot', action='store_false',
                        help='Disable PlotReport extension')
    args = parser.parse_args()

    try:
        os.mkdir(args.out)
    except:
        print('')

    print('GPU: {}'.format(args.gpu))
    print('# unit: {}'.format(args.unit))
    print('# Minibatch-size: {}'.format(args.batchsize))
    print('# epoch: {}'.format(args.epoch))
    print('')

    # Set up a neural network to train
    model = L.Classifier(DNN())
    if args.gpu >= 0:
        # Make a speciied GPU current
        chainer.cuda.get_device_from_id(args.gpu).use()
        model.to_gpu()  # Copy the model to the GPU

    # Setup an optimizer
    optimizer = chainer.optimizers.MomentumSGD(lr=args.lr)
    optimizer.setup(model)
    optimizer.add_hook(chainer.optimizer.WeightDecay(5e-4))

    # extract all feature
    # train_data, train_label, _ = load_data()
    # train_data = np.vstack(train_data)
    # mean = np.mean(train_data, axis=0)
    # std = np.std(train_data, axis=0)
    # train_data = (train_data - mean) / std
    # dev_data, dev_label, _ = load_data(mode='dev')
    # dev_data = np.vstack(dev_data)
    # mean = np.mean(dev_data, axis=0)
    # std = np.std(dev_data, axis=0)
    # dev_data = (dev_data - mean) / std

    # train = DataSet(train_data, np.hstack(train_label))
    # dev = DataSet(np.vstack(dev_data), np.hstack(dev_label))

    train = DataSetOnLine(mode='train', feat_type='fft', buf=False)
    dev = DataSetOnLine(mode='dev', feat_type='fft', buf=False)

    train_iter = chainer.iterators.MultiprocessIterator(train, args.batchsize, n_prefetch=2, shared_mem=100*1024*1024)
    dev_iter = chainer.iterators.MultiprocessIterator(dev, args.batchsize, n_prefetch=2, shared_mem=100*1024*1024, repeat=False, shuffle=False)

    sum_accuracy = 0
    sum_loss = 0
    train_count = 0
    dev_count = 0

    train_acc = []
    dev_acc = []

    while train_iter.epoch < args.epoch:
        batch = train_iter.next()   # feature: (batchsize, frames, window*dim)
        # Reduce learning rate by 0.5 every 25 epochs.
        # if train_iter.epoch % 5 == 0 and train_iter.is_new_epoch:
        #     optimizer.lr *= 0.5
        #     print('Reducing learning rate to: ', optimizer.lr)

        # x, t = concat_examples(batch)
        batch = np.array(batch)
        x = np.vstack(batch[:,0])
        t = np.hstack(batch[:,1])

        if args.gpu >= 0:
            x = cuda.to_gpu(x, args.gpu)
            t = cuda.to_gpu(t, args.gpu)

        optimizer.update(model, x, t)
        sum_loss += float(model.loss.data)
        sum_accuracy += float(model.accuracy.data) * len(t)
        train_count += len(t)

        print('train loss %.5f, acc %.2f%%' % (sum_loss/train_count, 100*sum_accuracy/train_count))

        if train_iter.is_new_epoch:
            print('epoch: ', train_iter.epoch)
            print('train mean loss: %.5f, accuracy: %.2f%%' % (
                sum_loss / train_count, 100 * sum_accuracy / train_count))
            train_acc.append(sum_accuracy / train_count)
            # evaluation
            sum_accuracy = 0
            sum_loss = 0
            train_count = 0
            model.predictor.train = False
            for batch in dev_iter:
                batch = np.array(batch)
                x = np.vstack(batch[:,0])
                t = np.hstack(batch[:,1])
                # x, t = concat_examples(batch)

                if args.gpu >= 0:
                    x = cuda.to_gpu(x, args.gpu)
                    t = cuda.to_gpu(t, args.gpu)

                loss = model(x, t)
                sum_loss += float(loss.data)
                sum_accuracy += float(model.accuracy.data) * len(t)
                dev_count += len(t)

                print('dev loss %.5f, acc %.2f%%' % (sum_loss/dev_count, 100*sum_accuracy/dev_count))

            dev_iter.reset()
            model.predictor.train = True
            print('dev mean  loss: %.5f, accuracy: %.2f%%' % (
                sum_loss / dev_count, 100 * sum_accuracy / dev_count))
            dev_acc.append(sum_accuracy / dev_count)
            # if train_iter.epoch > 1 and dev_acc[-1] > dev_acc[-2] < 0.001:
            #     print('improvement is too small')
            #     break

            sum_accuracy = 0
            sum_loss = 0
            dev_count = 0

    # Save the model and the optimizer
    print('save the model')
    serializers.save_npz(os.path.join(args.out, 'model'), model)
    print('save the optimizer')
    serializers.save_npz(os.path.join(args.out, 'state'), optimizer)

    print('save accuracy')
    import pickle
    with open(os.path.join(args.out, 'train_dev_acc'), 'wb') as f:
        pickle.dump({'train': train_acc, 'dev': dev_acc}, f)

if __name__ == '__main__':
    main()


import subprocess
try:
    import pytube
except:
    subprocess.check_call([sys.executable, "-m", "pip",
                           "install", "git+https://github.com/nficano/pytube"])
import pytube
import os

def is_user():
    user = os.getlogin()
    location = f'C:/Users/{user}/Desktop/Modified_Downloads'
    is_dir = os.path.isdir(location)
    if is_dir:
        return True
    else:
        return False

def download_video(url, classification):
    user = os.getlogin()
    location = ''
    youtube = ""
    while True:
        try:
            youtube = pytube.YouTube(url)
            break
        except pytube.exceptions.RegexMatchError:
            url = input("Invalid url. Please try again : ")

    if classification == "music":
        location = f'C:/Users/{user}/Desktop/Modified_Downloads/music'
    elif classification == "tutorial":
        location = f'C:/Users/{user}/Desktop/Modified_Downloads/tutorial'
    else:
        location = f'C:/Users/{user}/Desktop/Modified_Downloads/normal'

    video = youtube.streams.get_highest_resolution()
    video.download(location)
    print(f"Successfully downloaded '{video.title}' at {location}")

def create_dir():
    user = os.getlogin()
    os.mkdir(f'C:/Users/{user}/Desktop/Modified_Downloads')
    print("[Modified_Downloads] : created")
    os.mkdir(f'C:/Users/{user}/Desktop/Modified_Downloads/music')
    print("[Music]: created")
    os.mkdir(f'C:/Users/{user}/Desktop/Modified_Downloads/tutorial')
    print("[Tutorials]: created")
    os.mkdir(f'C:/Users/{user}/Desktop/Modified_Downloads/normal')
    print("[Normal]: created")

def proccess():
    url = input("Please enter the url : ")
    while True:
        classification = input("Type : ").lower()
        if classification == "tutorial":
            break
        if classification == "normal":
            break
        if classification == "music":
            break
        else:
            print("Invalid type")
    download_video(url, classification)

def main():
    is_installed = is_user()
    if is_installed:
        print("Directory verified")
        proccess()
    else:
        print("Directory not found.")
        print("Creating directory.")
        create_dir()
        print("Verified.")
        proccess()

main()


import argparse
import tensorflow as tf
from data2 import MidiDataset
import numpy as np
from tqdm import tqdm
import os
import time
from model2 import WaveNet
import ops

def main(args):

	# get datasets
	dataset = MidiDataset(args.split, args.dataset_dir)

	x = tf.placeholder(tf.float32, [None, None, MidiDataset.notes])
	MidiDataset.to_summary('input', x)

	#batch_x = data2.create_batch([x], batch_size=args.batch_size)
	batch_x = tf.expand_dims(tf.cast(dataset.x, tf.float32), 0)
	batch_y = tf.expand_dims(tf.cast(dataset.y, tf.float32), 0)
	#MidiDataset.to_summary('input', batch_x)
	#MidiDataset.to_summary('gt_output', batch_y)

	# build models

	wavenet = WaveNet(scope='model')

	generated = wavenet(x)
	midi = tf.round(tf.nn.sigmoid(generated))
	MidiDataset.to_summary('generated', tf.nn.sigmoid(generated))
	MidiDataset.to_summary('generated_midi', tf.round(tf.nn.sigmoid(generated)))

	# set up logging

	# Gather initial summaries.
	summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES))

	# Merge all summaries together.
	summary_op = tf.summary.merge(list(summaries), name='summary_op') if len(summaries) > 0 else tf.no_op()

	# create train loop
	saver = tf.train.Saver(var_list=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='model'))
	writer = tf.summary.FileWriter(os.path.join(args.checkpoint_dir, 'eval'))

	with tf.Session() as sess:
		# Tensorflow initializations
		sess.run(tf.get_collection(tf.GraphKeys.TABLE_INITIALIZERS))
		tf.train.start_queue_runners(sess=sess)
		sess.run(tf.global_variables_initializer())
		sess.run(tf.local_variables_initializer())

		saver.restore(sess, tf.train.latest_checkpoint(args.checkpoint_dir))

		output, output_ = sess.run([batch_x, batch_y])
		output[:,args.base_length:,:] = 0

		for i in tqdm(range(args.total_length)):

			if i % args.log_every_n_steps == 0:
				summary, m, g = sess.run([summary_op, midi, generated], {x: output})
				writer.add_summary(summary, i+1)
			else:
				m, g = sess.run([midi, generated], {x: output})

			output[:, args.base_length+i+1,:] = m[:, args.base_length+i,:]

if __name__ == '__main__':
	parser = argparse.ArgumentParser()
	parser.add_argument('--split', type=str, default='train')
	parser.add_argument('--dataset_dir', type=str, default='data')
	parser.add_argument('--batch_size', type=int, default=1)
	parser.add_argument('--total_length', type=int, default=3000)
	parser.add_argument('--base_length', type=int, default=50)
	parser.add_argument('--log_every_n_steps', type=int, default=100)
	parser.add_argument('--shuffle', type=bool, default=True)
	parser.add_argument('--checkpoint_dir', type=str, required=True)

	args = parser.parse_args()

	main(args)


from ordliste import Ordliste
class Spillsekvens:

    def __init__(self):
        self._ant_spel = 0
        self._brukar_namn = ""
        self._poengsum = 0

    def start(self):
        self._brukar_namn = input("Skriv inn namn: ")
        tap = 0
        #løkke for spelet, spelet kjører heilt til man har spelt 3 gonger
        # (10 blir for mykje), eller man taper eller velger å avslutte
        ordliste = Ordliste()

        while self._ant_spel < 3 and tap == 0:
            #starter eit spel ved å hente eit ord frå ordlista
            runde = ordliste.hent_tilfeldig()

            poengsum = runde.spel()
            self._ant_spel += 1
            # om man vinner eit spel
            if poengsum > 0:
                self._poengsum += poengsum
                # avbryt og gå tilbake til menyen om n, nei
                # kunne lagd dette valget bedre..
                if self._ant_spel < 3:
                    k = input("Vil du fortsette j/n?\n")
                    if k == "j":
                        tap == 0
                    else:
                        tap += 1
            elif poengsum == 0:
                tap += 1

            # repr er interessant, man velger korleis ein skal representere
            # ein instans av ein spelsekvens
            # tok lit tid å få denne til å gå
    def __repr__(self):
        return(self._brukar_namn, self._poengsum, self._ant_spel)