import os
import sys
import time
import argparse
import json
import requests

# The search engines we are using
SEARCH_ENGINES = ("bing", "google")

# The endpoints for the API of the search engines
BING_API_ENDPOINT = "https://api.cognitive.microsoft.com/bing/v7.0/images/search"
GOOGLE_API_ENDPOINT = "https://www.googleapis.com/customsearch/v1"

# The queries of the image search
QUERIES = [
    "makeup before after",
    "makeup before after instagram",
    "before and after makeup faces",
    "makeup transformation faces",
]

# Search results limit (this limit is soft/approximate)
MAX_RESULTS = 1e6

# Get absolute path of this file and force relative-to-file paths
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
# The checkpoint file recording the search progress
CHECKPOINT = os.path.join(FILE_DIR, "searcher.json")
# The file where image_urls will be exported to
IMAGE_URLS = os.path.join(FILE_DIR, "image_urls.csv")

def init_api(search_engines):
    """
    Initializes the necessary environment variables for the API requests.
    """
    if "bing" in search_engines and "BING_API_KEY" not in os.environ:
        os.environ["BING_API_KEY"] = input("Please enter your Bing API Key: ")
    if "google" in search_engines and "GOOGLE_API_KEY" not in os.environ:
        os.environ["GOOGLE_API_KEY"] = input("Please enter your Google API Key: ")
    if "google" in search_engines and "GOOGLE_CX" not in os.environ:
        os.environ["GOOGLE_CX"] = input("Please enter your Google Custom Search CX: ")

def api_search(endpoint, headers, params):
    """
    Performs an API request to a search API (either Bing or Google in our case).

    Args:
        search_engine: The name of the search engine to use.
        headers: The headers of the API request.
        params: The parameters of the API request.
        ignore_error: Ignore request error and continue without prompting the user.

    Returns:
        A tuple containing the response, as a dictionary, and its status code.
    """

    time.sleep(0.5)  # this ensures at most 2 requests per second
    result = None
    status_code = -1

    try:
        response = requests.get(endpoint, headers=headers, params=params)
        status_code = response.status_code
        response.raise_for_status()
        result = response.json()
    except requests.exceptions.HTTPError as e:
        print("Bad request! ({})".format(status_code))
        print(e)

    return result, status_code

###########################
class DataSearcher:
    def __init__(self, queries=[], checkpoint="checkpoint", load_from_checkpoint=True):

        # Sanity checks
        for query in queries: assert isinstance(query, str)
        assert isinstance(checkpoint, str) and checkpoint != ""

        self.checkpoint = checkpoint
        self.queries = queries       # the search queries for building the dataset
        self.query_index = 0         # the index of the current search query
        self.image_urls = []         # the url of the contents (images)
        self.reset_search_indices()  # reset api-specific search index values

        # Load from checkpoint, if any
        if load_from_checkpoint:
            self.load()

    def reset_search_indices(self):
        """
        Reset the indices that describe the search progress of the current query.
        """
        self.bing_offset = 0   # offset value of the image search (for Bing)
        self.google_start = 1  # offset value of the image search (for Google)

    ###########################
    def search(self, search_engines=["bing"]):
        """
        Search for images from all the queries using Bing's and Google's API.
        """

        # Check if given search engines are string and make them lowercase
        for s in search_engines: assert isinstance(s, str)
        search_engines = [s.lower() for s in search_engines]

        # Initialize API if not done yet
        init_api(search_engines)

        # Try to search for images using the given search_engines
        try:
            start_time = time.time()  # track time
            while self.query_index < len(self.queries):
                # Get current query
                query = self.queries[self.query_index]

                # Search for images
                if "bing" in search_engines: self.search_bing(query)
                if "google" in search_engines: self.search_google(query)

                # Finished search for this query
                self.query_index += 1
                self.reset_search_indices()

            print()
            print("Total image urls found = {}.".format(len(self.image_urls)))
            print("Time elapsed = {:.3f} seconds.".format(time.time() - start_time))

            # Save final results, and export image urls
            self.save()

        except (KeyboardInterrupt, SystemExit):
            print("Interrupted.")
            self.save()

        except Exception as e:
            # Interrupt all exceptions and keyboard interrupt to save progress
            print("Error!")
            self.save()
            print("\nRaising error:")
            raise e

    def search_bing(self, query):
        """
        Searches for `query` using Bing image search API.

        Args:
            query: query: The query of the search.
        """

        old_image_urls = set(self.image_urls)  # to avoid duplicates
        totalEstimatedMatches = 1e6  # to ensure that offset is smaller first

        # Define headers and default params of bing image search api
        headers = {"Ocp-Apim-Subscription-Key": os.environ["BING_API_KEY"]}
        params = {
            "q": query,
            "offset": self.bing_offset,
            "imageType": "photo",
        }  # "size": "Medium", "imageContent": "Face" or "Portrait",

        # Continue the search until all results are exhausted
        print("\nStarting Bing image search for query '%s'." % query)
        while self.bing_offset < min(totalEstimatedMatches, MAX_RESULTS):

            # Search for images starting from the specified offset
            print("Searching from offset %d ... " % self.bing_offset, end="")
            params["offset"] = self.bing_offset
            result, status_code = api_search(BING_API_ENDPOINT, headers, params)

            # Checking result of api search
            if result is None or "value" not in result:
                print("Trying again...")
                continue
            print("Done.")

            # Search for image urls and filter out the already saved urls
            new_image_urls = [image["contentUrl"] for image in result["value"]
                if image["contentUrl"] not in old_image_urls]
            self.image_urls += new_image_urls
            print("  Retrieved {} new image urls.".format(len(new_image_urls)))

            # Update offset and estimated matches
            if "totalEstimatedMatches" in result:
                totalEstimatedMatches = result["totalEstimatedMatches"]
            if "nextOffset" in result:
                self.bing_offset = result["nextOffset"]
            else:
                self.bing_offset += len(result["value"])

        print("Bing image search for query '{}' done.".format(query))
        print("Retrieved {} new image urls in total.".format(
            len(self.image_urls) - len(old_image_urls)))

    def search_google(self, query):
        """
        Searches for `query` using Google custom search API.

        Args:
            query: The query of the search.
        """

        old_image_urls = set(self.image_urls)  # to avoid duplicates

         # Define headers and default params of google custom search api
        params = {
            "key": os.environ["GOOGLE_API_KEY"],
            "q": query,
            "cx": os.environ["GOOGLE_CX"],
            "searchType": "image",
            "start": 1,
            "num": 10,
        }

        # Continue the search until all results are exhausted
        print("\nStarting Google image search for query: '%s'." % query)
        while self.google_start < min(100, MAX_RESULTS):

            # Search for images starting from start index
            print("Searching from start index %d ... " % self.google_start, end="")
            params["start"] = self.google_start
            result, status_code = api_search("google", {}, params)

            # Check results of api search
            if result is None:
                print("Trying again...")
                continue
            print("Done")

            # Search for image urls and filter out the already saved urls
            new_image_urls = [image["link"] for image in result["items"]
                if image["link"] not in old_image_urls]
            self.image_urls += new_image_urls
            print("  Retrieved {} new image urls.".format(len(new_image_urls)))

            # Update start index
            self.google_start += params["num"]

        print("Google image search done. ")
        print("Retrieved {} new image urls in total.".format(
            len(self.image_urls) - len(old_image_urls)))

    ###########################
    def load(self, checkpoint=None):
        """
        Loads the searcher from a json checkpoint file.

        Args:
            checkpoint: The name of the checkpoint file.
        """

        if checkpoint is None: checkpoint = self.checkpoint

        print("[*] Loading search progress from '{}'... ".format(checkpoint), end="")
        if os.path.isfile(checkpoint):
            with open(checkpoint, "r") as f:
                dataset_metadata = json.load(f)
                print("Loaded.")
                self.from_json(dataset_metadata)
        else:
            print("Couldn't find file.")
            if "n" == input("Type anything to start a new search or 'n' to exit: "):
                sys.exit()

    def save(self, checkpoint=None):
        """
        Saves the searcher to a json checkpoint file.

        Args:
            checkpoint: The name of the checkpoint file.
        """

        if checkpoint is None: checkpoint = self.checkpoint

        print("[*] Saving search progress to '{}'... ".format(checkpoint), end="")
        with open(checkpoint, "w") as f:
            search_json = self.to_json()
            json.dump(search_json, f)
            print("Saved.")

    def from_json(self, search_json):
        """
        Copy the data from `search_json` to `self`.

        Args:
            search_json: A dict holding the progress data of the given searcher.
        """

        self.query_index  = search_json["query_index"]
        self.queries      = search_json["queries"]
        self.bing_offset  = search_json["bing_offset"]
        self.google_start = search_json["google_start"]
        self.image_urls   = search_json["image_urls"]

    def to_json(self):
        """
        Copy the data from `self` to `search_json`.

        Returns:
            A dict holding the progress data of `self`.
        """

        search_json = {}
        search_json["query_index"]  = self.query_index
        search_json["queries"]      = self.queries
        search_json["bing_offset"]  = self.bing_offset
        search_json["google_start"] = self.google_start
        search_json["image_urls"]   = self.image_urls

        return search_json

    def export_image_urls(self, fname=IMAGE_URLS):
        """
        Creates a simple file of image urls, one url per line

        Args:
            fname: The name of the file where the urls will be written.
        """

        with open(fname, "w") as f:
            f.writelines(image_url + "\n" for image_url in self.image_urls)

###########################
def main(args):

    searcher_params = {
        "queries": args.queries,
        "checkpoint": args.checkpoint,
    }

    searcher = DataSearcher(**searcher_params)
    searcher.search(args.search_engines)
    searcher.export_image_urls(args.out)

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="Search images using Bing and Google.")

    parser.add_argument("--search_engines", nargs="+", type=str, default=SEARCH_ENGINES,
        help="the search engines to be used.",
        choices=SEARCH_ENGINES)
    parser.add_argument("-q", "--queries", nargs="+", type=str, default=QUERIES,
        help="list of queries to be searched.")
    parser.add_argument("--checkpoint", type=str, default=CHECKPOINT,
        help="name of checkpoint file.")
    parser.add_argument("-o", "--out", type=str, default=IMAGE_URLS,
        help="the output file where the urls of the images will be saved.")

    args = parser.parse_args()

    main(args)


from flask import render_template
from app import app
from app.forms import LoginForm

@app.route('/')
@app.route('/index')
def index():
    user = {'username': 'Den Smyk'}
    posts = [
        {
            'author' : {'username': 'John'},
            'body': 'Beautiful day in Portland!'
        },
        {
            'author' : {'username': 'Susan'},
            'body': 'The Avengers movie was so cool!'
        },
        {
            'author' : {'username': 'Іванко'},
            'body': 'Яка погана риба у вас!'
        }
    ]
    return render_template('index.html', title='Home', user=user, posts = posts)

@app.route('/login')
def login():
    form = LoginForm()
    return render_template('login.html', title='Sign In', form=form)


#Developed by Henrique Treza

#sistema que calcula a diaria e valor do km rodado para o cliente

qtdDia = int(input('Por quantos dia o carro foi alugado: '))
kmRodados = float(input('Quantos quilometros o sr(a) percorreu com o carro alugado: '))

valorDiaria = qtdDia * 60
valorKm = kmRodados * 0.15
valorTotal = valorDiaria + valorKm

print('O sr(a) ficou {} dias com o carro alugado e rodou {}'
      'Km, o valor total a pagar é de R${:.2f}'.format(qtdDia, kmRodados, valorTotal))


# -*- coding: utf-8 -*-
"""
Created on Mon Apr  6 18:50:48 2020

@author: Adref
"""

# This module is here to illustrate the principal points about MapReduce

# Imports

from collections import defaultdict

# Example of a simple function to count words in a collection
# Here we can easily do that

def wordCount(text):
    counts = defaultdict(int)
    for word in text.split():
        counts[word.lower()] += 1
    return counts

'''
Now if we have a text wich has more than a 30 M words we can't do the count with a simple function, thats take a lot of time
In this case we can illustrate the main aspect of MapReduce
We are going to work on two extracts from the text of the song "Le Jour se lève" by Grand Corps Malade

'''

# We supposed that our data is splited and cleaned from the stop words, etc finally we got that

D1 = {"./lot1.txt" : "jour lève notre grissaille"}
D2 = {"./lot2.txt" : "trottoir notre ruelle notre tour"}
D3 = {"./lot3.txt" : "jour lève notre envie vous"}
D4 = {"./lot4.txt" : "faire comprendre tous notre tour"}

def map(key, value):
    intermediate = []
    for word in value.split():
        intermediate.append((word, 1))
    return intermediate

'''
Example :
    (Lot1, "jour lève notre grissaille") -> [(jour, 1), (lève, 1), (notre, 1), (grissaille, 1)]
'''

# now we can go to implement the reduce function
# so we have for each key a list of values, the main goal of reduce is to compute all times the key appear in fragments
# input : (key, list_values) - output : (key, value)
def reduce(key, values):
    result = 0
    for c in values:
        result += c
    return (key, result)

'''
MapReduce -> " divide and rule "

the main steps :
    1. Choose a way to split the data
    2. Choose the key to use for the targeted problem
    3. Write the function code for the MAP operation
    4. Write the function code for the REDUCE operation

'''

# the MapReduce is a good strategy, but it isn't always easy to reformulate
# It's even sometimes impossible  !!!!

# To familiarize with the MapReduce logique we go to implement others examples

'''
First Example: Multiplication (Matrix * Vector) for the famous alogrithm PageRank used to schedule
              the results of a research web

steps :

    - Matrix is stocked as a triplet (i, j, M[i][j]) and we don't represent the 0's positions
    - The same thing for the Vector V (i, V[i])
    - here we have 2 cases:

        ./ Case 1: V is small enough ro fit in the memory of the Map node

            * Map(key, value) will give us the peers (i, M[i][j] * V[i])
                SHUFFLE & SORT : Groups all values assosicieted with the same key i in a pair (i, [v1, v2, ...])
            * Reduce(key, value) will sum all vaulues with a gaven key

        ./ Case 2: V is too large to fit in the memory of the Map node

            Here we have to split V to horizontal stripes and M to virticla stripes and we apply the same strategy
'''

'''
Second Example: Navigate the database tables (Films, directors)

            FILMS(ID_Film*, Title, Nb_hours, #ID_Director)
            Directors(ID_Director*, Name)

the problem can be easy using SQL but when we are in big dimension, here we will need an other solution

we will use Reduce-Side Join (mean that the join operation we will apply it in the REDUCE part)

Steps:

    - Concatination of the tables on one unique table
    - Apply map(key, value) here the key is the name of file (last table) and value is the content <string, int, string>
        example: (123, (Films, Fast&Furious))
    - SHUFFLE & SORT to structure the results of map() as peers (key, [v1, v2, ...])
        example: (123, [(Films, F&F), (Director, James)])
    - Apply reduce(key, value) collect the films title for the same director

'''

def map(key,value):
    intermediate = []
    for i in value:
        intermediate.append((i[1], (i[0], i[1:])))
    return intermediate


from keras.datasets import mnist
from keras.optimizers import SGD
from keras.utils import to_categorical

import create_model as cm
import read_data as rd

## Creating the model

data_shape = (28, 28, 1)

model = cm.create_model(data_shape)

model.summary()

## Compiling the model

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(
        loss='categorical_crossentropy',
        optimizer=sgd,
        metrics=['accuracy']
        )

## Training

try:
        (x_train, y_train), (x_test, y_test) = rd.read_data("/data")
        using_floydhub = True
except IOError:
        print("Couldn't open the dataset in /data, loading keras dataset")
        (x_train, y_train), (x_test, y_test) = mnist.load_data()
        using_floydhub = False

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

model.fit(x_train, y_train,
        epochs=20,
        batch_size=128)

## Evaluation
score = model.evaluate(x_test, y_test, batch_size=128)
print("\n", "Model accuracy: ", score[1], "\n")

## save model
if using_floydhub:
        output_dir = '/output/'
else:
        output_dir = './output/'
        if not os.path.exists(output_dir):
                os.makedirs(output_dir)

model.save(output_dir+'nikulaj_model.hdf5')


import pymongo

if __name__ == "__main__":
    client = pymongo.MongoClient("mongodb://localhost:27017/")

    all_db_name = client.list_database_names()
    print(all_db_name)

    colletn = client["ayush"]
    print(colletn.list_collection_names())


# requirements a < b > c OR a  > b < c
# check array of input int on a rolling basis
# 12134 returns 110
# results 100% correct
def isZigzag(numbers):
	array_length = len(numbers)
	# omit arrays less than 3 digits
	if array_length < 3:
		return [0]
	num_groups = array_length - 2
	print(array_length, num_groups)
	current_group = 0
	i = 0
	output = []
	while current_group < num_groups:
		# case 1
		first = numbers[i]
		second = numbers[i+1]
		third = numbers[i+2]
		if (first < second) and (second > third):
			output.append(1)
		elif (first > second) and (second < third):
			output.append(1)
		else:
			output.append(0)
		i+=1
		current_group +=1
	return output

answers = [[1, 1, 0]]
case_dict = {
# case 1: positive missing value
"case1" : [1, 2, 1, 3 , 4],
# case 2: positive no missing values
"case2" : [1, 2, 3],
# case 3: negative values
"case3" : [-5, -1, -2],
# case 4: one neg value
"case4" : [-3],
# case 5: one pos value
"case5" : [1],
# case 6: mixed values missing values
"case6" : [-5000, -100000, 5, 1, 2],
# case 7: mixed values no missing values
"case7" : [-5000, -100000, 3, 1, 2],
# case 8: two gaps
"case8" : [1, 2, 4, 5, 7], # expect 3,
# biggest value is 0
"case9" : [-1,-2,-3,0] #  expect 1
}

test_cases = []
for key in case_dict:
	test_cases.append(case_dict[key])

def run_tests(test_cases, answers):
	"""
	Runs all test cases to compare actual results to expected results.
	Prints results to console.
	:param test_cases: array with [[tests array]]
	:param answers: expected answer array
	:return: prints to console
	"""
	results = []
	i = 0
	for test in test_cases:
		# input array, k
		results = isZigzag(test)
		if (results == answers[i]):
			print("Passed: Test case %s"%str(test))
			i +=1
		else:
			print(("Failed: Test case %s, Expected: %s, Actual: %s" %(str(test), str(answers[i]), str(results))))
			i += 1

run_tests(test_cases,answers)


# %% [markdown]
# # Assignment 4
# | Topic | Information |
# | --------  |  -------- |
# | Team Members       | Antonio Cascio & Krystian Confeiteiro |
# | Professor  | Dr. Jack |
# | Course     | DS 440 - 01DB |
# | Assignment | Assignment 4 |
# | Date       | 09/29/2023 (submitted **10/03/2023**) |
#
# ## Assignment Objective
# Use [seaborn](https://seaborn.pydata.org/) to do [explorative data analysis (EDA)](https://en.wikipedia.org/wiki/Exploratory_data_analysis) with this `.csv` file in Google Colab, generate 5 different graphs and explain the results in the resultant graphs using the flight delay statistics of flights from Daytona Beach to ATL and CLT are recorded from [FAA ASPM website](https://aspm.faa.gov/apm/sys/main.asp) and saved in `DS440_assignment4_data_FA23.csv` from the [DS 440 - Assignment 4 FA23 Canvas page](https://erau.instructure.com/courses/163647/assignments/3312890#submit). You can *also* download the data from in our [Assignment 4 Google Drive folder](https://drive.google.com/drive/folders/1wWIdr0zu7_Q7yCXqqM01zviF58LwTHqo?usp=sharing).
#
# # Assignment Layout
# - Part 1
#   - Reading & analysis of data
#   - Discuss analysis of the data
# - Part 2
#   - Plotting & data visualization
#   - Make five plots and discuss them
#
# ## Part Sources
# ### Part 1
# - Type(s) of statistical analysis
#     - Descriptive statistics
#     - Probability distributions
#     - Multivariate analysis
# - Types of plots
#   1. Heatmap
#   2. Horizontal bar plot
#   3. Conditional kernel density estimate
#   4. Diagonal correlation matrix
#   5. Histogram
#
# # Assignment Checklist
# - Read the dataset with [pandas](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shape.html) or [seaborn](https://seaborn.pydata.org/)
# - Complete explorative data analysis on the flight delay statistics dataset
# - Create five plots
# - Plot explanations

# %% [markdown]
# # Part 1

# %% [markdown]
# ## Reading & Analysis

# %%
import pandas as pd

# read data with pandas
DATA = pd.read_csv("DS440_assignment4_data_FA23.csv")
DESCRIPTION = DATA.describe()

print("Dataset shape:\n", DATA.shape)
print("Dataset:")
DATA.head(15)

# %%
print("\nDescriptive analysis of dataset:\n-------------------------------\n")

# %%
import warnings
from typing import Literal, Tuple

import seaborn as sns
from matplotlib import pyplot as plt
from pandas import DataFrame

warnings.filterwarnings("ignore")

def plt_catplot(
    data: DataFrame = None,
    xy_hue: Tuple[str, str, str] = None,
    save_as: str = None,
    plt_type: Literal["bar", "violin", "swarm"] = None,
):
    if plt_type in {"bar", "violin", "swarm"}:
        FIG = sns.catplot(
            data=data, kind=plt_type, x=xy_hue[0], y=xy_hue[1], hue=xy_hue[2]
        )
        if save_as:
            FIG.savefig(save_as)
    elif not plt_type:
        for plttype in ["bar", "violin", "swarm"]:
            FIG2 = sns.catplot(
                data=data, kind=plttype, x=xy_hue[0], y=xy_hue[1], hue=xy_hue[2]
            )
            FIG2.savefig(f"{plttype}.jpg")

XY_HUE = ("GateDepartureDelay", "ArrivalHour", "FlightCount")
with plt.ioff():
    # bar, swarm, and violin plots
    plt_catplot(DATA, XY_HUE)

    # line plot
    fig = sns.lineplot(x=XY_HUE[0], y=XY_HUE[1], hue=XY_HUE[2], data=DATA)
    fig = fig.get_figure()
    fig.savefig("lineplot.jpg")

    # final plot: grouped barplot
    X, Y, HUE = "FlightCount", "DepartureHour", "Arrival"
    G = sns.catplot(
        data=DATA,
        kind="bar",
        x=X,
        y=Y,
        hue=HUE,
        errorbar="sd",
        palette="dark",
        alpha=0.6,
        height=6,
    )

    G.despine(left=True)
    G.set_axis_labels("On time Dept.", "On Time Arrivals")
    G.legend.set_title("Depts. & Arrivals")
    G.savefig("grouped_bar.jpg")

Fall 2023/DS 440/(001) Assignments/Assignment 4/cascio_and_confeiteiro_DS440_assignment_4.py


# Don't ask me why this looks like a fucking shit! Just go and make a fukcking PR as i'm fucking lazy to do these things! Fuck Off!

import os
from os import getenv

from pyrogram import Client
from dotenv import load_dotenv
from helpers.modhelps import fetch_heroku_git_url

load_dotenv()

SESSION_NAME = getenv("SESSION_NAME", "session")
BOT_TOKEN = getenv("BOT_TOKEN")

API_ID = int(getenv("API_ID"))
API_HASH = getenv("API_HASH")

DURATION_LIMIT = int(getenv("DURATION_LIMIT", "7"))

COMMAND_PREFIXES = list(getenv("COMMAND_PREFIXES", "/ !").split())

# Your Telegram User ID
BOT_OWNER = int(os.environ.get("BOT_OWNER"))
# Sudo users IDs, They are admins everywhere
SUDO_USERS = list(map(int, getenv("SUDO_USERS").split()))
# Your Bot's Username without "@"
BOT_USERNAME = os.environ.get("BOT_USERNAME")
# Your MongoDB url
DATABASE_URL = os.environ.get("DATABASE_URL")
# Your Log Channel! Make a private channel and get it's ID
LOG_CHANNEL = int(os.environ.get("LOG_CHANNEL"))
# If you need to broadcast messages as a copy or Forwarded Message
BROADCAST_AS_COPY = bool(os.environ.get("BROADCAST_AS_COPY", False))
# Thumbnail URL
THUMB_URL = os.environ.get("THUMB_URL", "https://telegra.ph/file/2ed47c81eda6b0624021d.jpg")
# Your Updates Channel! Don't Put Anything If you don't have one
UPDATES_CHANNEL = os.environ.get("UPDATES_CHANNEL", "NexaBotsUpdates")

# Your ARQ API Key
ARQ_API_KEY = getenv("ARQ_API_KEY")
# Don't Change Anything Here
ARQ_API_URL = "https://grambuilders.tech/"

# Updator Configs
HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME", None)
HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY", None)
UPSTREAM_REPO = os.environ.get("UPSTREAM_REPO", "https://github.com/Itz-fork/Callsmusic-Plus")
U_BRANCH = "master"
HEROKU_URL = fetch_heroku_git_url(HEROKU_API_KEY, HEROKU_APP_NAME)

# Versions
cp_version = "v2.9.3.2"
nexaub_version = "v0.4"


import tkinter as tk
from tkinter import ttk
from PIL import ImageTk

def nameSign():
    #创建窗口
    global window
    window = tk.Tk()
    window.geometry('1050x660')
    window.resizable(0, 0)
    #设置标题
    window.title('艺术签名')
    #设置背景图片的路径
    bgPath = "./images/bg1.jpg"
    #加载背景图片
    bgImg = ImageTk.PhotoImage(file=bgPath)
    #设置窗口背景
    bg = tk.Label(window,width=1050,height=660,image=bgImg)
    bg.pack()
    #设置开始按钮的图片路径
    startPath = "./images/start.png"
    #加载开始按钮
    startImg = ImageTk.PhotoImage(file=startPath)
    #添加开始按钮
    start = tk.Button(window,image=startImg,bd=0,width=179,height=70,
                      command=inputName)
    start.place(x=438,y=466)
    window.mainloop()

# 按钮事件函数inputName
def inputName():
    global window
    window.destroy()
    #创建窗口
    window = tk.Tk()
    window.geometry('1050x660')
    window.resizable(0,0)
    #窗口标题
    window.title('艺术签名')
    bgImg = ImageTk.PhotoImage(file="./images/bg3.jpg")
    bg = tk.Label(window,width=1050,height=660,image=bgImg)
    bg.pack()
    #字体路径
    fontPath = "./font/simhei.ttf"
    #颜色字符
    color = '#ffd46c'
    name = tk.Label(window,text='姓名',bg=color,font=(fontPath,18))
    style = tk.Label(window,text='样式',bg=color,font=(fontPath,18))
    name.place(x=370,y=165)
    style.place(x=370,y=235)
    window.mainloop()

# 程序开始
nameSign()


import pandas as pd
import csv
from collections import defaultdict, Counter

#Percentage of Hobbyist & not Hobbyist. [%age of people coding as a hobby??]
with open('survey_results_public.csv') as f:
    csv_reader = csv.DictReader(f)

    #hobbyist_counter= {'Yes':0,
    #                  'No': 0
    #                 }
    #hobbyist_counter = defaultdict(int)
    hobbyist_counter = Counter()

    for line in csv_reader:
        hobbyist_counter[line["Hobbyist"]] += 1

    total = hobbyist_counter['Yes'] + hobbyist_counter['No']

    percentage_yes = hobbyist_counter['Yes']/total * 100
    percentage_yes = round(percentage_yes,2)

    percentage_no = hobbyist_counter['No']/total * 100
    percentage_no = round(percentage_no,2)

    print(f'Percentage of people that do coding as a hobby: {percentage_yes}')
    print(f'Percentage of people that don\'t coding as a hobby: {percentage_no}')

#for plotting results
from matplotlib import pyplot as plt
plt.style.use('fivethirtyeight')

slices = [ percentage_yes, percentage_no ]
labels = ['people that like', 'people that don\'t']
explode= [ 0, 0.1 ]

plt.pie(slices, labels=labels, wedgeprops={'edgecolor':'black'},
        explode=explode,shadow=True, startangle=90, autopct='%1.1f%%')
plt.title("Coding As a Hobby")
plt.tight_layout()
plt.show()


# Problem Statement: https://leetcode.com/problems/evaluate-division/

class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        # Step 1. Build the Graph
        graph = collections.defaultdict(dict)
        for (x, y), val in zip(equations, values):
            graph[x][y] = val
            graph[y][x] = 1.0 / val
        print(graph)

        # Step 2. DFS function
        def dfs(x, y, visited):
            # neither x not y exists
            if x not in graph or y not in graph:
                return -1.0

            # x points to y
            if y in graph[x]:
                return graph[x][y]

            # x maybe connected to y through other nodes
            # use dfs to see if there is a path from x to y
            for i in graph[x]:
                if i not in visited:
                    visited.add(i)
                    temp = dfs(i, y, visited)
                    if temp == -1:
                        continue
                    else:
                        return graph[x][i] * temp
            return -1

        # go through each of the queries and find the value
        res = []
        for query in queries:
            res.append(dfs(query[0], query[1], set()))
        return res


from tqdm import tqdm
from dataset import SentimentClassifierDataset
from torch.utils.data import DataLoader
import config
import torch
import numpy as np
from sklearn import svm

def get_features(model, train=True, text=None):
    if train == True:
        dataset = SentimentClassifierDataset()
        n_samples = len(dataset)
        train_dataloader = DataLoader(
            dataset, batch_size=config.BATCH_SIZE, shuffle=False)
        labels = []
        features = []
        device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
        model.to(device)
        with torch.no_grad():
            for ind, d in tqdm(enumerate(train_dataloader), total=len(train_dataloader)):
                input_ids = d['input_ids'].to(device).long()
                attention_mask = d['attention_mask'].to(device).long()
                label = np.array(d['label'])
                labels.extend(label)
                feature = model(input_ids, attention_mask)
                features.extend(feature)
                del ind
                del d
        return np.array(features), np.array(labels)

    else:
        device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
        model.to(device)
        dataset = SentimentClassifierDataset(train=False, text=text)
        input_ids = [dataset.get_tokens(dataset.data)]
        attention_mask = dataset.get_attention_mask(np.array(input_ids[0]))

        with torch.no_grad():
            input_ids = torch.tensor(input_ids).to(device).long()
            attention_mask = torch.tensor(attention_mask).to(device).long()
            feature = model(input_ids, attention_mask)

        return np.array(feature)

def train_fn(X_train, y_train):
    clf = svm.SVC()
    clf.fit(X_train, y_train)
    return clf

def eval_fn(clf, X_test):
    return clf.predict(X_test)

def test_results(clf, test_data):
    return clf.predict(test_data)


from collections import deque
import sys
input = sys.stdin.readline

# 변수 선언
N = int(input())
RGB = [list(map(str, input().strip())) for _ in range(N)]
visit = [[False for _ in range(N)] for _ in range(N)]
answer = [0, 0]
queue = deque()

# bfs 선언
def bfs(x, y):
    queue.append([x, y])
    visit[x][y] = True
    color = RGB[x][y]

    while queue:
        x, y = queue.popleft()
        dx = [1, -1, 0, 0]
        dy = [0, 0, 1, -1]

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < N and 0 <= ny < N:
                # 색깔이 같고, 방문하지 않았다면 다음 탐색 대상
                if color == RGB[nx][ny] and not visit[nx][ny]:
                    queue.append([nx, ny])
                    visit[nx][ny] = True
    return None

# 탐색 시작: 일반인일때
for x in range(N):
    for y in range(N):
        if not visit[x][y]:
            bfs(x, y)
            answer[0] += 1

# 적녹색약은 빨강과 그린을 구별할 수 없다. 따라서 R 또는 G를 둘 중 하나로 통일한다.
for x in range(N):
    for y in range(N):
        if RGB[x][y] == 'G':
            RGB[x][y] = 'R'

# 재탐색해야 되니 방문 기록을 초기화해주자
visit = [[False for _ in range(N)] for _ in range(N)]

# 탐색 시작: 적녹색약일때
for x in range(N):
    for y in range(N):
        if not visit[x][y]:
            bfs(x, y)
            answer[1] += 1

# 정답 출력
for i in range(2):
    print(answer[i], end=" ")


# The program takes in the number of test cases in the first line of input.
# This is followed by space-separated values of m,n, and s that indicate the number of rows, columns, and length of string respectively.
# The following line is the string of length 's' that needs to be inserted spirally inward into a matrix.
# The output of each test case will be the matrix with the required string entered spirally.

t=int(input())
i=0

while(i!=t):
    test=list(map(int,input().split()))
    string=input()
    m=test[0]
    n=test[1]
    s=test[2]
    top=0
    bottom=m-1
    left=0
    right=n-1
    dir=0
    j=0
    matrix=[[None for h in range(n)] for l in range(m)]
    while top<=bottom and left<=right:
        if dir==0: #left to right
            for k in range(left,right+1):
                matrix[top][k]=string[j]
                j=(j+1)%s
            top+=1
        elif dir==1:
            for k in range(top,bottom+1):
                matrix[k][right]=string[j]
                j=(j+1)%s
            right-=1
        elif dir==2:
            for k in range(right,left-1,-1):
                matrix[bottom][k]=string[j]
                j=(j+1)%s
            bottom-=1
        elif dir==3:
            for k in range(bottom,top-1,-1):
                matrix[k][left]=string[j]
                j=(j+1)%s
            left+=1
        dir=(dir+1)%4

    i+=1
    for g in range(m):
        for v in range(n):
            print(matrix[g][v],end=' ')
        print()


# Consecutive prime sum
#
# The prime 41, can be written as the sum of six consecutive primes:
#
# 41 = 2 + 3 + 5 + 7 + 11 + 13
# This is the longest sum of consecutive primes that adds to a prime below one-hundred.
#
# The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
#
# Which prime, below one-million, can be written as the sum of the most consecutive primes?

# !!! work only if you know numbers 'below' and 'terms' !!!

import sympy

def prime_(below):
    prime_numbers = []
    n = 1
    while True:
        if sympy.isprime(n):
            if n < below:
                prime_numbers.append(n)
            else:
                break
        n += 1
    return prime_numbers

def prime_sum(below, terms):
    list_ = prime_(below)
    result = 0
    a, b = 0, terms
    while True:
        if result < sum(list_[a:b]):
            result = sum(list_[a:b])
        a += 1
        b += 1
        if result >= below:
            break
        print(result)

if __name__ == '__main__':
    prime_sum(1000000, 543)


import logging
import json
import azure.functions as func
from .classes import Dolar

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    try:
        dolar = Dolar()

        value = dolar.get_value()
    except:
        value = 'None'

    if value:
        return func.HttpResponse(
            json.dumps(value)
        )
    else:
        return func.HttpResponse(
            {'error': '400'},
            status_code=100
        )


from __future__ import annotations

from argparse import ArgumentParser
from typing import Sequence
from coverage import Coverage, CoverageException

def make_html_report(db: str, report: str) -> int:
    try:
        cov = Coverage(db)
        cov.load()
        cov.html_report(directory=report)
        return 0

    except CoverageException as e:
        print(str(e))
        return 1

def main(argv: Sequence[str] | None = None) -> int:
    parser = ArgumentParser()
    parser.add_argument("--input", type=str, default="./test.coverage", help="Coverage report file")
    parser.add_argument("--output", type=str, default="./htmlcov", help="Coverage html report path")
    args = parser.parse_args(argv)
    return make_html_report(
        db=args.input,
        report=args.output,
    )

if __name__ == "__main__":
    raise SystemExit(main())


import math
from geometry_msgs.msg import Point, Quaternion, Vector3
from scipy.interpolate import interp1d
import numpy as np
import tf.transformations

def distance(point1, point2):
    return math.sqrt( (point2.x-point1.x)**2 + (point2.y-point1.y)**2 + (point2.z-point1.z)**2 )

def vector_to_list(vec):
    return [vec.x, vec.y, vec.z]

def vector_from_to(p0, p1):
    v = Vector3()
    v.x = p1.x - p0.x
    v.y = p1.y - p0.y
    v.z = p1.z - p0.z
    return v

def unit_vector_from_to(point1, point2):
    return normalize(vector_from_to(point1, point2))

def magnitude_vector(vec):
    return math.sqrt(vec.x**2 + vec.y**2 + vec.z**2 )

def normalize(vec, magnitude=1.0):
    res = Vector3()
    m = magnitude_vector(vec)
    res.x = vec.x * magnitude / m
    res.y = vec.y * magnitude / m
    res.z = vec.z * magnitude / m
    return res

def dot(v1,v2):
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z

def scalar_multiply(a,v):
    res = Vector3()
    res.x = a * v.x
    res.y = a * v.y
    res.z = a * v.z
    return res

def point_plus_vector(point, vector):
    res = Vector3()
    res.x = point.x + vector.x
    res.y = point.y + vector.y
    res.z = point.z + vector.z
    return res

def point_to_vector(point):
    res = Vector3()
    res.x = point.x
    res.y = point.y
    res.z = point.z
    return res

# http://www.chrobotics.com/library/understanding-quaternions
# http://mathworld.wolfram.com/Quaternion.html
# http://kieranwynn.github.io/pyquaternion/
# http://docs.ros.org/lunar/api/geometry_msgs/html/msg/Quaternion.html
# http://wiki.ros.org/tf2/Tutorials/Quaternions
# http://www.chrobotics.com/library/understanding-euler-angles
# http://docs.ros.org/jade/api/tf/html/python/transformations.html

def rpy_to_vector(roll, pitch, yaw, magnitude=1.0):
    v = Point()
    v.y = math.sin(yaw)*math.cos(pitch)
    v.x = math.cos(yaw)*math.cos(pitch)
    v.z = - math.sin(pitch)
    return normalize(v, magnitude)

def quaternion_to_vector(quaternion, magnitude=1.0):
    tf_quat = [quaternion.x,quaternion.y,quaternion.z,quaternion.w]
    tf_euler = tf.transformations.euler_from_quaternion(tf_quat)
    return rpy_to_vector(tf_euler[0],tf_euler[1],tf_euler[2], magnitude)

def rotate_vector_wrt_quaternion(quaternion, vector):
    p = np.array([vector.x, vector.y, vector.z, 0])
    q = np.array([quaternion.x, quaternion.y, quaternion.z, quaternion.w])
    # p' = q * p * q'
    p_prime = tf.transformations.quaternion_multiply(
                tf.transformations.quaternion_multiply(q, p),
                tf.transformations.quaternion_inverse(q))
    return Vector3(*(p_prime[:3].tolist()))

#def rotate_vector_wrt_quaternion(q, v):
#    tf_quat = np.array([q.x, q.y, q.z, q.w])
#    tf_vec = np.array([v.x, v.y, v.z])
#    result = np.matmul(tf.transformations.quaternion_matrix(tf_quat)[:3, :3], tf_vec)
#    return Vector3(*(result.tolist()))

def rpy_to_quat(roll, pitch, yaw):
    quaternion_array = tf.transformations.quaternion_from_euler(roll, pitch, yaw, 'rxyz')
    result = Quaternion()
    result.x = quaternion_array[0]
    result.y = quaternion_array[1]
    result.z = quaternion_array[2]
    result.w = quaternion_array[3]
    return result

def vector_to_quat(vec):
    """To fully determine the orientation represented by the resulting quaternion, this method will assume the top of objects would always facing up
    """
    np_vec = np.array([vec.x, vec.y, vec.z])
    norm = np.linalg.norm(np_vec)
    if norm < 1e-5:
        return np.array([0.0, 0.0, 0.0, 1.0])
    obj_x = np.array([vec.x, vec.y, vec.z]) / norm
    obj_z_t = np.array([0.0, 0.0, 1.0])
    obj_y = np.cross(obj_z_t, obj_x)
    obj_y /= np.linalg.norm(obj_y)
    obj_z = np.cross(obj_x, obj_y)
    rot_mat = np.identity(4)
    rot_mat[:3,:3] = np.array([obj_x,
                               obj_y,
                               obj_z]).T
    q = tf.transformations.quaternion_from_matrix(rot_mat)
    return q / np.linalg.norm(q)

def points_to_spline(points):
    # returns "spline" data that can be used for mapping between path distance s and Point on the spline.
    # https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html
    distance_so_far = 0.0
    last_point = points[0]
    distances = []
    for point in points:
        distances.append(distance_so_far + distance(last_point, point))
        distance_so_far = distances[-1]
    return {'x': interp1d(distances, [p.x for p in points], kind='cubic', bounds_error=False, fill_value="extrapolate"),
            'y': interp1d(distances, [p.y for p in points], kind='cubic', bounds_error=False, fill_value="extrapolate"),
            'z': interp1d(distances, [p.z for p in points], kind='cubic', bounds_error=False, fill_value="extrapolate"),
            'max_distance': distances[-1]}

def spline_distance_to_point(spline, distance):
    res = Point()
    res.x = spline['x'](distance)
    res.y = spline['y'](distance)
    res.z = spline['z'](distance)
    return res

def spline_distance_to_tangent(spline,distance):
    return unit_vector_from_to(spline_distance_to_point(spline, distance - 0.1), spline_distance_to_point(spline, distance + 0.1))

def spline_distance_to_curvature(spline, distance):
    # Centripetal acceleration = curvature * speed^2 where both acceleration and curvature have type Vector3.
    # Use example speed of 1 m/s2 to calculate acceleration, then convert to curvature.
    # https://opentextbc.ca/physicstestbook2/chapter/centripetal-acceleration/
    # https://en.wikipedia.org/wiki/Differential_geometry_of_curves#Normal_or_curvature_vector
    velocity_before = spline_distance_to_tangent(spline, distance - 0.1)
    velocity_after = spline_distance_to_tangent(spline, distance - 0.1)
    acceleration = scalar_multiply(1/0.2, vector_from_to(velocity_before, velocity_after))
    curvature = acceleration # because acceleration calculated using speed of 1.0 and acceleration=curvature*speed^2
    return curvature


import os
import json

def get_prefills():
	res = dict()

	session_dirs = [d for d in os.listdir() if "Session " in d]

	for dn in session_dirs:
		path = os.path.join(dn, "Preparation")

		if not os.path.isdir(path):
			continue

		k = int(dn.split("Session ")[1])
		v = [f.split(".")[0] for f in os.listdir(path) if ".pdf" == f[-4:] and len(f.split(".")[0]) == 8]

		res[k] = v

	with open("prefills.json", "w") as f:
		json.dump(res, f, sort_keys=True, indent=4)

if __name__ == "__main__":
	get_prefills()