# tuples -->> It is a immutable sequence  of Python objects, A Tuple are also comparable and hashable.
# syntax
newTuple = ('a','b','c','d')
'''
# or
newTuple2 = ('a',)
# or we can just use tuple() operator to create a new tuple

print(newTuple)
print(newTuple2)
'''

# Access element in a tuple
'''
print(newTuple[1])
# slice operator
print(newTuple[::2])
'''

# Traversing a Tuple
'''
for i in range (len(newTuple)):
    # print(i)
    print(newTuple[i])
'''

# Searching in a Tuple
'''
print('a' in newTuple)  #-->> output == True
print('f' in newTuple) #-->> output == False

# index method
print(newTuple.index('a'))

# method 3
def searchTuple(tuple,value):
    for i in range (0,len(tuple)):
        if tuple[i] == value:
            return(f'The {value} was found at {i} index')
    return("Value not Found")

print(searchTuple(newTuple,'c'))
'''

# Tuple Operators/Functions
myTuple = (1,4,3,2,5)
myTuple1 = (1,2,6,9,8,7)

# concatenation
'''
print(myTuple + myTuple1)
'''

# star operator (*) -->> each element of a tuple will be repated each time (for example 4 times)
'''
print(myTuple * 4)
'''

# Count Method -->> count the number of times a element is present in a tuple
'''
print(myTuple.count(2))
'''

# len function -->> return the length of the tuple
'''
print(len(myTuple))
'''

# max/min function -->> returns the maximum/minimum element of the tuple
'''
print(max(myTuple))
print(min(myTuple))
'''
# tuple is also build in fuction in python library


"""Tests the functions in day08"""
from typing import List
import pytest
from pytest import fixture

from ..day08 import (
    Operation,
    Instruction,
    parse_instruction,
    negate_instruction,
    determine_accumulator,
    swapped_instructions,
)

def test_parse_instruction():
    assert parse_instruction("jmp -1") == Instruction(Operation.JUMP, -1)
    assert parse_instruction("nop +1") == Instruction(Operation.NO_OPERATION, 1)
    assert parse_instruction("acc +11") == Instruction(Operation.ACCUMULATE, 11)

def test_negate_instruction():
    fn = negate_instruction
    assert fn(Instruction(Operation.JUMP, 1)) == Instruction(Operation.NO_OPERATION, 1)

    assert fn(Instruction(Operation.NO_OPERATION, 1)) == Instruction(Operation.JUMP, 1)

    assert fn(Instruction(Operation.ACCUMULATE, 1)) == Instruction(
        Operation.ACCUMULATE, 1
    )

@fixture
def instructions_loop() -> List[Instruction]:
    """Returns a list of instructions that lead to an loop"""
    return [Instruction(Operation.JUMP, 0)]

@fixture
def instructions_with_end() -> List[Instruction]:
    """Returns a list of instructions that lead to an accumulator 20"""
    return [
        Instruction(Operation.ACCUMULATE, 10),
        Instruction(Operation.JUMP, 2),
        Instruction(Operation.JUMP, 2),
        Instruction(Operation.JUMP, -1),
        Instruction(Operation.NO_OPERATION, 0),
        Instruction(Operation.ACCUMULATE, 10),
    ]

def test_determine_accumulator(instructions_loop, instructions_with_end):
    assert determine_accumulator(instructions_loop) is None
    assert determine_accumulator(instructions_with_end) == 20

def test_swapped_instructions(instructions_with_end):
    generator_instruction = swapped_instructions(instructions_with_end)

    # Testing 0th iteration. Nothing is being changed
    tmp_instructions = instructions_with_end.copy()
    assert next(generator_instruction) == tmp_instructions

    # Testing 1st iteration. First possible index is being changed
    tmp_instructions = instructions_with_end.copy()
    tmp_instructions[1] = Instruction(Operation.NO_OPERATION, 2)
    assert next(generator_instruction) == tmp_instructions

    # Testing 2nd iteration. Second possible index is being changed
    tmp_instructions = instructions_with_end.copy()
    tmp_instructions[2] = Instruction(Operation.NO_OPERATION, 2)
    assert next(generator_instruction) == tmp_instructions

    # Testing 3rd iteration. Third possible index is being changed
    tmp_instructions = instructions_with_end.copy()
    tmp_instructions[3] = Instruction(Operation.NO_OPERATION, -1)
    assert next(generator_instruction) == tmp_instructions

    # Testing 4th iteration. Fourth possible index is being changed
    tmp_instructions = instructions_with_end.copy()
    tmp_instructions[4] = Instruction(Operation.JUMP, 0)
    assert next(generator_instruction) == tmp_instructions

    with pytest.raises(StopIteration):  # The generator ends after that
        next(generator_instruction)


# course: Object-oriented programming, year 2, semester 1
# academic year: 201920
# author: B. Schoen-Phelan
# date: 17-10-2019
# purpose: Lab 5 - GUI and card game using queue

from tkinter import *
# to use the queue FIFO
from queue import Queue

# to use the shuffle for shuffling the cards
from random import shuffle

class CardGame(Frame):

    # initialises the application
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        # set up game logic here:
        # shuffle the cards before first use
        # variable for holding the score
        self.player_score=0

        self.init_window()

    # used by __init__
    # initialises the GUI window
    def init_window(self):
        self.pack(expand=True)

        # frames hold the elements of the window
        # grid arranges the elements in a tabular manner
        # see mock-up screen in lab sheet for the layout design
        cards_frame = LabelFrame(self)
        cards_frame.grid(row=0, column=0)
        button_frame = LabelFrame(self)
        button_frame.grid(row=0, column=1)
        score_frame = LabelFrame(self)
        score_frame.grid(row=1, column=0, columnspan=2)

        # add elements into the frames
        self.open_card = Button(cards_frame)
        the_card = PhotoImage(file='cards/queen_hearts.gif')
        self.open_card.config(image=the_card)
        self.open_card.grid(row=0, column=0, padx=2, pady=2)
        self.open_card.photo = the_card

        closed_deck = Button(cards_frame)
        closed_card = PhotoImage(file='cards/closed_deck.gif')
        closed_deck.config(image=closed_card)
        closed_deck.grid(row=0, column=1, padx=2, pady=2)
        closed_deck.photo = closed_card

        done_button = Button(button_frame, text="I'm done!")
        done_button.grid(row=0, column=0, pady=12)
        new_game_button = Button(button_frame, text="New Game")
        new_game_button.grid(row=1, column=0, pady=13)
        exit_button = Button(button_frame, text="Exit", command=self.game_exit)
        exit_button.grid(row=2, column=0, pady=13)

        self.score_label = Label(score_frame, text="Your score: "+ str(self.player_score), justify=LEFT)
        self.score_label.pack()

    # called by the exit_button Button
    # ends the GUI application
    def game_exit(self):
        exit()

# object creation here:
root = Tk()
root.geometry("300x200")
root.title("Card Game")
app = CardGame(root)
root.mainloop()


from configure import Entry, Frame, LabelFrame, Button, Label, Tk
from Manager.manager_suggestion import SuggestionView
from Manager.store_panel import StorePanel
from Manager.create_store import CreateStore
from tkinter import ttk, messagebox

class ManagerView(Tk):
    def __init__(self, callback_all_stores, callback_all_users, callback_all_suggestion, callback_create_store,
                 callback_search_store, callback_new_user, callback_delete_sug):
        super(ManagerView, self).__init__()
        self.all_stores = callback_all_stores
        self.all_users = callback_all_users
        self.all_suggestion = callback_all_suggestion
        self.create_store = callback_create_store
        self.search_store = callback_search_store
        self.new_user = callback_new_user
        self.delete_sug = callback_delete_sug
        self.end = self.all_stores()
        self.start = self.end.copy()
        self.item = 5

        self.not_tab = ttk.Notebook(self)
        self.not_tab.grid(row=0, column=0)
        self.main_tab = Frame(self)
        self.main_tab.grid(row=0, column=0)
        self.not_tab.add(self.main_tab, text="Manager")

        frm_lbl = LabelFrame(self.main_tab)
        frm_lbl.grid(row=0, column=1)

        frm1 = Frame(frm_lbl)
        frm1.grid(row=0, column=0)
        Label(frm1, text="Store Code:").grid(row=0, column=0, padx=10)
        self.entry_cs = Entry(frm1)
        self.entry_cs.grid(row=0, column=1, padx=5)

        frm2 = Frame(frm_lbl)
        frm2.grid(row=1, column=0)
        Button(frm2, text="Search", command=self.store_search).grid(row=0, column=0, pady=3)
        Button(frm2, text="Suggestion", command=self.suggestion_view).grid(row=0, column=1, pady=3)

        frm3 = Frame(frm_lbl)
        frm3.grid(row=2, column=0)
        self.tree = ttk.Treeview(frm3, show="headings", selectmode="browse")
        self.tree["column"] = ("SC", "ADDRESS")
        self.tree.heading("SC", text="Store Code")
        self.tree.heading("ADDRESS", text="Address")
        self.tree.grid(row=0, column=0)
        self.tree.bind("<Double-1>", self.double)

        frm4 = Frame(frm_lbl)
        frm4.grid(row=3, column=0)
        Button(frm4, text="prev", command=self.prev_page).grid(row=0, column=0)
        Button(frm4, text="next", command=self.next_page).grid(row=0, column=1, sticky="w")

        frm5 = Frame(frm_lbl)
        frm5.grid(row=4, column=0)
        Button(frm5, text="New Store", command=self.new_store).grid(row=0, column=0)

        self.next_page()

    def double(self, even):
        result = self.tree.selection()
        if result == ():
            return
        ID, address = self.tree.item(result)["values"]
        panel = StorePanel(self.search_store(ID), self.all_users, self.new_user, self.not_tab)
        self.not_tab.add(panel, text=ID)
        self.not_tab.select(panel)
        self.tree.selection_remove()

    def suggestion_view(self):
        panel = SuggestionView(self.all_suggestion, self.delete_sug, self.not_tab)
        self.not_tab.add(panel, text="Suggestion")

    def store_search(self):
        cs = self.entry_cs.get()
        if cs == "":
            return
        if not cs.isnumeric:
            messagebox.showerror("error", "please enter number")
            self.entry_cs.delete(0, "end")
            return
        if not 1 <= int(cs) <= 200:
            messagebox.showerror("error", "please enter number between 1 and 200")
            self.entry_cs.delete(0, "end")
            return

        result = self.search_store(int(cs))
        self.tree.delete(*self.tree.get_children())
        finish = (cs, result.address)
        self.tree.insert("", "end", value=finish)

    def next_page(self):
        if not self.end.has_next():
            return
        self.start = self.end.copy()
        count = 0
        self.tree.delete(*self.tree.get_children())
        for it in self.end.traverse():
            ite = (str(it.code), it.address)
            self.tree.insert("", "end", value=ite)
            if count >= self.item:
                break
            count += 1

    def prev_page(self):
        if not self.start.has_prev():
            return
        self.end = self.start.copy()
        count = 0
        self.tree.delete(*self.tree.get_children())
        for it in self.start.traverse(True):
            ite = (str(it.code), it.address)
            self.tree.insert("", 0, value=ite)
            if count >= self.item:
                break

    def new_store(self):
        panel = CreateStore(self.create_store, self.not_tab)
        self.not_tab.add(panel, text="New Store")
        self.not_tab.select(panel)


import re
import pandas as pd
import pretty_errors
import pycountry
from geonamescache import GeonamesCache
import json

    # Create an instance of the GeonamesCache class
gc = GeonamesCache()

    # Get a dictionary of all countries and their information, including capital cities
geo_countries = gc.get_countries()

df = pd.read_csv('/Users/juanreyesgarcia/Library/CloudStorage/OneDrive-FundacionUniversidaddelasAmericasPuebla/DEVELOPER/PROJECTS/CRAWLER_ALL/download/sql_distinct.csv')

    #df['location'] = df['location'].apply(clean_location)

def add_spaces(text):
    return re.sub(r'(?<=[a-z])(?=[A-Z])', ' ', text)

def clean_location_rows(rows):
    if not isinstance(rows, str):
        #print(f"{rows} is not a string! Returning unmodified")
        return rows
        # Keep countries, country codes, states, remote words, and timezones
    # Remove double quotes
    rows = rows.replace('"', '')

    # Add spaces before uppercase letters
    rows = add_spaces(rows)

    keep_words = ['remote', 'remoto', 'international', 'anywhere', 'worldwide', 'utc', 'apac', 'nafta', 'latam', 'asean', 'mena', 'brics', 'anz', 'gcc', 'cee', 'nordic', 'europe', 'americas', 'asia', 'africa', 'oceania', 'antarctica', 'southeast asia', 'emea', 'uk', 'usa', 'united', 'states', 'north', 'america', 'kingdom', 'korea', 'global', 'south', 'latin', 'america']

        # Get country codes and names
    country_codes = [country.alpha_2 for country in pycountry.countries]
    country_names = [country.name for country in pycountry.countries]
        # Extract the capital cities & countries from GeonamesCache
    capital_cities = [geo_countries[country]['capital'] for country in geo_countries]
    country_other_names = [geo_countries[country]['name'] for country in geo_countries]

        # US state codes
    state_codes = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']

        # Remove unwanted characters and split the text into words
    text = re.sub(r'[^a-zA-Z0-9\s\+\-]', ' ', rows)
    words = text.split()

        # Keep only the desired words
    cleaned_words = [word for word in words if any([word.lower().startswith(kw) for kw in keep_words]) or word in country_codes or word in country_names or word in state_codes or word in capital_cities or word in country_other_names or re.match(r'UTC[+\-]\d{1,2}', word)]

        # Join the cleaned words back into a string
    cleaned_text = ' '.join(cleaned_words)
    return cleaned_text

df['location'] = df['location'].apply(clean_location_rows)

df.to_csv('/Users/juanreyesgarcia/Library/CloudStorage/OneDrive-FundacionUniversidaddelasAmericasPuebla/DEVELOPER/PROJECTS/CRAWLER_ALL/download/sql_distinct.csv', index=False)

SAVE_PATH = "/Users/juanreyesgarcia/Library/CloudStorage/OneDrive-FundacionUniversidaddelasAmericasPuebla/DEVELOPER/PROJECTS/CRAWLER_ALL/data"

def convert_names_to_codes(row):
    if isinstance(row, str):  # Check if row is a string

        # Country name transformed to their respective codes & clean
        with open(SAVE_PATH + '/continent_countries_with_capitals.json', 'r') as f:
            data = json.load(f)

        # Create dictionaries for country names and subdivision names
        country_dict = {}
        for continent in data.values():
            for country in continent['Countries']:
                country_dict[country['country_name']] = country['country_code']

        # Split the string into a list of names
        names = row.split()

        # Replace each name with its code
        codes = [country_dict.get(name, name) for name in names]

        # Remove duplicates and join the codes back into a string
        return ' '.join(pd.unique(codes))
    else:
        return row

# Apply the function to the 'location' column
#df['location'] = df['location'].apply(convert_names_to_codes)

#df.to_csv(SAVE_PATH + '/location_distinct.csv', index=False)

    #print(df['location'])

if __name__ == "__main__":
    clean_location_rows(df)


from django.db import models
from django.contrib.auth.models import User
from allauth.account.models import EmailAddress
from datetime import datetime
from django.utils import timezone
#from allauth.socialaccount.models import SocialAccount
#import hashlib

today = datetime.now()

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    img = models.ImageField(upload_to='web', default='sitio/static/img/defaultuser.jpg')
    fecha = models.DateTimeField(default=timezone.now)
    nombre = models.TextField()
    apellido = models.TextField()
    about_me = models.TextField(null=True, blank=True)

    def __unicode__(self):
        return "{}'s profile'".format(self.user.username)

    class Meta:
        db_table = 'user_profile'

    def __str__(self):
        return self.nombre

    def account_verified(self):
        if self.user.is_authenticated:
            result = EmailAddress.objects.filter(email=self.user.email)
            if len(result):
                return result[0].verified
        return False

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])


import argparse
from server import Server

if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument("--host", default="localhost", help="Host address to bind to")
        parser.add_argument("--port", type=int, default=1423, help="Port number to bind to")
        args = parser.parse_args()
        # start server & accept connections
        # start new thread for processing user request
        server = Server(args.host, args.port)
        server.start()


from typing import Any, Optional

class Knot:

    def __init__(self, value: Optional[Any] = None, next_value: Optional['Knot'] = None) -> None:
        self.value = value
        self.next_value = next_value

    def __str__(self) -> str:
        return 'Knot [{value}]'.format(
            value=str(self.value)
        )

class LinkedList:

    def __init__(self) -> None:
        self.head = None
        self.length = 0

    def __str__(self) -> str:
        if self.head is not None:
            current = self.head
            values = [str(current.value)]
            while current.next_value is not None:
                current = current.next_value
                values.append(str(current.value))
            return '[{values}]'.format(values=' '.join(values))
        return '[]'

    def append(self, elem: Any) -> None:
        new_knot = Knot(elem)
        if self.head is None:
            self.head = new_knot
            return

        last_knot = self.head
        while last_knot.next_value:
            last_knot = last_knot.next_value
        last_knot.next_value = new_knot
        self.length += 1

    def remove(self, index: int) -> None:
        cur_knot = self.head
        cur_index = 0
        if self.length == 0 or self.length <= index:
            raise IndexError

        if cur_knot is not None:
            if index == 0:
                self.head = cur_knot.next_value
                self.length -= 1
                return

        while cur_knot.next_value is not None:
            prev = cur_knot
            cur_knot = cur_knot.next_value
            cur_index += 1
            if cur_index == index:
                prev.next_value = cur_knot.next_value
                self.length -= 1
                break

    def get(self, index: int) -> None:
        cur_knot = self.head
        cur_index = 0
        if self.length == 0 or self.length < index:
            raise IndexError

        while cur_knot.next_value is not None:
            if cur_index == index:
                return cur_knot.value
            cur_knot = cur_knot.next_value
            cur_index += 1
        return cur_knot.value

my_list = LinkedList()
my_list.append(10)
my_list.append(20)
my_list.append(30)
print('Текущий список:', my_list)
print('Получение третьего элемента:', my_list.get(2))
print('Удаление второго элемента.')
my_list.remove(1)
print('Новый список:', my_list)


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

from typing import List

class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        if len(matrix) == 0: return 0
        m, n = len(matrix), len(matrix[0])
        dp = [[0 for j in range(n)] for i in range(m)]
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == "0":
                    dp[i][j] = 0
                else:
                    dp[i][j] = dp[i - 1][j] + 1
        max_value = 0
        for line in dp:
            cur_value = self.largest_rectange_in_histogram(line)
            # print(line)
            # print(cur_value)
            # print('#' * 10)
            max_value = max(cur_value, max_value)
        return max_value

    def largest_rectange_in_histogram(self, heights):
        if len(heights) == 0: return 0
        heights.insert(0, 0)
        heights.append(0)
        ist, max_rectange = [], 0
        for i in range(0, len(heights)):
            while (len(ist) != 0 and heights[i] < heights[ist[-1]]):
                cur_index = ist[-1]
                ist.pop()
                left = ist[-1] + 1
                right = i - 1
                max_rectange = max(max_rectange, (right - left + 1) * heights[cur_index])

            ist.append(i)

        return max_rectange

if __name__ == '__main__':
    matrix1 = [
        ["1", "0", "1", "0", "0"],
        ["1", "0", "1", "1", "1"],
        ["1", "1", "1", "1", "1"],
        ["1", "0", "0", "1", "0"]
    ]
    matrix = [["0", "1"], ["0", "1"]]
    solution = Solution()
    ans = solution.maximalRectangle(matrix1)
    print('ans: ', ans)


from flask import Flask
from flask import Blueprint, flash, g, redirect, render_template, request, url_for
import rr_main
from datetime import date
today = date.today()
current_year = date.today().strftime('%Y')

import numpy as np
import pandas as pd
import random

ratings = pd.read_csv('datasets/ratings-s.csv')
users = ratings.userid.unique()

recipeeze = Flask(__name__)
theme = 'cappucino'

@recipeeze.route('/')
def index():
    bg_image = 'static/images/emy-90710FOygrg-unsplash.jpg'
    bg_mobile = 'static/images/food-photographer-david-fedulov-h-R_D-zD8KQ-unsplash.jpg'
    #get the ingredients and search
    ingredients_list = ["What's in your fridge?","List a few things. example; cheddar, broccoli"]
    return render_template('index.html', bg_image = bg_image, bg_mobile = bg_mobile,
    ingredients = ingredients_list,theme = theme)

@recipeeze.route('/recipes', methods=['POST'])
#@login_required
def recipes():
    #posting the results
    bg_image = ''
    user_1 = random.choice(users)
    user_2 = random.choice(users)
    user_3 = random.choice(users)
    ingredient_list = request.form['ingredients']

    recipe_list1 = rr_main.set_up_ml(user_1,ingredient_list) # generate a list of recommendations for each user
    recipe_list2 = rr_main.set_up_ml(user_2,ingredient_list)
    recipe_list3 = rr_main.set_up_ml(user_3,ingredient_list)

    final_recommendation = rr_main.get_final_recommendation(recipe_list1,recipe_list2,recipe_list3)
    return render_template('recipe.html',
    recipes_table = final_recommendation, bg_image = bg_image,
    ingredients = ingredient_list,theme = theme)

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


from nn_work import NeuralNetwork
import numpy as np

if __name__ == '__main__':
    X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
    y = np.array([[0], [1], [1], [0]])
    nn = NeuralNetwork([2, 4, 1], alpha=0.5)
    nn.fit(X, y, epochs=20000)
    # print(nn)

    # now that our network is trained, loop over the Xor data
    for (x, target) in zip(X, y):
        pred = nn.predict(x)[0][0]
        step = 1 if pred > 0.5 else 0
        print("[INFO] data={}, ground-truth={}, pred={:.4f}, step={}".format(x, target[0], pred, step))


#version: 1.0
#author: Jan Kurpas
#
#
#Tool to create finding charts, with objects marked.
#Start script with:
#
#python fctool.py IMAGE OBJECTS WINDOWSIZE
#
#
#IMAGE: FITS IMAGE showing the sky
#OBJECTS: ASCII File, where the first row gives the plots title, and the following rows give the objects position and name. Write each object in one row, that shall be marked by giving RA DEC STRING
#The Image will be centered on the first object.
#WINDOWSIZE: number, giving the size of the skyarea that will be plotted in arcmin=(1/60 degree)
#FILENAME: string, telling the name of the output file.
#
#Additional options can be defined below
#
#

#Additional Options
cv = 0.99  #Set Cut for percentile
obj_sep = ' ' #Set Seperator in objectlist
#colmap = 'gray' #Set Colormap (black background, white stars: gray; white background, black stars: Greys)
colmap = 'Greys' #Set Colormap (black background, white stars: gray; white background, black stars: Greys)
nr_hdu = 0 # Fits File extension number, where Image is at.
axis_hms = True #Set False if axis labels should be in degree
#arcol = 'white' #Set color of compass
arcol = 'black' #Set color of compass

#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

import sys
#Janbrauchte die folgende Zeile, wofuer auch immer
# reload(sys)
# brauchen wir fue Iris' komische Symbole (Ref J Kurpas)
#sys.setdefaultencoding('utf8')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
from astropy.visualization import simple_norm
from astropy.visualization import SqrtStretch
from astropy.visualization import PercentileInterval
from astropy.io import fits
from astropy import wcs
from astropy.nddata import Cutout2D
from astropy.coordinates import Angle

#Function calculates Angular Distance on Sky
def ang_dist(x1,x2):
    return 180*np.arccos(np.sin(x1[1]*np.pi/180)*np.sin(x2[1]*np.pi/180)+np.cos(x1[1]*np.pi/180)*np.cos(x2[1]*np.pi/180)*np.cos((x1[0]-x2[0])*np.pi/180))/np.pi

# Function calculates Percentile value
def perc(Array,lim):
    #2d Array in 1d Array umwandeln und Grenzwert fuer Percentile finden
    Lst = Array.flatten()
    Lst.sort()
    l = len(Lst)
    n = int(round(lim*l))

    #Element, dass bei Grenze
    k = Lst[n]

    #Sicherstellen, dass Normierung durchgefuerht werden kann durch Typanpassung und durchfueren der Normierung, sowie des Ersetzens aller Werte ueber dem Grenzwert durch 1
    Array = np.asarray(Array, dtype=np.float64)
    Array = Array/k
    Array[Array>1] = 1

    #Array zurueckgeben, sowie den Grenzwert an der Perzentile
    return Array,k

#Function checks string for bad characters
def cl_str(x):
    if '\r' in x:
        return x.replace('\r','')
    else:
        return x

#Control whether enough parameters are given
if len(sys.argv) >1:
    inp = sys.argv[1:]
else:
    print('Not enough arguments given.')
    exit()
if len(inp)==1 and (inp[0] == '-h' or inp[0] == '--help'):
    print('Tool to create finding charts, with objects marked.\nStart script with:\n\npython fctool.py IMAGE OBJECTS WINDOWSIZE\n\nIMAGE: FITS image showing the sky\nOBJECTS: ASCII File, where the first row gives the plots title, and the following rows give the objects position and name. Write each object in one row, that shall be marked by giving RA DEC STRING\nThe Image will be centered on the first object.\nWINDOWSIZE: number, giving the size of the skyarea that will be plotted in arcmin=(1/60 degree)\nFILENAME: string, telling the name of the output file.\n\nAdditional options can be defined in the top part of the script.')
    exit()
elif len(inp) ==3 or len(inp) ==2 or (len(inp) ==1 and (inp[0] != '-h' and inp[0] != '--help')):
    print('Not enough arguments given.')
    exit()
    # (M.C.B): I erased "len(inp) ==3".
else:
    #Get parameters
    imlnk = inp[0]
    objfl = inp[1]
    wsz = float(inp[2])
    print('Start fctool\n')
    print('Image: '+imlnk)
    print('Objectfile: '+objfl)
    print('Image Size: '+str(wsz)+' arcmin\n')

    #Get Objectinformation
    info = open(objfl, 'r')
    t = info.read()
    info.close()
    t = t.split('\n')
    title = cl_str(t[0])
    obj = []
    for g in t[1:]:
        tmp = g.split(obj_sep)
        if len(g)>2:
            if (":" in tmp[0]):
                v = tmp[0].split(':')
                RA = Angle(v[0]+'h'+v[1]+'m'+v[2]+'s', unit= 'hourangle')
                DEC = Angle(tmp[1]+'d')
            else:
                RA = Angle(tmp[0]+'d')
                DEC = Angle(tmp[1]+'d')
            s = cl_str(tmp[2])
            obj.append([RA,DEC,s])

    #Get Image
    hdu = fits.open(imlnk)
    hdr = hdu[nr_hdu].header
    dat = hdu[nr_hdu].data
    w = wcs.WCS(hdr)

    print('')
    #Get Central Object Pixelposition:
    print('Central Object Coordinates [deg]: '+str(obj[0][0].deg)+', '+str(obj[0][1].deg))
    objpix_x,objpix_y=w.wcs_world2pix(obj[0][0].deg,obj[0][1].deg,0)
    print('objpix_x,objpix_y:',objpix_x,objpix_y)
    objcoox,obcooy = w.wcs_pix2world(objpix_x,objpix_y,0)

    #Round Object Pixelcoordinates to closest Integer
    print (type(objpix_x))
    xcoord = int(round(float(objpix_x),0))
    ycoord = int(round(float(objpix_y),0))

    #Get subpixel resol.
    spgx = objpix_x-xcoord
    spgy = objpix_y-ycoord

    #print('Central Object Pixel Coordinates: '+str(objpix_x)+', '+str(objpix_y))

    #Initialize Image
    fig = plt.figure()

    #Normierung und Skalierungvornehmen
    naxisx = hdr['NAXIS1']-1
    naxisy = hdr['NAXIS2']-1

    #Determine Pixelsize:
    tpix_x1,ydum1 = w.wcs_pix2world(0,0,0,ra_dec_order = True)
    tpix_x2,ydum2 = w.wcs_pix2world(1,0,0,ra_dec_order = True)
    dx1 = ang_dist([tpix_x1,ydum1],[tpix_x2,ydum2])
    tpix_x1,ydum1 = w.wcs_pix2world(naxisx-1,naxisy,0,ra_dec_order = True)
    tpix_x2,ydum2 = w.wcs_pix2world(naxisx,naxisy,0,ra_dec_order = True)
    dx2 = ang_dist([tpix_x1,ydum1],[tpix_x2,ydum2])
    dx = (dx1+dx2)/2

    xdum1,tpix_y1 = w.wcs_pix2world(0,0,0,ra_dec_order = True)
    xdum2,tpix_y2 = w.wcs_pix2world(0,1,0,ra_dec_order = True)
    dy1 = ang_dist([xdum1,tpix_y1],[xdum2,tpix_y2])
    xdum1,tpix_y1 = w.wcs_pix2world(naxisx,naxisy-1,0,ra_dec_order = True)
    xdum2,tpix_y2 = w.wcs_pix2world(naxisx,naxisy,0,ra_dec_order = True)
    dy2 = ang_dist([xdum1,tpix_y1],[xdum2,tpix_y2])
    dy = (dy1+dy2)/2

    dx = dx #Pixelsize in deg
    dy = dy #Pixelsize in deg
    nxpix = int(round((wsz)/(60*dx),0))
    nypix = int(round(wsz/(60*dy),0))

    if nxpix%2 == 1:
        nrmwx = nxpix/2+1
    else:
        nrmwx = nxpix/2

    if nypix%2 == 1:
        nrmwy = nypix/2+1
    else:
        nrmwy = nypix/2

    gr = [0,0,0,0]  # Array mit Grenzen der Normierung

    #x-Achse
    su = 0
    so = 0
    if xcoord - nrmwx < 0:
        gr[0] = 0
        su = abs(xcoord - nrmwx)
    else :
        gr[0] = xcoord-nrmwx

    gr[1] = xcoord+ nrmwx
    if gr[1] > naxisx:
        so = gr[1]-naxisx
        gr[1] = naxisx
        gr[0] = gr[0]-so
    else:
        gr[1] = gr[1]+su

    #y-Achse
    su = 0
    so = 0
    if ycoord - nrmwy < 0:
        gr[2] = 0
        su = abs(ycoord - nrmwy)
    else :
        gr[2] = ycoord-nrmwy

    gr[3] = ycoord+ nrmwy
    if gr[3] > naxisy:
        so = gr[3]-naxisy
        gr[3] = naxisy
        gr[2] = gr[2]-so
    else:
        gr[3] = gr[3]+su

    #Fall, dass Bild kleiner als eingegebene doppelte Normierungsbreite nrmwx/nrmwy
    if naxisx <= 2*nrmwx:
        gr[0] = 0
        gr[1] = naxisx
    if naxisy <= 2*nrmwy:
        gr[2] = 0
        gr[3] = naxisy

    stretch = SqrtStretch()
    dat = np.asarray(dat, dtype=np.float64)

    #Correct for not a number values, by setting them to -100
    dat[np.isnan(dat)] = -100

    #Trail Cut-Out to get shape of cutout area, in order to normalize right
    cutout = Cutout2D(dat, (xcoord,ycoord), (nypix,nxpix), wcs = w)
    spx = int(cutout.shape[1])/2 #Get x shape of cutout area
    spy = int(cutout.shape[0])/2 #Get y shape of cutout area

    gr[0] = int(gr[0])
    gr[1] = int(gr[1])
    gr[2] = int(gr[2])
    gr[3] = int(gr[3])
    print ('gr[0]:gr[1],gr[2]:gr[3]:',gr[0],gr[1],gr[2],gr[3])
    a,p1 = perc(dat[gr[0]:gr[1],gr[2]:gr[3]],cv)
#    dummyshow = plt.imshow(dat[xcoord-spx:xcoord+spx,ycoord-spy:ycoord+spy], norm = simple_norm(dat[gr[0]:gr[1],gr[2]:gr[3]], stretch = 'sqrt', min_cut=0, max_cut=p1), cmap=colmap)
    plt.clf()
    dat = dat/p1
    dat[dat>1] = 1
    dat = stretch(dat)

    #Bereich ausschneiden
    cutout = Cutout2D(dat, (xcoord,ycoord), (nypix,nxpix), wcs = w)

    #Koordinaten hinzufuegen
    ax = plt.subplot(projection = cutout.wcs)

    #Quellausdehnung berechnen:
    bx = cutout.input_position_cutout[0]+spgx #Get x position of central object in cutout
    by = cutout.input_position_cutout[1]+spgy #Get y position of central object in cutout
    spx = cutout.shape[1] #Get x shape of cutout area
    spy = cutout.shape[0] #Get y shape of cutout area
    mf = 3
    #ccol = '#009ee7'
    ccol = 'green'
    d = spx/80
    if spx/80 < 1:
        d = 1
    r1 = Polygon([[bx+d,by],[bx+mf*d,by]],closed= True, edgecolor = ccol,facecolor = 'none')
    r2 = Polygon([[bx-d,by],[bx-mf*d,by]],closed= True, edgecolor = ccol,facecolor = 'none')
    r3 = Polygon([[bx,by+d],[bx,by+mf*d]],closed= True, edgecolor = ccol,facecolor = 'none')
    r4 = Polygon([[bx,by-d],[bx,by-mf*d]],closed= True, edgecolor = ccol,facecolor = 'none')
    plt.text(bx+d,bx+d,obj[0][2],color =ccol, transform=ax.transData)

    for adob in obj[1:]:
        adobjpix_x,adobjpix_y=w.wcs_world2pix(adob[0].deg,adob[1].deg,0)
        adobjpix_x = adobjpix_x
        adobjpix_y = adobjpix_y
        xdif = adobjpix_x-objpix_x
        ydif = adobjpix_y-objpix_y
        aobx = xdif+ bx
        aoby = ydif+ by
        lwd = 0.8
        col = 'red'
        daob = d
        if aobx>=0 and aoby >= 0 and aobx < spx+5 and aoby < spy+5:
            ax.add_patch(Polygon([[aobx+daob,aoby],[aobx+mf*daob,aoby]],closed= True, edgecolor = col,facecolor = 'none',ls = '-'))#, lw = wsz*lwd))
            ax.add_patch(Polygon([[aobx-daob,aoby],[aobx-mf*daob,aoby]],closed= True, edgecolor = col,facecolor = 'none',ls = '-'))#, lw = wsz*lwd))
            ax.add_patch(Polygon([[aobx,aoby-daob],[aobx,aoby-mf*daob]],closed= True, edgecolor = col,facecolor = 'none',ls = '-'))#, lw = wsz*lwd))
            ax.add_patch(Polygon([[aobx,aoby+daob],[aobx,aoby+mf*daob]],closed= True, edgecolor = col,facecolor = 'none',ls = '-'))#, lw = wsz*lwd))
            plt.text(aobx+daob,aoby+daob,adob[2],color = col, transform=ax.transData)
        print('Plot Star: '+adob[2]+', at '+str(adob[0].deg)+', '+str(adob[1].deg))

    #Koordinateneinstellungen vornehmen
    ax.add_patch(r1)
    ax.add_patch(r2)
    ax.add_patch(r3)
    ax.add_patch(r4)

    if axis_hms == True:
        ax.coords[0].set_major_formatter('hh:mm:ss')
        ax.coords[1].set_major_formatter('dd:mm:ss')
    else:
        ax.coords[0].set_major_formatter('d.ddd')
        ax.coords[1].set_major_formatter('d.ddd')

    ax.coords[0].set_axislabel('Right Ascension')
    ax.coords[1].set_axislabel('Declination')

    #Bild erstellen
    plt.imshow(cutout.data , cmap = colmap, origin = 'lower',vmin = 0, vmax = 1)

    #Weitere anzuzeigende Objekte Plotten
    plt.title(title)

    #Koordinatensystem
    xk = int(round(spx*0.975))
    yk = int(round(spy*0.9))
    txk1 = int(round(spx*0.9))
    txk2 = int(round(spx*0.86))
    tyk1 = int(round(spy*0.925))
    tyk2 = int(round(spy*0.95))

    q = int(round(spx*0.05))
    plt.arrow(xk,yk,(-1)*q,0,head_width=spx/50, head_length=spx/35, fc='white', ec=arcol) #x-Richtung
    plt.text(txk1,txk2,'E',color = arcol)

    plt.arrow(xk,yk,0,q,head_width=spx/50, head_length=spx/35, fc='white', ec=arcol) #Y-Richtung
    plt.text(tyk1,tyk2,'N',color = arcol)

    #Bild speichern (format with duch file extension festgelegt)
    plt.savefig(inp[3], dpi='figure', bbox_inches = 'tight')
    plt.close()
    hdu.close()
    print('Done')
    # (M.C.B): I changed inp[3] to inp[2].


with open("./main/exceptions.py", "r") as exceptions:
    with open("emeraldexceptions.txt", "w") as emeraldExceptions:
        name = ""
        for line in exceptions:
            if line.startswith("class"):
                name = line[line.find(" ")+1:line.find("(")]
            elif "self.code" in line:
                line = line.strip()
                code = line[line.find(" = ") + 3:]
                emeraldExceptions.write("public class " + name + " : EmeraldException\n"
                                        "{\n"
                                        "   public new static int code = " + code + ";\n"
                                        "   public " + name + "(string message) : base(message) { }\n"
                                        "}\n\n")


#!/usr/bin/env python3

import sys

def matches(w, evil_str):
    return [c for c in w if c in evil_str] == list(evil_str)

def main():
    words = [line.strip() for line in sys.stdin]
    evil_words = [w for w in words if (matches(w.lower(), "evil"))]
    for w in evil_words:
        print(w)

if __name__ == '__main__':
    main()


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
f = (np.exp((-x)/10))*np.sin(np.pi*x)
g = x*np.exp(-x/3)
plt.figure()
plt.plot(x, f,label='f')
plt.plot(x, g,label='g')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()


'''
在二值mask（只含有单个目标）中找到目标的bbox
'''
import time
import numpy as np

# Setup
mask = np.zeros((4000, 5000), dtype=np.bool8)
for j in range(-50, 50):
    for k in range(-50, 50):
        if np.sqrt(j**2 + k**2) < 50:
            mask[1000 + j, 2000 + k] = True
image = np.random.randint(0, 256, (4000, 5000, 3), dtype=np.uint8)
exp_image = image[951:1050, 1951:2050]
n_loops = 1000

# Method 1
t1 = time.time()
for _ in range(n_loops):
    i, j = np.where(mask)
    y, x = np.meshgrid(
        np.arange(min(i), max(i) + 1),
        np.arange(min(j), max(j) + 1),
        indexing="ij",
    )
    sub_image = image[y, x]
t2 = time.time()
print((t2 - t1) / n_loops)
assert sub_image.shape == exp_image.shape, (sub_image.shape, exp_image.shape)
assert np.all(sub_image == exp_image)

# Method 2
t1 = time.time()
for _ in range(n_loops):
    where = np.array(np.where(mask))
    y1, x1 = np.amin(where, axis=1)
    y2, x2 = np.amax(where, axis=1) + 1
    sub_image = image[y1:y2, x1:x2]
t2 = time.time()
print((t2 - t1) / n_loops)
print(x1, y1, x2, y2)
assert sub_image.shape == exp_image.shape, (sub_image.shape, exp_image.shape)
assert np.all(sub_image == exp_image)

# Method 3
t1 = time.time()
for _ in range(n_loops):
    maskx = np.any(mask, axis=0)
    masky = np.any(mask, axis=1)
    x1 = np.argmax(maskx)
    y1 = np.argmax(masky)
    x2 = len(maskx) - np.argmax(maskx[::-1])
    y2 = len(masky) - np.argmax(masky[::-1])
    sub_image = image[y1:y2, x1:x2]
t2 = time.time()
print((t2 - t1) / n_loops)
print(x1, y1, x2, y2)
assert sub_image.shape == exp_image.shape, (sub_image.shape, exp_image.shape)
assert np.all(sub_image == exp_image)


# 数据类型：字符串
str1 = "可爱多"
# 数字类型： 整形：100 、 浮点型
num = 10
num_2 = 100.05

# 布尔值 True False
a = True
b = False

# 列表 = 字典
cc = None

# 请列出你在王者荣耀当中你最熟悉的五个英雄
# 表达一组数据 - list
hero_list = ["亚瑟", "鲁班七号", "狄仁杰", "武则天", "孙尚香"]
# 有序列表
# 读取数据 -变量名[下标] -从0开始
print(hero_list[0])
# 给列表添加数据   -列表变量名append(英雄名字)  -追加到末尾
hero_list.append("芈月")
print(hero_list)

# 修改列表当中，某一个位置的值
# 先找到这个位置，然后再更换数据
hero_list[1] = "芈月"
hero_list[5] = "鲁班七号"
print("修改之后的英雄榜:", hero_list)

# 获取列表的长度   -len(列表变量名)
print(len(hero_list))

# 获取列表的最后一个元素
print(hero_list[-1])
print(hero_list[len(hero_list)-1])

# str_hero = "亚瑟、鲁班七号、狄仁杰、武则天、孙尚香"

# 字典  key = value  键值对
# 键名 = 字符串
# 键值 = 各种数据类型
# 无序 - 键名唯一
yase_dict = {"name": "亚瑟",
             "type": "战士",
             "技能": "大宝剑",
             "玩家心得": "XXXXX",
             "年龄": "3",
             }

# 取值 - 根据键名来取值 - 字典的变量名[键名]
print(yase_dict['type'])
print(yase_dict['技能'])

# 给一个字典添加键值对 - 字典的变量名[键名]=键值  键名是不存在与字典中
yase_dict['装备'] = "XXXX"
print(yase_dict)

# 加皮肤
yase_dict["skin"] = ["皮肤1", "皮肤2", "皮肤3"]
print(yase_dict)

# 修改值
yase_dict["玩家心得"] = "好好玩!"
print(yase_dict)

# 获取字典的长度   -len(字典变量名)
print(len(yase_dict))
hero_list_new = [
    {"name": "亚瑟",
     "type": "战士"},
    {"name": "鲁班七号",
     "type": "射手"},
    {"name": "狄仁杰",
     "type": "射手"},
    yase_dict
]

# 修改新英雄亚瑟的type的值
# print(hero_list_new[0]["type"] = "辅助")
print(hero_list_new)
# 删除字典中的一个键值对
yase_dict.pop("name")
print(yase_dict)


import pygame
import os
import math
import random
import time
from player import Player
from pipe import Pipe
from population import Population

population = 100 # set initial population

config = [
        # 3 input: bird y position, top pipe position and bottom pipe position
		{"nodeCount": 3, "type": "input"},
        # output 1: jump or not
		{"nodeCount": 1, "type": "output"}
	]

birds = [] # array contains bird object

def setup():
    global WIN_WIDTH
    global WIN_HEIGHT
    global FLOOR
    global STAT_FONT
    global END_FONT
    global DRAW_LINES
    global WIN
    global population
    global bg_img
    global bird_images
    global pipe_img
    global neat

    pygame.font.init()
    WIN_WIDTH = 600
    WIN_HEIGHT = 750
    FLOOR = 730

    # font style for displaying text
    STAT_FONT = pygame.font.SysFont("comicsans", 50)
    END_FONT = pygame.font.SysFont("comicsans", 70)

    # indicate whether to show line from birds to pipes or not
    # set to true if you want to draw lines
    DRAW_LINES = False

    WIN = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    pygame.display.set_caption("Flappy Bird")

    # load image assets
    pipe_img = pygame.transform.scale2x(pygame.image.load(os.path.join("img","pipe.png")).convert_alpha())
    bg_img = pygame.transform.scale(pygame.image.load(os.path.join("img","bg.png")).convert_alpha(), (600, 900))
    bird_images = [pygame.transform.scale2x(pygame.image.load(os.path.join("img","bird" + str(x) + ".png"))) for x in range(1,4)]

    # init population
    for i in range(population):
        birds.append(Player(WIN, bird_images, 200, 200))

    # init NEAT algorithm
    neat = Population(config)

def draw(birds, win, pipes):
    """draw birds to the screen \n
    add line indication for detecting closest pipes
    """
    for pipe in pipes:
        pipe.show(WIN)
    for bird in birds:
        # draw lines from bird to pipe
        if DRAW_LINES:
            try:
                # draw lines from bird to closest pipe
                pygame.draw.line(win, (255,0,0), (bird.x+bird.img.get_width()/2, bird.y + bird.img.get_height()/2), (pipes[pipe_ind].x + pipes[pipe_ind].PIPE_TOP.get_width()/2, pipes[pipe_ind].height), 5)
                pygame.draw.line(win, (255,0,0), (bird.x+bird.img.get_width()/2, bird.y + bird.img.get_height()/2), (pipes[pipe_ind].x + pipes[pipe_ind].PIPE_BOTTOM.get_width()/2, pipes[pipe_ind].bottom), 5)
            except:
                pass
        # draw bird
        if bird.dead == False:
            bird.show()
    pygame.display.update()

setup()

#player = Player(WIN, bird_images ,200, 200)
pipes = [Pipe(pipe_img, 700)]
while True:
    add_pipe = False
    rem = []
    pipe_ind = 0

    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

    if len(birds) > 0:
            if len(pipes) > 1 and birds[0].x > pipes[0].x + pipes[0].PIPE_TOP.get_width():  # determine whether to use the first or second
                pipe_ind = 1

    WIN.blit(bg_img, (0, 0))
    for pipe in pipes:
        for bird in birds:
            # detect for bird collision
            if pipe.collide(bird):
                bird.dead = True

        if pipe.x + pipe.PIPE_TOP.get_width() < 0:
            rem.append(pipe)

        if not pipe.passed and pipe.x < bird.x:
            pipe.passed = True
            add_pipe = True
        pipe.update()

    # send bird location to the nn, top pipe location and bottom pipe location
    for i in range(population):
        birds[i].update()
        neat.observe([birds[i].y, abs(birds[i].y - pipes[pipe_ind].height), abs(birds[i].y - pipes[pipe_ind].bottom)], i)

    neat.feed_forward() # feed forward the network
    decisions = neat.think() # get neural network output in form of array

    for i in range(population):
        if decisions[i] > 0.5: # for tanh activation, we decide whether to jump or not if the value is larger than 0.5
            birds[i].jump()

    finish = True
    for i in range(len(birds)):
        if birds[i].dead == False:
            finish = False
            break

    if finish:
        pipes = [Pipe(pipe_img, 700)] # start over again
        for i in range(population):
            neat.set_fitness(birds[i].score, i) # set fitness score after all birds are killed
            birds[i] = Player(WIN, bird_images , 200, 200) # create new bird at given index postion
        print(neat.print_statistic())
        neat.perform_natural_selection() # do crossover and mutation method

    for bird in birds:
            # if bird goes out of map
            if bird.y + bird.img.get_height() - 10 >= FLOOR or bird.y < -50:
                bird.dead = True
    if add_pipe:
        pipes.append(Pipe(pipe_img, 700))

    for i in rem:
        pipes.remove(i)

    draw(birds, WIN, pipes) #draw everything to the screen


# pylint: disable=W0621,C0116,R0903,E0401,W0703,W1201,missing-function-docstring,E0401,C0114,W0511,W1203,C0200,C0103,W1203
import logging

from models.section import Section
from repository.persist_fs import PersistFS as persist_fs
from tests.moke.process_fs import ProcessFS as process_fs

def test_init(get_config_map, http_url):
    actual = Section(persist_fs, process_fs, get_config_map, http_url)
    assert actual.http_url == "http://cloud.google.com/docs"
    assert actual.dir_name == "http§§§cloud.google.com§docs"
    assert actual.dir_readme_md == "http§§§cloud.google.com§docs/readme.md"

def test_write(get_config_map, http_url):
    actual = Section(persist_fs, process_fs, get_config_map, http_url)
    logging.debug(actual)

def test_build_from_dir(get_config_map, simple_http, simple_dir):
    assert (
        Section.build_from_dir(
            persist_fs, process_fs, get_config_map, simple_http
        ).dir_name
        == simple_dir
    )


"""Main module."""

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import spikedetekt2
import logging
import imp
import os.path as op

import numpy as np
import tables as tb

from .progressbar import ProgressReporter
from kwiklib.dataio import (BaseRawDataReader, read_raw, excerpt_step,
    to_contiguous, convert_dtype, KwdRawDataReader, ExperimentRawDataReader)
from spikedetekt2.processing import (bandpass_filter, apply_filter, decimate,
    get_threshold, connected_components, extract_waveform,
    compute_pcs, project_pcs, DoubleThreshold)
from kwiklib.utils import (Probe, iterkeys, debug, info, warn, exception,
    display_params, FileLogger, register, unregister)

def _import_module(path):
    module_name = op.basename(path)
    module_name = op.splitext(module_name)[0]
    return imp.load_source(module_name, path)

# -----------------------------------------------------------------------------
# Processing
# -----------------------------------------------------------------------------
def apply_threshold(chunk_fil, threshold=None, **prm):
    # Determine the chunk used for thresholding.
    if prm['detect_spikes'] == 'positive':
        chunk_detect = chunk_fil
    elif prm['detect_spikes'] == 'negative':
        chunk_detect = -chunk_fil
    elif prm['detect_spikes'] == 'both':
        chunk_detect = np.abs(chunk_fil)

    # Perform thresholding.
    # shape: (nsamples, nchannels)
    chunk_threshold = DoubleThreshold(
        strong=chunk_detect > threshold.strong,
        weak=chunk_detect > threshold.weak,
    )
    return chunk_detect, chunk_threshold

def extract_waveforms(chunk_detect=None, threshold=None,
                      chunk_fil=None, chunk_raw=None,
                      probe=None, components=None,
                      **prm):
    # For now, we use the same binary chunk for detection and extraction
    # +/-chunk, or abs(chunk), depending on the parameter 'detect_spikes'.
    chunk_extract = chunk_detect  # shape: (nsamples, nchannels)
    # This is a list of Waveform instances.
    waveforms = []
    for component in components:
        w = extract_waveform(component,
                             chunk_extract=chunk_extract,
                             chunk_fil=chunk_fil,
                             chunk_raw=chunk_raw,
                             threshold_strong=threshold.strong,
                             threshold_weak=threshold.weak,
                             probe=probe,
                             **prm)
        if w is not None:
            waveforms.append(w)

    # Remove skipped waveforms (in overlapping chunk sections).
    # waveforms = [w for w in waveforms if w is not None]
    return waveforms

def add_waveform(experiment, waveform, **prm):
    """Add a Waveform instance to an Experiment."""
    experiment.channel_groups[waveform.channel_group].spikes.add(
        time_samples=waveform.s_offset,
        time_fractional=waveform.s_frac_part,
        recording=waveform.recording,
        waveforms_raw=waveform.raw,
        waveforms_filtered=waveform.fil,
        masks=waveform.masks,
    )

def save_features(experiment, **prm):
    """Compute the features from the waveforms and save them in the experiment
    dataset."""
    nwaveforms_max = prm['pca_nwaveforms_max']
    npcs = prm['nfeatures_per_channel']
    kwik = experiment._files['kwik']

    for chgrp in iterkeys(experiment.channel_groups):
        spikes = experiment.channel_groups[chgrp].spikes
        # Extract a subset of the saveforms.
        nspikes = len(spikes)

        # We convert the extendable features_masks array to a
        # contiguous array.
        if prm.get('features_contiguous', True):
            # Make sure to update the PyTables node after the recreation,
            # to avoid ClosedNodeError.
            spikes.features_masks = to_contiguous(spikes.features_masks, nspikes=nspikes)
        else:
            warn(("The features array has not been converted to a contiguous "
                  "array."))

        # Skip the channel group if there are no spikes.
        if nspikes == 0:
            continue
        nwaveforms = min(nspikes, nwaveforms_max)
        step = excerpt_step(nspikes, nexcerpts=nwaveforms, excerpt_size=1)
        waveforms_subset = spikes.waveforms_filtered[::step]

        # With this option, PCs are directly provided in the PRM file as
        # a NumPy array
        if prm.get('canonical_pcs', None) is not None:
            pcs = prm['canonical_pcs']
            assert isinstance(pcs, np.ndarray)
        else:
            # We take the masks in order to compute the PCs only on
            # the unmasked spikes, for each channel.
            masks = spikes.features_masks[::step,::npcs,1]  # (nspikes, nchannels)
            # Compute the PCs.
            pcs = compute_pcs(waveforms_subset, npcs=npcs, masks=masks)

        # Add PCs to the KWIK file
        kwik.createArray(experiment.channel_groups[chgrp]._node, 'pca_waveforms',
            pcs)

        # Project the waveforms on the PCs and compute the features.
        # WARNING: optimization: we could load and project waveforms by chunks.
        for i, waveform in enumerate(spikes.waveforms_filtered):
            # Convert waveforms from int16 to float32 with scaling
            # before computing PCA so as to avoid getting huge numbers.
            waveform = convert_dtype(waveform, np.float32)
            features = project_pcs(waveform, pcs)
            spikes.features_masks[i,:,0] = features.ravel()

# -----------------------------------------------------------------------------
# File logger
# -----------------------------------------------------------------------------
def create_file_logger(filename):
    # global LOGGER_FILE
    LOGGER_FILE = FileLogger(filename, name='file',
        level=logging.DEBUG)
    register(LOGGER_FILE)
    return LOGGER_FILE

def close_file_logger(LOGGER_FILE):
    unregister(LOGGER_FILE)

# -----------------------------------------------------------------------------
# Main loop
# -----------------------------------------------------------------------------
def run(raw_data=None, experiment=None, prm=None, probe=None,
        _debug=False, convert_only=False):
    """This main function takes raw data (either as a RawReader, or a path
    to a filename, or an array) and executes the main algorithm (filtering,
    spike detection, extraction...)."""
    assert experiment is not None, ("An Experiment instance needs to be "
        "provided in order to write the output.")

    # Create file logger for the experiment.
    LOGGER_FILE = create_file_logger(experiment.gen_filename('log'))

    # Get parameters from the PRM dictionary.
    chunk_size = prm.get('chunk_size', None)
    chunk_overlap = prm.get('chunk_overlap', 0)
    nchannels = prm.get('nchannels', None)

    # Ensure a RawDataReader is instantiated.
    if raw_data is not None:
        if not isinstance(raw_data, BaseRawDataReader):
            raw_data = read_raw(raw_data, nchannels=nchannels)
    else:
        raw_data = read_raw(experiment)

    # Log.
    if convert_only:
        info("Starting file conversion only. Klusta version {1:s}, on {0:s}".format((str(raw_data)), spikedetekt2.__version__))
        info("Running spike detection on a single chunk of spikes only, so as to have some information")
        first_chunk_detected = False # horrible hack - detects spikes on one chunk only so KV doesn't complain
    else:
        info("Starting SpikeDetekt version {1:s} on {0:s}".format((str(raw_data)), spikedetekt2.__version__))
    debug("Parameters: \n" + (display_params(prm)))

    # Get the bandpass filter.
    filter = bandpass_filter(**prm)

    if not (convert_only and first_chunk_detected):
        # Compute the strong threshold across excerpts uniformly scattered across the
        # whole recording.
        threshold = get_threshold(raw_data, filter=filter,
                                  channels=probe.channels, **prm)
        assert not np.isnan(threshold.weak).any()
        assert not np.isnan(threshold.strong).any()
        debug("Threshold: " + str(threshold))

        # Debug module.
        diagnostics_path = prm.get('diagnostics_path', None)
        if diagnostics_path:
            diagnostics_mod = _import_module(diagnostics_path)
            if not hasattr(diagnostics_mod, 'diagnostics'):
                raise ValueError("The diagnostics module must implement a "
                                 "'diagnostics()' function.")
            diagnostics_fun = diagnostics_mod.diagnostics
        else:
            diagnostics_fun = None

    # Progress bar.
    progress_bar = ProgressReporter(period=30.)
    nspikes = 0

    # Loop through all chunks with overlap.
    for chunk in raw_data.chunks(chunk_size=chunk_size,
                                 chunk_overlap=chunk_overlap,):
        # Log.
        debug("Processing chunk {0:s}...".format(chunk))

        nsamples = chunk.nsamples
        rec = chunk.recording
        nrecs = chunk.nrecordings
        s_end = chunk.s_end

        # Filter the (full) chunk.
        chunk_raw = chunk.data_chunk_full  # shape: (nsamples, nchannels)
        chunk_fil = apply_filter(chunk_raw, filter=filter)

        i = chunk.keep_start - chunk.s_start
        j = chunk.keep_end - chunk.s_start

        # Add the data to the KWD files.
        if prm.get('save_raw', False):
            # Do not append the raw data to the .kwd file if we're already reading
            # from the .kwd file.
            if not isinstance(raw_data, (KwdRawDataReader, ExperimentRawDataReader)):
                # Save raw data.
                experiment.recordings[chunk.recording].raw.append(convert_dtype(chunk.data_chunk_keep, np.int16))

        if prm.get('save_high', False):
            # Save high-pass filtered data: need to remove the overlapping
            # sections.
            chunk_fil_keep = chunk_fil[i:j,:]
            experiment.recordings[chunk.recording].high.append(convert_dtype(chunk_fil_keep, np.int16))

        if prm.get('save_low', True):
            # Save LFP.
            chunk_low = decimate(chunk_raw)
            chunk_low_keep = chunk_low[i//16:j//16,:]
            experiment.recordings[chunk.recording].low.append(convert_dtype(chunk_low_keep, np.int16))

        if not (convert_only and first_chunk_detected):
            # Apply thresholds.
            chunk_detect, chunk_threshold = apply_threshold(chunk_fil,
                threshold=threshold, **prm)

            # Remove dead channels.
            dead = np.setdiff1d(np.arange(nchannels), probe.channels)
            chunk_detect[:,dead] = 0
            chunk_threshold.strong[:,dead] = 0
            chunk_threshold.weak[:,dead] = 0

            # Find connected component (strong threshold). Return list of
            # Component instances.
            components = connected_components(
                chunk_strong=chunk_threshold.strong,
                chunk_weak=chunk_threshold.weak,
                probe_adjacency_list=probe.adjacency_list,
                chunk=chunk, **prm)

            # Now we extract the spike in each component.
            waveforms = extract_waveforms(chunk_detect=chunk_detect,
                threshold=threshold, chunk_fil=chunk_fil, chunk_raw=chunk_raw,
                probe=probe, components=components, **prm)

            # DEBUG module.
            # Execute the debug script.
            if diagnostics_fun:
                try:
                    diagnostics_fun(**locals())
                except Exception as e:
                    warn("The diagnostics module failed: " + e.message)

            # Log number of spikes in the chunk.
            nspikes += len(waveforms)

            # We sort waveforms by increasing order of fractional time.
            [add_waveform(experiment, waveform) for waveform in sorted(waveforms)]

            first_chunk_detected = True

        # Update the progress bar.
        progress_bar.update(rec/float(nrecs) + (float(s_end) / (nsamples*nrecs)),
            '%d spikes found.' % (nspikes))

        # DEBUG: keep only the first shank.
        if _debug:
            break

    # Feature extraction.
    save_features(experiment, **prm)

    close_file_logger(LOGGER_FILE)
    progress_bar.finish()


#import art
import random
from art import logo, vs
from game_data import data
from replit import clear

def get_random_account():
    """Get data from random account"""
    return random.choice(data)

def format_data(account):
    """format the acct dat into printable formats."""
    account_name = account['name']
    account_descr = account['description']
    account_country = account['country']
    return (f"{account_name},a {account_descr}, from {account_country}")

def check_answer(player_guess, a_followers, b_followers):
    """Take the user guess and follower acounts and returns if they got it right."""
    if a_followers > b_followers:
        return player_guess == 'a'
    else:
        return player_guess == 'b'

def game():
    print(logo)
    score = 0
    game_should_continue = True
    compare_a = get_random_account()
    compare_b = get_random_account()
    #Make the game repeatable.
    while game_should_continue:
        #generate a random acct from the game data.
        #Making account at position B become the next position A

        compare_a = compare_b
        compare_b = get_random_account()
        while compare_a == compare_b:
            compare_b = get_random_account()

        print(f"Compare A: {format_data(compare_a)}.")
        print(vs)
        print(f"Against B: {format_data(compare_b)}.")

        #Ask user for a guess

        player_guess = input(
            "Who have more followers? Type 'A' or 'B': ").lower()

        #Check if the user is correct
        a_follower_account = compare_a['follower_count']
        b_follower_account = compare_b['follower_count']

        is_correct = check_answer(player_guess, a_follower_account,
                                  b_follower_account)

        #Clear the screen betwee rounds.
        clear()
        print(logo)
        #Give user feedback on their guess
        ##Score keeping.
        if is_correct:
            score += 1
            print(f"You're right! Current score: {score}.")
        else:
            game_should_continue = False
            print(f"Oops, that's wrong. Finallt score: {score}.")

game()


# "x.py" as in "execute"
import os
import sys
import subprocess
import requests
from datetime import datetime, timedelta
from threading import Thread, Event

token = "{{ token }}"
logs_url = "{{ logs_url }}"
heartbeat_url = "{{ heartbeat_url }}"

class HeartbeatThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(10):
            requests.get(heartbeat_url, headers={"Authorization": token})

stop_flag = Event()
thread = HeartbeatThread(stop_flag)
thread.start()

process = subprocess.Popen(["sh", "wrapper.sh"], stdout=subprocess.PIPE)

last_post = datetime.utcnow()
five_seconds = timedelta(seconds=5)
log_lines = b""

for line in iter(process.stdout.readline, b""):

    log_lines += line

    if datetime.utcnow() - last_post > five_seconds:
        last_post = datetime.utcnow()
        requests.post(logs_url, headers={"Authorization": token}, data=log_lines)
        log_lines = b""

requests.post(logs_url, headers={"Authorization": token}, data=log_lines)
stop_flag.set()


# tic-tac-toe

def init_board():
    return [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

def player1_move(board, x, y):
    board[x][y] = 1

def player2_move(board, x, y):
    board[x][y] = 2

def print_board(board):
    for y in range(0, 3):
        line = ''
        for x in range(0, 3):
            if board[x][y] == 0:
                line = line + '-'
            elif board[x][y] == 1:
                line = line + 'X'
            elif board[x][y] == 2:
                line = line + 'O'
        print(line)

def who_won(board):
    # 0 means no one win, 1 means player 1 wins, 2 means player 2 wins
    result = 0
    # check row
    for y in range(0, 3):
        result = check_winning(board[0][y], board[1][y], board[2][y])
        if result > 0:
            return result
    # check col
    for x in range(0, 3):
        result = check_winning(board[x][0], board[x][1], board[x][2])
        if result > 0:
            return result
    # check diagonal:
    result = check_winning(board[0][0], board[1][1], board[2][2])
    if result > 0:
        return result
    result = check_winning(board[2][0], board[1][1], board[0][2])
    if result > 0:
        return result
    return 0

def check_winning(a, b, c):
    if (a == 1) and (b == 1) and (c == 1):
        return 1
    elif (a == 2) and (b == 2) and (c == 2):
        return 2
    else:
        return 0

def print_line():
    print("")

def is_full(board):
    result = True
    for y in range(0, 3):
        for x in range(0, 3):
            if board[x][y] == 0:
                result = False
                break
    return result

def input_player_move(player_number):
    x = input("Player {0}, enter your move X:".format(player_number))
    y = input("Player {0}, enter your move Y:".format(player_number))
    return int(x), int(y)

def computer_move(turn, board):
    if is_full(board) and who_won(board):
        return -1, -1, 0

    best_score = -999999999
    best_x = -1
    best_y = -1
    for y in range(0, 3):
        for x in range(0, 3):
            if board[x][y] == 0:
                score = evaluate_move(turn, x, y, board)
                if score > best_score:
                    best_score = score
                    best_x = x
                    best_y = y
    # print(best_score)
    return best_x, best_y, best_score

def evaluate_move(player_number, tx, ty, board):
    score = -99999999999
    # already occupied ==> invalid move
    if board[tx][ty] > 0:
        return -999999
    # propose move
    board[tx][ty] = player_number
    # horizontal
    score += get_score(player_number, get_board(board, tx-2, ty), get_board(board, tx - 1, ty), get_board(board, tx,ty))
    score += get_score(player_number, get_board(board, tx-1, ty), get_board(board, tx, ty), get_board(board, tx + 1, ty))
    score += get_score(player_number, get_board(board, tx, ty), get_board(board, tx + 1, ty), get_board(board, tx + 2, ty))
    # vertical
    score += get_score(player_number, get_board(board, tx, ty-2), get_board(board, tx, ty-1), get_board(board, tx, ty))
    score += get_score(player_number, get_board(board, tx, ty-1), get_board(board, tx, ty), get_board(board, tx, ty+1))
    score += get_score(player_number, get_board(board, tx, ty), get_board(board, tx, ty+1), get_board(board, tx, ty+2))
    # diagonal NW -> SE
    score += get_score(player_number, get_board(board, tx-2, ty-2), get_board(board, tx-1, ty-1), get_board(board, tx, ty))
    score += get_score(player_number, get_board(board, tx-1, ty-1), get_board(board, tx, ty), get_board(board, tx+1, ty+1))
    score += get_score(player_number, get_board(board, tx, ty), get_board(board, tx+1, ty+1), get_board(board, tx+2, ty+2))
    # diagonal NE -> SW
    score += get_score(player_number, get_board(board, tx+2, ty-2), get_board(board, tx+1, ty-1), get_board(board, tx, ty))
    score += get_score(player_number, get_board(board, tx+1, ty-1), get_board(board, tx, ty), get_board(board, tx-1, ty+1))
    score += get_score(player_number, get_board(board, tx, ty), get_board(board, tx-1, ty+1), get_board(board, tx-2, ty+2))

    opponent = get_opponent(player_number)
    temp_x, temp_y, temp_score = computer_move(opponent, board)
    score -= temp_score

    # undo move
    board[tx][ty] = 0
    return score

def get_score(player_number, a, b, c):
    if check_mate(player_number, a, b, c):
        return 1000000
    if can_block(player_number, a, b, c):
        return 1000
    if check_opponent(player_number, a, b, c):
        return 100
    if has_potential(player_number, a, b, c):
        return 10
    return 0

def check_mate(player_number, a, b, c):
    if a == player_number and b == player_number and c == player_number:
        return True
    else:
        return False

def can_block(player_number, a, b, c):
    opponent = get_opponent(player_number)
    if a == player_number and b == opponent and c == opponent:
        return True
    elif a == opponent and b == player_number and c == opponent:
        return True
    elif a == opponent and b == opponent and c == player_number:
        return True
    else:
        return False

def check_opponent(player_number, a, b, c):
    if a == player_number and b == player_number and c == 0:
        return True
    elif a == player_number and b == 0 and c == player_number:
        return True
    elif a == 0 and b == player_number and c == player_number:
        return True
    else:
        return False

def has_potential(player_number, a, b, c):
    if a == player_number and b == 0 and c == 0:
        return True
    if a == 0 and b == player_number and c == 0:
        return True
    if a == 0 and b == 0 and c == player_number:
        return True

def get_opponent(player_number):
    if player_number == 1:
        return 2
    else:
        return 1

def get_board(board, x, y):
    if x < 0 or x > 2:
        return -1
    if y < 0 or y > 2:
        return -1
    return board[x][y]

def main():
    board = init_board()
    won = 0
    turn = 1
    computer_player = True
    while (won == 0) and (is_full(board) is False):
        print_board(board)
        print_line()
        if turn == 1:
            x, y = input_player_move(turn)
        else:
            if computer_player is False:
                x, y = input_player_move(turn)
            else:
                x, y, score = computer_move(turn, board)
                print("Computer move to {0}, {1}".format(x, y))
        if turn == 1:
            player1_move(board, x, y)
        if turn == 2:
            player2_move(board, x, y)
        won = who_won(board)
        if turn == 1:
            turn = 2
        else:
            turn = 1
    print_board(board)
    print_line()
    if won > 0:
        print("Player {0} has won!!".format(won))
    else:
        print("It is a tie.")

'''
    print(board)
    print(board[0][0])
    print(board[0][1])
    print_board(board)
    print_line()
    player1_move(board, 1, 1)
    print_board(board)
    print_line()
    player2_move(board, 1, 0)
    print_board(board)
    print_line()
    player1_move(board, 0, 0)
    x, y = input_player_move(1)
    print("{0}, {1}".format(x, y))
'''

if __name__ == "__main__":
    main()


import click
import openai

from skainet import utils
from skainet.data import CONFIG

DEFAULT_CHAT_MODEL = CONFIG["moderation"]["model"]

@click.command()
@click.argument("input", type=utils.Prompt(), default="")
@click.option(
    "-m",
    "--model",
    type=str,
    default=DEFAULT_CHAT_MODEL,
    help=f"Model selection. Default is {DEFAULT_CHAT_MODEL}.",
)
def moderate(input: str, model: str):
    """Check if text violates OpenAI's Content Policy"""
    try:
        response = openai.Moderation.create(
            input=input,
            model=model,
        )
    except openai.OpenAIError as e:
        utils.handle_openai_error(e)
    else:
        click.echo(response)


from a10sdk.common.A10BaseClass import A10BaseClass

class Udp(A10BaseClass):

    """Class Description::
    L4 UDP switch config.

    Class udp supports CRUD Operations and inherits from `common/A10BaseClass`.
    This class is the `"PARENT"` class for this module.`

    :param short: {"description": "Short lived session", "format": "flag", "default": 0, "optional": true, "not": "immediate", "type": "number"}
    :param qos: {"description": "QOS level (number)", "format": "number", "type": "number", "maximum": 63, "minimum": 1, "optional": true}
    :param name: {"description": "Fast UDP Template Name", "format": "string-rlx", "default": "default", "minLength": 1, "optional": false, "maxLength": 63, "type": "string"}
    :param age: {"optional": true, "minimum": 1, "type": "number", "maximum": 31, "format": "number"}
    :param stateless_conn_timeout: {"description": "Stateless Current Connection Timeout value (5 - 120 seconds) (idle timeout in second, default 120)", "format": "number", "default": 120, "optional": true, "maximum": 120, "minimum": 5, "type": "number"}
    :param idle_timeout: {"description": "Idle Timeout value (default 120 seconds) (idle timeout in second, default 120)", "format": "number", "default": 120, "optional": true, "maximum": 2097151, "minimum": 1, "type": "number"}
    :param re_select_if_server_down: {"default": 0, "optional": true, "type": "number", "description": "re-select another server if service port is down", "format": "flag"}
    :param immediate: {"description": "Immediate Removal after Transaction", "format": "flag", "default": 0, "optional": true, "not": "short", "type": "number"}
    :param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

    URL for this object::
    `https://<Hostname|Ip address>//axapi/v3/slb/template/udp/{name}`.

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""
        self.required = [ "name"]

        self.b_key = "udp"
        self.a10_url="/axapi/v3/slb/template/udp/{name}"
        self.DeviceProxy = ""
        self.short = ""
        self.qos = ""
        self.name = ""
        self.age = ""
        self.stateless_conn_timeout = ""
        self.idle_timeout = ""
        self.re_select_if_server_down = ""
        self.immediate = ""
        self.uuid = ""

        for keys, value in kwargs.items():
            setattr(self,keys, value)


#!/usr/bin/env python

## 2021/05/09. Levi King. From the blog,
## https://naturallanguagepuzzling.blogspot.com
## This code was written to assist with the 2021/05/09 Sunday Puzzle:
## https://www.npr.org/2021/05/09/995172987/sunday-puzzle-supermarket-scramble
## That puzzle:
"""
This week's challenge comes from listener Jim Dale, of Plano, Texas. Think of a
word with six syllables that's spelled with only 11 letters — and the four
middle syllables have the same vowel. What word is it?
"""

## You'll need to download the file as I did:
## https://github.com/dwyl/english-words/blob/master/words_alpha.txt
lexfilename = "../annex/words_alpha.txt"

## open & read lexicon file, return lexicon of only words of length n
def get_n_lex(some_lex_filename, my_n):
    lexfile = open(some_lex_filename, "r")
    full_lex = lexfile.readlines()
    print("Number of words in the full lexicon: "+str(len(full_lex)))
    n_lex = [l.strip().lower() for l in full_lex if len(l.strip())==my_n]
    print("Number of "+str(my_n)+"-letter words in lexicon: "+str(len(n_lex)))
    return n_lex

def n_of_a_kind_vowels(myn, some_lex):
	vowels = ['a', 'e', 'i', 'o', 'u', 'y']
	consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
	quads = []
	keep = []
	for lx in some_lex:
		midlex = lx[1:-1]
		for vw in vowels:
			if midlex.count(vw) >= myn:
				quads.append(lx)
	for qd in quads:
		qvs = 0
		for vw in vowels:
			qvs+=qd.count(vw)
		if qvs >= 6:
			keep.append(qd)
	print(len(keep))
	for kp in keep:
		print(kp)

def main():
	target_vowels = 4
	eleven_lex = get_n_lex(lexfilename, 11)
	n_of_a_kind_vowels(target_vowels, eleven_lex)

if __name__ == "__main__":
    main()


from gpiozero_ps.generators import constant
from effects.fire import fire_sources
from effects.rainbow import rainbow_sources
from machine.components import Component, LightSourceMixin, SourceConsumerMixin

class Neopixel(Component, LightSourceMixin):
    def __init__(self, device_id, pix_from, num_pixels, name, neopixel_strip):
        Component.__init__(self, device_id, name)
        LightSourceMixin.__init__(self)
        self._setting = 'rgb'
        self._sources = [(constant(0), constant(0), constant(0)) for _ in range(num_pixels)]
        self._setting_params.update({
            "r": 0.5,
            "g": 0.5,
            "b": 0.5,
            "brightness": 0.5,
            "speed": 0.5,
            "intensity": 0.5,
        })
        self._device = _NeopixelDevice(neopixel_strip, pix_from, num_pixels, self._param_generator("brightness"))
        self._num_pixels = num_pixels

    def _turn_on(self, effect=True):
        self._do_update_settings()
        if effect:
            self._device.set_sources([self._wrap_source_in_turn_on_effect(self._wrap_source_in_additional_effect(s)) for s in self._sources])
        else:
            self._device.set_sources([self._wrap_source_in_additional_effect(s) for s in self._sources])

    def _turn_off(self, effect=True):
        if effect:
            self._device.set_sources([self._wrap_source_in_turn_off_effect(self._wrap_source_in_additional_effect(s)) for s in self._sources])
        else:
            self._device.set_sources([(constant(0), constant(0), constant(0)) for _ in range(self._num_pixels)])

    def _current_value(self):
        return self._device.value

    def _update_current_setting(self):
        self._do_update_settings()
        if self._on:
            self._device.set_sources([self._wrap_source_in_additional_effect(s) for s in self._sources])

    def _do_update_settings(self):
        if self.setting == "fire":
            self._fire()
        elif self.setting == "rgb":
            self._rgb()
        elif self.setting == "rainbow":
            self._rainbow()
        else:
            raise Exception("Unknown setting: " + self.setting)

    def _fire(self):
        self._set_sources([fire_sources(self._param_generator("intensity")) for _ in range(self._num_pixels)])

    def _rgb(self):
        set_defaults(self._setting_params, {'r': 0.5, 'g': 0.5, 'b': 0.5})
        self._set_sources([(
            self._param_generator("r"), self._param_generator("g"), self._param_generator("b")
        ) for _ in range(self._num_pixels)])

    def _rainbow(self):
        self._set_sources([rainbow_sources(speed_generator=self._param_generator('speed')) for _ in range(self._num_pixels)])

    def _set_sources(self, sources):
        self._sources = sources

    def _type(self):
        return 'neopixel'

def set_defaults(params, defaults):
    for name, val in defaults.items():
        if name not in params:
            params[name] = val

class _NeopixelDevice(SourceConsumerMixin):
    def __init__(self, neopixel_strip, pix_from, num_pixels, brightness_generator):
        SourceConsumerMixin.__init__(self)
        self._strip = neopixel_strip
        self.pix_from = pix_from
        self._num_pixels = num_pixels
        self._value = [(0, 0, 0) for _ in range(num_pixels)]
        self._brightness_generator = brightness_generator
        self.source = None

    @property
    def value(self):
        # list of rgb values
        return self._value

    @value.setter
    def value(self, val):
        brightness = next(self._brightness_generator)
        for i in range(self._num_pixels):
            r, g, b = val[i]
            self._value[i] = (r * brightness, g * brightness, b * brightness)
            self._strip.set_pixel(self.pix_from + i, self._value[i])

    def set_sources(self, sources):
        def generator():
            while True:
                yield [(next(r), next(g), next(b)) for (r, g, b) in sources]
        self.source = generator()


################################
#Project Euler

#Problem Statement 1
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.

################################
import time

multiple1=3
multiple2=5

def one_divN():
	sumN=0
	inputN=input('Input the natural number')
	for i in range(1,int(inputN)):
		if not (i % multiple1) or not(i % multiple2):
			sumN=sumN+i
	print('The sum of natural numbers is =',sumN)
	return sumN

start_time = time.time()
one_divN()

print("--- %s seconds ---" % (time.time() - start_time))


"""
Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
Example: countdown(5) should return [5,4,3,2,1,0]
"""
def countdown(x):
    new_list = []
    for i in range(x, -1, -1):
        new_list.append(i)
    return new_list
print(countdown(5))

"""
Create a function that will receive a list with two numbers. Print the first value and return the second.
Example: print_and_return([1,2]) should print 1 and return 2
"""
def print_and_return(ab):
    print(ab[0])
    return ab[1]
print(print_and_return([3,4]))

"""
Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
"""
def first_plus_length(a):
    sum = len(a) + a[0]
    return sum
print(first_plus_length([2,2,3,4,5,6]))

"""
Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False
Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
Example: values_greater_than_second([3]) should return False
"""
def values_greater_than_second(b):
    newer_list = []
    if len(b) == 1:
        return False
    for i in range(len(b)):
        if b[1] < b[i]:
            newer_list.append(b[i])
            amount = len(newer_list)
    print(amount)
    return newer_list
print(values_greater_than_second([5,3]))

"""
Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
Example: length_and_value(4,7) should return [7,7,7,7]
Example: length_and_value(6,2) should return [2,2,2,2,2,2]
"""
def length_and_value(fixed_size, fixed_value):
    newest_list = []
    for i in range(fixed_size):
        newest_list.append(fixed_value)
    return newest_list
print(length_and_value(10,9))


def solve(s):
    s = input()

    for x in s.split():
        s = s.replace(x, x.capitalize())
    return s

    # first, last = s.split()
    # first =first[0].upper() + first[1:]
    # last =last[0].upper() + last[1:]
    # s = first +" "+ last
    # print(s)


from datetime import datetime
import numpy as np
import json
from pandas import read_csv
from pandas import datetime
from matplotlib import pyplot
from sklearn.model_selection import train_test_split
from statsmodels.tsa.arima_model import ARIMA
from sklearn.metrics import mean_squared_error

with open("../Data/companies.json") as file:
    # Load data from the json file
    data = json.load(file)
    quarter_dates = []
    revenue = []
    for x in data['companies'][1]['income_statement']:
        # Fetch date information
        date_list = x['date'].split('-')
        date = datetime(int(date_list[0]), int(date_list[1]), int(date_list[2]))
        quarter_dates.append(date.toordinal())

        # Fetch revenue information
        revenue.append(float(x['Revenue']))

    # Reverse all the dates in the list
    quarter_dates.reverse()
    revenue.reverse()

    # Split data for training and testing
    quarter_dates_train, quarter_dates_test, revenue_train, revenue_test = \
        train_test_split(np.array(quarter_dates), np.array(revenue), test_size=0.30)

    history = [x for x in revenue_train]

    predictions = list()
    for t in range(len(revenue_test)):
        # this model will be different on each iteration because we are appending our predictions to history
        model = ARIMA(history, order=(5, 1, 0))
        model_fit = model.fit(disp=0)
        output = model_fit.forecast()
        yhat = output[0]
        predictions.append(yhat)
        obs = revenue_test[t]
        history.append(obs)
        print('predicted=%f, expected=%f' % (yhat, obs))
    error = mean_squared_error(revenue_test, predictions)
    print('Test MSE: %.3f' % error)

    # plot
    pyplot.plot(revenue_test, label="Actual values")
    pyplot.plot(predictions, color='red', label="Prediction")
    pyplot.xlabel("Date")
    pyplot.ylabel("Revenue ($ Billion)")
    pyplot.legend()
    pyplot.title("Revenue Prediction for the AEP ticker (ARIMA)")
    pyplot.show()


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :param l1: ListNode
        :param l2: ListNode
        :return: ListNode
        """
        current = dummy = ListNode(0)

        while l1 and l2:
            if l1.val < l2.val:
                current.next = l1
                l1 = l1.next
            else:
                current.next = l2
                l2 = l2.next
            current = current.next

        current.next = l1 or l2

        return dummy.next


from flask import Flask

app = Flask(__name__)

def get_fibonacci_numbers(n):
    numbers = [1, 1]
    for i in range(2, n):
        numbers.append(numbers[i - 1] + numbers[i - 2])
    return numbers

def get_fib(n):
    a, b = 1, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

@app.route("/fibonacci")
def fibonacci():
    return ' '.join([str(s) for s in get_fibonacci_numbers(n)])

@app.route('/fib')
def fib():
    return '<br>'.join([str(s) for s in get_fib(100)])

if __name__ == '__main__':
    n = 100
    app.run(debug=True)


from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from utilities.media import write_file
from utilities.media import remove_old_file
from utilities.image_base64 import encode_image, image_exists
from django.db import models

models.options.DEFAULT_NAMES += ('show_in_admin_menu',)

class CustomUser(AbstractUser):
    logo = models.ImageField(
            _('Logo'),
            upload_to='uploads/users/',
            null=True,
            blank=True
        )

    nick = models.CharField(
            _('NICK_LABEL'),
            max_length=255,
            unique=True,
            blank=True
        )

    autor_info = models.TextField(
            _('About You'),
            blank=True
        )
    def __unicode__(self):
        return '%s' % (self.username)

    def __init__(self, *args, **kwargs):
        super(CustomUser, self).__init__(*args, **kwargs)
        if self.logo is not None:
            self._prev_logo = self.logo

    class Meta:
        #swappable = 'AUTH_USER_MODEL'
        verbose_name = _('User')
        verbose_name_plural = _('Users')
        get_latest_by = "created"
        ordering = ('-id',)
        db_table = 'auth_custom_user'
        app_label = 'user'
        show_in_admin_menu = False

    def update_logo(self):
        instance = self
        if instance.logo is not None:
            write_file(instance.logo, instance.id)

            if len(instance._prev_logo.name)> 0:
                if instance._prev_logo.name != instance.logo.name:
                    remove_old_file(instance._prev_logo, instance.id)

            CustomUser.objects.filter(id=instance.id).update(
                    logo=instance.logo
                )

    def get_logo(self, width=38, height=38):
        image = self.logo.name
        logo = settings.STATIC_URL + "images/avatar-%s-%s.png" % (width,height)
        if len(image) and image_exists(image, self.id):
            logo = "data:image/png;base64," + encode_image( image, self.id, width, height)
        return logo

    def get_logo60x60(self,width=60,height=60):
        image = self.logo.name
        logo = settings.STATIC_URL + "img/coment.jpg" % (width,height)
        if len(image) and image_exists(image, self.id):
            logo = "data:image/png;base64," + encode_image( image, self.id, width, height)
        return logo
    def get_logo_comment(self):
        image = self.logo.name
        logo = settings.STATIC_URL + "img/coment.jpg"
        if len(image) and image_exists(image, self.id):
            logo = "data:image/png;base64," + encode_image( image, self.id, width, height)
        return logo


import requests
from datetime import datetime
import json
from config import API_KEY

class WeatherInfo:
    # Constructor for the class
    def __init__(self, cityName, lat = None, lon = None):
        # location info
        self.lat = lat
        self.lon = lon
        self.cityName = cityName

        # weather info
        self.timezone = ""
        self.tempC = ""
        self.tempF = ""
        self.feelsLikeC = ""
        self.feelsLikeF = ""
        self.pressure = ""
        self.humidity = ""
        self.windSpeed = ""
        self.weatherDescription = ""
        self.lastUpdate = None

    def GenerateRequest(self, type) -> str:
        # default setting
        limit = 1
        exclude = "minutely,hourly,daily,alerts"

        # default api call:
        # geocoding api: http://api.openweathermap.org/geo/1.0/direct?q={city name},{state code},{country code}&limit={limit}&appid={API key}
        # weather api: https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}

        if type == "geo":
            return f"http://api.openweathermap.org/geo/1.0/direct?q={self.cityName}&limit={limit}&appid={API_KEY}"
        else:
            return f"https://api.openweathermap.org/data/3.0/onecall?lat={self.lat}&lon={self.lon}&exclude={exclude}&appid={API_KEY}"

    # Getting weather info
    def GetInfo(self):
        if not self.lat or not self.lon:
            geoRequest = self.GenerateRequest("geo")
            r = requests.get(geoRequest)
            if r.status_code == 200:
                getjson = json.loads(r.text)
                self.lat =  getjson[0]["lat"]
                self.lon = getjson[0]["lon"]

        weatherRequest = self.GenerateRequest("weather")
        r = requests.get(weatherRequest)
        if r.status_code == 200:
            getjson = json.loads(r.text)
            self.timezone = getjson["timezone"]

            tempVal = getjson["current"]["temp"]
            self.tempC = self.TempConvert("c", tempVal)
            self.tempF = self.TempConvert("f", tempVal)

            feelsLikeVal = getjson["current"]["feels_like"]
            self.feelsLikeC = self.TempConvert("c", feelsLikeVal)
            self.feelsLikeF = self.TempConvert("f", feelsLikeVal)

            self.pressure = getjson["current"]["pressure"]
            self.humidity = getjson["current"]["humidity"]
            self.windSpeed = getjson["current"]["wind_speed"]
            self.weatherDescription = getjson["current"]["weather"][0]["description"]

    # This function mostly likely use for testing
    def PrintInfo(self) -> None:
        print(f"Location: {self.cityName}")
        print(f"Timezone: {self.timezone}")
        print("temp: {:0.2f}ºC, feels like: {:0.2f}ºC".format(self.tempC, self.feelsLikeC))
        print(f"Pressure: {self.pressure} hPA")
        print(f"Humidity: {self.humidity}%")
        print(f"Wind Speed: {self.windSpeed} m/s")
        print(f"Weather Description: {self.weatherDescription}")

    def TempConvert(self, type, temp) -> None:
        if type == "c":
            return round(temp - 273.15,2)
        elif type == "f":
            return round((temp - 273.15) * 9/5 + 32,2)