from src.process.ranking.ranker import Ranker
from typing import Dict, List
from tqdm import tqdm
from src.shared.logger_factory import LoggerFactory

log = LoggerFactory.logger(__name__)

class InfluenceTwoRanker(Ranker):
    def __init__(self, raw_tweet_getter, friends_getter, ranking_setter):
        self.raw_tweet_getter = raw_tweet_getter
        self.friends_getter = friends_getter
        self.ranking_setter = ranking_setter
        self.ranking_function_name = "influence two"

    def create_friends_dict(self, user_ids):
        friends = {}
        for user_id in user_ids:
            friends_of_user_id = self.friends_getter.get_user_friends_ids(user_id)
            if friends_of_user_id is None:
                friends[user_id] = []
            else:
                friends[user_id] = [str(id) for id in friends_of_user_id]
        return friends

    def score_users(self, user_ids: List[str], respection: List[str]):
        scores = {}

        for user_id in user_ids:
            scores[user_id] = self.score_user(user_id, respection)

        return scores

    def _group_by_retweet_id(self, tweets) -> Dict:
        # Puts all tweets with the same retweet_id in the same list
        # Returns: A dictionary where the key is the retweet_id and
        # the value is the list of tweets with that retweet_id
        dict = {}
        for tweet in tweets:
            key = str(tweet.retweet_id)
            if key in dict:
                dict[key].append(tweet)
            else:
                dict[key] = [tweet]

        return dict

    def _group_by_retweeter(self, tweets) -> Dict:
        # Puts all tweets with the same retweeter in the same list
        # Returns: A dictionary where the key is the user_id of the retweeter and
        # the value is the list of tweets retweeted by the retweeter
        dict = {}
        for tweet in tweets:
            if tweet.retweet_id is None: # tweet is not a retweet
                continue
            key = str(tweet.user_id)
            if key in dict:
                dict[key].append(tweet)
            else:
                dict[key] = [tweet]

        return dict

    def score_user(self, user_id, user_ids: List[str]):
        if user_id not in user_ids:
            user_ids = user_ids + [user_id]
            weight = 1
        else:
            weight = len(user_ids) / (len(user_ids) - 1)

        # Score users by summing up the percentage of tweets they make up in all followers' retweets
        score = 0

        tweets = self.raw_tweet_getter.get_tweets_by_user_ids(user_ids)
        # log.info("Get tweets from Database")
        valid_tweets = [tweet for tweet in tweets if tweet.retweet_user_id != tweet.user_id]

        # Define helper functions
        tweets_by_retweet_group = self._group_by_retweet_id(valid_tweets)
        def get_retweets_of_tweet_id(tweet_id):
            return tweets_by_retweet_group.get(str(tweet_id), [])
        def get_later_retweets_of_tweet_id(tweet_id, created_at):
            return [tweet for tweet in get_retweets_of_tweet_id(tweet_id) if tweet.created_at > created_at]

        retweets_by_retweeter = self._group_by_retweeter(valid_tweets)
        def get_num_retweets_by(id):
            return len(retweets_by_retweeter.get(id, []))

        friends = self.create_friends_dict(user_ids)
        def is_direct_follower(a, b): # 'b' is a follower of 'a'
            return a in friends.get(b, [])

        user_tweets = [tweet for tweet in valid_tweets if str(tweet.user_id) == user_id]
        user_original_tweets = [tweet for tweet in user_tweets if tweet.retweet_id is None]
        user_retweets = [tweet for tweet in user_tweets if tweet.retweet_id is not None]

        for follower_id in [other_id for other_id in user_ids if user_id != other_id and is_direct_follower(user_id, other_id)]:
            follower_score = 0
            # Score original tweets
            for original_tweet in user_original_tweets:
                retweets = get_retweets_of_tweet_id(original_tweet.id)
                follower_score += 1 if any(str(rtw.user_id) == follower_id for rtw in retweets) else 0
            # Score retweets
            for user_retweet in user_retweets:
                retweets = get_later_retweets_of_tweet_id(user_retweet.retweet_id, user_retweet.created_at)
                follower_score += 1 if any(str(rtw.user_id) == follower_id for rtw in retweets) else 0

            if get_num_retweets_by(follower_id) > 0:
                follower_score /= get_num_retweets_by(follower_id)
            score += follower_score

        # log.info("Finish scoring influence 2")

        return score


# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/

import random

def game():
    player=input("r for 'rock', s for 'scissor', p for 'paper' Whats your choice? ")
    computer = random.choice(['r', 'p', 's'])
    print("Computers choice - ",computer)

    if player == computer:
        print("Its a Tie!!")

    if winner(player,computer):
        print("You Won!!!")
    else:
        print("You Loose!!")

def winner(user,opponent):
    if(user == 'r' and opponent == 's') or (user == 'p' and opponent == 'r') or (user == 's' and opponent == 'p'):
        return True
game()


import llama_debug as ld

def breakpoint(bp):
    print("breakpoint", bp)

def exception(e):
    print("exception", e)

def process_create(name, base, size):
    print("process_create", name, hex(base), hex(size))

def process_exit(code):
    print("process_exit", hex(code))

def module_load(name, base, size):
    print("module_load", name, hex(base), hex(size))

def output(text):
    print("output", text, end="")

def __main__():
    debugger = ld.debugger()
    if (not debugger.open("cmd.exe")):
        print("Could not create debugger!");
    print("Opened process!")

    debugger.set_breakpoint_cb(breakpoint)
    debugger.set_exception_cb(exception)
    debugger.set_process_create_cb(process_create)
    debugger.set_process_exit_cb(process_exit)
    debugger.set_module_load_cb(module_load)
    debugger.set_output_cb(output)

    while True:
        status = debugger.wait()
        if status == ld.debug_status.ERROR or \
            status == ld.debug_status.DEAD:
            break
        if status == ld.debug_status.LOAD_MODULE:
            continue
        user_input = input("> ")

    debugger.close()

if __name__ == "__main__":
    __main__()


#!/usr/bin/env python
# coding: utf-8

# ![BTS](img/Logo-BTS.jpg)
#
# # Session 5: Text Mining (II)
#
# ### Juan Luis Cano Rodríguez <juan.cano@bts.tech> - Data Science Foundations (2018-10-19)
#
# Open this notebook in Google Colaboratory: [![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Juanlu001/bts-mbds-data-science-foundations/blob/master/sessions/05-Text-Mining-II.ipynb)

# In[1]:

# Source: http://billchambers.me/tutorials/2014/12/21/tf-idf-explained-in-python.html

t0 = "China has a strong economy that is growing at a rapid pace. However politically it differs greatly from the US Economy."
t1 = "At last, China seems serious about confronting an endemic problem: domestic violence and corruption."
t2 = "Japan's prime minister, Shinzo Abe, is working towards healing the economic turmoil in his own country for his view on the future of his people."
t3 = "Vladimir Putin is working hard to fix the economy in Russia as the Ruble has tumbled."
t4 = "What's the future of Abenomics? We asked Shinzo Abe for his views"
t5 = "Obama has eased sanctions on Cuba while accelerating those against the Russian Economy, even as the Ruble's value falls almost daily."
t6 = "Vladimir Putin was found to be riding a horse, again, without a shirt on while hunting deer. Vladimir Putin always seems so serious about things - even riding horses."

# ## Exercise 1: Jaccard similarity
#
# 1. Write a function `lemmatize` that receives a spaCy `Doc` and returns a list of lemmas as strings, removing stopwords, punctuation signs and whitespace
# 2. Write a function that receives two spaCy `Doc`s and returns a floating point number representing the Jaccard similarity (see formula below) (hint: use [`set`s](https://docs.python.org/3/library/stdtypes.html#set))
# 3. Compute the Jaccard similarity between `t0` and `t1`
# 4. Create a pandas `DataFrame` that holds the Jaccard similarity of all the text combinations from `t0` to `t6` (hint: use [`enumerate`](http://book.pythontips.com/en/latest/enumerate.html#enumerate))
#
# $$ J(A,B) = {{|A \cap B|}\over{|A \cup B|}} $$

# In[1]:

import spacy
from spacy.lang.en.stop_words import STOP_WORDS

# In[2]:

nlp = spacy.load("en_core_web_sm")

# In[4]:

def lemmatize(doc):
    return [token.lemma_ for token in doc if not
           (token.is_punct or token.is_space or token.lower_ in STOP_WORDS)]

# In[5]:

lemmatize(nlp(t0))

# In[6]:

def jaccard(doc1, doc2):
    s1 = set(lemmatize(doc1))
    s2 = set(lemmatize(doc2))
    return len(s1.intersection(s2)) / len(s1.union(s2))

# In[7]:

jaccard(nlp(t0), nlp(t1))

# In[8]:

import numpy as np
import pandas as pd

# In[9]:

data = np.zeros((7, 7))
docs = [nlp(text) for text in (t0, t1, t2, t3, t4, t5, t6)]
for ii, doc_a in enumerate(docs):
    for jj, doc_b in enumerate(docs):
        data[ii, jj] = jaccard(doc_a, doc_b)

pd.DataFrame(data)

# ## Exercise 2: TF-IDF
#
# 1. Write a function `tf` that receives a string and a spaCy `Doc` and returns the number of times the word appears in the `lemmatize`d `Doc`
# 2. Write a function `idf` that receives a string and a list of spaCy `Doc`s and returns the number of docs that contain the word
# 3. Write a function `tf_idf` that receives a string, a spaCy `Doc` and a list of spaCy `Doc`s and returns the product of `tf(t, d) · idf(t, D)`.
# 4. Write a function `all_lemmas` that receives a list of `Doc`s and returns a `set` of all available `lemma`s
# 5. Write a function `tf_idf_doc` that receives a `Doc` and a list of `Doc`s and returns a dictionary of `{lemma: TF-IDF value}`, corresponding to each the lemmas of all the available documents
# 6. Write a function `tf_idf_scores` that receives a list of `Doc`s and returns a `DataFrame` displaying the lemmas in the columns and the documents in the rows.
# 7. Visualize the TF-IDF, like this:
#
# ![TF-IDF](img/tf-idf.png)

# In[3]:

import spacy
from spacy.lang.en.stop_words import STOP_WORDS

nlp = spacy.load('en_core_web_sm')

# In[3]:

from collections import Counter

# In[89]:

def lemmatize(doc):
    return [
        token.lemma_
        for token in doc
        if not token.is_space and not token.is_punct and not token.lower_ in STOP_WORDS
        and not token.tag_ == "POS"
    ]

# In[20]:

def tf(word, doc):
    lemmas = lemmatize(doc)
    #return Counter(lemmas)[word]
    return lemmas.count(word)

# In[59]:

def tf(word, doc):
    lemmas = lemmatize(doc)
    #return Counter(lemmas)[word]
    print(lemmas.count(word))

# In[61]:

def tf(word, doc):
    lemmas = lemmatize(doc)
    return Counter(lemmas)[word]

# In[51]:

count = 2
if count:
    print(1 / count)
else:
    print(0)

# In[72]:

def foo(a):
    return a > 0

# In[73]:

foo(1)

# In[75]:

foo(-1)

# In[69]:

def foo(a):
    condition = a > 0
    if condition:
        return True
    else:
        return False

# In[70]:

foo(1)

# In[71]:

foo(-1)

# In[64]:

if "":
    print("Empty string is true")

# In[67]:

if [0]:
    print("Empty list is true")

# In[63]:

if 0:
    print("Zero is true")

# In[42]:

def idf(word, docs):
    count = 0
    for doc in docs:
        if word in lemmatize(doc):
            count += 1

    # We don't need to account for the 0 case since all the words will be in at least 1 document
    return 1 / count  # if count else 0

# In[40]:

docs = [nlp(text) for text in (t0, t1, t2, t3, t4, t5, t6)]

# In[41]:

idf("china", docs)

# In[43]:

def tf_idf(word, doc, docs):
    return tf(word, doc) * idf(word, docs)

# In[44]:

tf_idf("china", nlp(t1), docs)

# In[90]:

def all_lemmas(docs):
    lemmas = set()
    for doc in docs:
        #lemmas = lemmas.union(set(lemmatize(doc)))
        #lemmas = set(lemmatize(doc))
        lemmas.update(set(lemmatize(doc)))

    return lemmas

# In[91]:

print(all_lemmas(docs))

# In[98]:

def tf_idf_doc(doc, docs):
    lemmas = all_lemmas(docs)
    values = {}
#     for lemma in lemmas:
#         values[lemma] = tf_idf(lemma, doc, docs)

#     return values
    return {lemma: tf_idf(lemma, doc, docs) for lemma in lemmas}

# In[100]:

print(tf_idf_doc(nlp(t1), docs))

# In[102]:

import pandas as pd

# In[104]:

ll = ['a', 'b', 'c']
ll.append('d')
ll

# In[109]:

ll = ['a', 'b', 'c']
ll + ['d', 'e']

# In[106]:

ll = ['a', 'b', 'c']
ll.extend(['d', 'e'])
ll

# In[101]:

def tf_idf_scores(docs):
    rows = []
    for doc in docs:
        rows.append(tf_idf_doc(doc, docs))

    return pd.DataFrame(rows)

# In[110]:

res = tf_idf_scores(docs)
res

# In[112]:

get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt

# In[114]:

import seaborn as sns

# In[118]:

fig, ax = plt.subplots(figsize=(15, 3))
sns.heatmap(res, ax=ax)

# In[119]:

from sklearn.feature_extraction.text import TfidfVectorizer

# In[113]:

plt.pcolor(res)

# In[10]:

from collections import Counter

# In[11]:

def tf(word, doc):
    counts = Counter(lemmatize(doc))
    return counts[word]

# In[12]:

tf('economy', nlp(t0))

# In[13]:

def idf(word, docs):
    count = 0
    for doc in docs:
        if word in lemmatize(doc):
            count += 1
    return 1 / count

# In[14]:

idf('economy', docs)

# In[15]:

def tf_idf(word, doc, docs):
    assert doc in docs
    return tf(word, doc) * idf(word, docs)

# In[16]:

tf_idf('economy', docs[0], docs)

# In[17]:

def all_lemmas(docs):
    lemmas = set()
    for doc in docs:
        lemmas.update(lemmatize(doc))
    return lemmas

# In[18]:

print(all_lemmas(docs))

# In[19]:

def tf_idf_doc(doc, docs):
    lemmas = all_lemmas(docs)
    res = {}
    for lemma in lemmas:
        res[lemma] = tf_idf(lemma, doc, docs)
    return res

# In[20]:

print(tf_idf_doc(docs[0], docs))

# In[21]:

def tf_idf_scores(docs):
    lemmas = all_lemmas(docs)
    rows = []
    for doc in docs:
        rows.append(tf_idf_doc(doc, docs))

    return pd.DataFrame(rows)

# In[22]:

tb = tf_idf_scores(docs)
tb

# In[23]:

tb / tb.max().max()

# In[24]:

tb.columns

# In[25]:

tb

# In[32]:

import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')

plt.figure(figsize=(15, 3))
sns.heatmap(tb / tb.max().max(), cmap="RdYlGn_r", annot=False);


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 13:04:41 2020

@author: lea
"""
# Lea Wetzke
# lwetzke@uni-potsdam.de
# Universität Potsdam
# Bachelor Computerlinguistik

import csv
import logging
import os
from source.data_processing import ProcessData

logging.basicConfig(filename='errors.log', level=logging.DEBUG)

class FeatureAnalysis(ProcessData):
    """Class that uses the previously calculated models for both authors to
       classify the raw tweets in a csv by extracting the same linguistic
       features as the train set. By calculating the minimal distance
       between a tweet vector and both models, it can be decided which author
       is most likely.
    csv
    Args:
        train (str) : CSV file containing the train set
        is_test (bool) : boolean value whether or not the csv that is going
                         to be analyzed is either the test set (True) or the
                         train set (False)
        stats_csv (str) : CSV file containing the models for Hillary Clinton
                          and Donald Trump

    Returns:
        None

    """

    def __init__(self, stats_csv, train, is_test):
        super().__init__(train, is_test)
        self.stats_csv = stats_csv
        self.is_test = True
        # instances to be analyzed are part of the test set
        self.H_stats = []
        # mean statistics for the features of Hillary Clinton's tweets
        self.D_stats = []
        # mean statistics for the features of Donald Trump's tweets
        self.test_ling_inf = []
        # linguist information stored in three-valued tuples (text, tag, lemma)
        self.test_seg_tweets = []
        # segmented tweets of the test set
        self.test_tweet_stats = []
        # statistics for every tweet of the test set stored in tuples
        self.removed_links = False
        # Were dead tweets (aka links only containing a link) removed?
        self.classified_tweets = []
        # List containing lists with a raw tweet and the suspected author
        self.bad_indices = []
        # In rare cases, a tweet is only a link, which is removed by a regex,
        # leading to problems down the line. The indices of those "bad tweets"
        # is saved

    def classify_tweet(self, test_csv):
        """Method that classifies a test set of tweets by author, either
           Donald Trump or Hillary Clinton, depending on the minimum feature
           distance.
           Args:
               test_csv (str) : Name of a csv containing the test set

           Returns:
               None

        """
        self._read_data(test_csv)
        # read data from test_set.csv
        self._read_agg_stats_csv()
        # read models from stats.csv
        self._get_test_stats()
        # get all stats from the test set
        self.classified_tweets = self._calc_likely_author()
        # classify the tweets with the most likely author
        self._write_results_csv(self.classified_tweets,
                                os.path.join("csvs", "results.csv"))
        # write results to csv

    def _read_agg_stats_csv(self):
        """Method that extracts data from the stats CSV and saves the
           statistics in an attribute.
           Args:
               None

           Returns:
               None

        """

        if not os.path.isfile(self.stats_csv):
            raise FileNotFoundError
            logging.error("stats.csv not found.")
        with open(self.stats_csv, "r", encoding="utf-8") as stats_file:
            csv_reader = csv.reader(stats_file, delimiter=",")
            for line in csv_reader:
                if line:
                    if line[0] == "HillaryClinton":
                        self.H_stats = line
                    else:
                        self.D_stats = line

    def _get_test_stats(self):
        """Method that calculates the feature statistics for every tweet in
           the test set, saving said statistics in an attribute.

           Args:
               None

           Returns:
               None

        """
        try:
            test_segmented_unclean = self._segment_sentences(self.test_tweets)
            # make "unclean" segments containing empty tweet (previously link)
            self.bad_indices = [i for i, value in enumerate(
                                test_segmented_unclean) if value == ['']]
            # get indices of [''], aka prior link only tweet
            if self.removed_links == False:
                self._remove_links(self.test_tweets)
                self._remove_links(self.test_authors)
                # remove "bad" tweets (aka tweets that only contain link and
                # nothing else) to ensure that both self.test_tweets and the
                # punctuation and word feature indices match
            test_segmented = self._segment_sentences(self.test_tweets)
            test_ling_inf = self._extract_linguistic_inf(test_segmented)
            test_punct_1 = self._count_punctuation("!", test_segmented)
            test_punct_2 = self._count_punctuation(".", test_segmented)
            test_punct_3 = self._count_punctuation("?", test_segmented)
            test_punct_4 = self._count_punctuation(",", test_segmented)
            # get punctuation stats
            word_len = self._get_av_word_len(test_ling_inf)
            for i in range(len(test_segmented)):
                low_up_char = self._count_lower_upper_case(test_segmented[i])
                self.test_stats.append((self.test_tweets[i], low_up_char[2],
                                        low_up_char[0], low_up_char[1],
                                        len(test_segmented[i]
                                            ), test_punct_1[i],
                                        test_punct_2[i], test_punct_3[i],
                                        test_punct_4[i], word_len[i]))
                # save stats per tweet in a tuple
        except IndexError:
            raise IndexError
            logging.error("self.test_tweets might be empty. Is test_set.csv " +
                          "empty?")

    def _calc_likely_author(self):
        """Method that calculates the minimum distance between the features
           of all test tweets and one of the authors.

           Args:
               None

           Returns:
               classified_tweets (list) : List containing lists with a raw
                                          tweet and the suspected author

        """
        classified_tweets = []
        for stat_tuple in self.test_stats:
            distance_H = 0
            distance_D = 0
            for i in range(1, len(stat_tuple)):
                distance_H += abs(stat_tuple[i] - float(self.H_stats[i]))
                distance_D += abs(stat_tuple[i] - float(self.D_stats[i]))
            if distance_H > distance_D:
                classified_tweets.append([stat_tuple[0], "realDonaldTrump"])
            elif distance_D > distance_H:
                classified_tweets.append([stat_tuple[0], "HillaryClinton"])
            elif distance_D == distance_H:
                classified_tweets.append([stat_tuple[0], "unclear"])
                # very unlikely case but still good to have
        return classified_tweets

    def _write_results_csv(self, classified_tweets, filename):
        with open(filename, mode="w", encoding="utf-8") as stat_file:
            result_writer = csv.writer(stat_file, delimiter=",",
                                       quotechar='"',
                                       quoting=csv.QUOTE_MINIMAL)
            for i in range(len(classified_tweets)):
                # First row: tweet, second row: suspected author, third row:
                # actual author
                result_writer.writerow([classified_tweets[i][0],
                                        classified_tweets[i][1],
                                        self.test_authors[i]])

    def _remove_links(self, data_list):
        """Method that removes 'dead' indices correlating to a tweet that
           only consists of a single tweet (which is removed by a regex
           earlier, making the tweet or author entry obsolete).

           Args:
               data_list (list) : a list containing data correlating to tweets
                                  (either the raw tweet or the author)

           Returns:
               None

        """
        if len(self.bad_indices) == 1:
            del data_list[self.bad_indices[0]]
            # If only one bad index: simply delete it (no consequences)
        if len(self.bad_indices) > 1:
            index_c = 0
            # Counter for how many elements have been removed: with every
            # element removed, the placement of other bad indices later on
            # shifts by -c
            # Else: non-link tweets removed
            for i in self.bad_indices:
                del data_list[i-index_c]
                index_c += 1
        self.removed_links = True

    def _get_accuracy(self, class_tweet_list):
        """Method that calculates the accuracy of the classifier.

           Args:
               class_tweet_list (list) : a list containing lists with a raw
                                         tweet and the suspected author

           Returns:
               counter/len(class_tweet_list) (float) : a float describing
                                                       the accuracy of the
                                                       classifier

        """
        counter = 0
        for i in range(len(class_tweet_list)):
            if class_tweet_list[i][1] == self.test_authors[i]:
                counter += 1
        return counter/len(class_tweet_list)


n = int(input())
s = set(map(int, input().split()))

commands = int(input())

while commands:
    inp = input().split()

    if inp[0] == "pop":
        s.pop()

    if inp[0] == "remove":
        s.remove(int(inp[1]))

    if inp[0] == "discard":
        s.discard(int(inp[1]))

    commands-=1

print(sum(s))


PATHTOFILES = './setting_files/files_to_run/'
PATHTODBSETTINGS = './setting_files/db_settings.txt'

FILEFOLDER = 'csv_files'

# Implementation settings
FILES_SETTING = '###Files'
FILE_SETTING = '###File'
PATH_SETTING = '###Path'
DELIMETER_SETTING = '###Delimeter'
CHOOSE_COLUMNS_SETTING = '###ChooseColumns'
COLUMN_SETTING = '###Column'
NAME_SETTING = '###Name'
NEWNAME_SETTING = '###NewName'
WHERECLAUSE_SETTING = '###WhereClause'
CLAUSE_SETTING = '###Clause'
EQUAL_SETTING = '###Equal'

# Database settings
TABLENAME_SETTING = '###TableName'
COLUMN_TYPES_SETTING = '###ColumnTypes'
TYPE_SETTING = '###Type'


n=int(input())

for i in range(0,n):
    list1=input().split()
    list2=input().split()
    list3=list2.copy()
    list4=[]
    flag=0
    for j in list2:
        list3.remove(j)
        if not(j in list3)and list3!=[]:
            flag=1
            list4.append(j)
        list3.append(j)

    try:
        print(list4[int(list1[1])-1])
    except:
        print(-1)


from django.conf import settings

default_app_config = "layers.apps.LayersConfig"
LAYER_STACKS = {}

def _build_layer_stacks(node, di, parent=None, depth=0):
    """Recursive helper to map each tree node to its parent."""

    if isinstance(node, list):
        for child in node:
            if isinstance(child, list):
                _build_layer_stacks(child, di, node[0], depth+1)
            else:
                _build_layer_stacks(child, di, parent, depth+1)
    else:
        if node in di:
            raise RuntimeError("Node %s is already in the tree" % node)
        di[node] = parent

def build_layer_stacks():
    """Support both the legacy "layers" format and the newer "tree" format.
    Tree uses a list of lists format, eg.
    single inheritance line basic-smart-web
       ['basic',
           ['smart',
               ['web']
           ]
       ]
    or two inheritance lines basic-smart, basic-web
       ['basic',
         ['web'],
         ['smart']
       ]
    """

    global LAYER_STACKS
    setting = getattr(settings, "LAYERS", {})
    tree = setting.get("tree", [])
    layers = setting.get("layers", [])
    if tree:
        di = {}
        _build_layer_stacks(tree, di)

        # Build a dictionary of layer -> parent layers
        for layer in di.keys():
            LAYER_STACKS[layer] = [layer]
            parent = di[layer]
            while parent is not None:
                LAYER_STACKS[layer].insert(0, parent)
                parent = di.get(parent, None)

    elif layers:
        LAYER_STACKS[layers[-1]] = layers

def get_layer_stacks():
    global LAYER_STACKS
    return LAYER_STACKS

def get_current_layer(request=None):
    """Return the current layer. The setting, if set, trumps the request."""

    current = None
    setting = getattr(settings, "LAYERS", {})
    if "current" in setting:
        current = setting["current"]
    elif "layers" in setting:
        current = setting["layers"][-1]
    elif request is not None:
        current = request.META.get("X-Django-Layer", None)
    return current

def get_current_layer_stack(request=None):
    global LAYER_STACKS
    if not LAYER_STACKS:
        build_layer_stacks()
    current = get_current_layer(request)
    return LAYER_STACKS.get(current, [])

def reset_layer_stacks():
    global LAYER_STACKS
    LAYER_STACKS = {}

build_layer_stacks()


import turtle
import math

wn = turtle.Screen()
wn.bgcolor('lightgray')
toba = turtle.Turtle()
toba.shape('turtle')
toba.penup()
toba.backward(180)
toba.pendown()
for x in range(360):
	y = math.sin(math.radians(90))
	toba.left(y)
	toba.forward(x)


class Queue():
    def __init__(self, max_queue_size=False) -> None:
        self.queue = []
        self.start = 0
        self.end = 0
        if (max_queue_size):
            self.max_queue_size = max_queue_size

    def get_size(self):
        return len(self.queue)

    def insert(self, element):
        if (self.get_size() + 1 > self.max_queue_size):
            return False
        self.queue.append(element)
        return True

    def delete(self):
        try:
            return self.queue.pop(0)
        except IndexError:
            return False

    def clear(self):
        if self.get_size() == 0:
            return False
        while self.get_size() > 0:
            self.delete()
        return True

    def print_queue(self):
        print(self.queue)

# try:
#     MAX_STACK_SIZE = int(input("Enter maximum stack size [default 5]: "))
# except ValueError:
#     MAX_STACK_SIZE = 5
MAX_STACK_SIZE = 5

queue = Queue(MAX_STACK_SIZE)

while (True):
    queue.print_queue()  # for easy debugging

    print("\nAvailable queue operations: \n\
        1 Insert \n\
        2 Delete \n\
        3 Clear \n\
        4 Get Size \n\
        5 Exit \n\
        ")
    try:
        op = int(input("# Enter option: "))
    except ValueError:
        print("Invalid option")
        continue

    if (op == 1):
        temp = input("# Enter element to insert: ")
        if len(temp) == 0:
            print("# input can't be empty")
            continue
        output = queue.insert(temp)
        if (output):
            print("# {} inserted successfully".format(output))
        else:
            print("# QUEUE OVERFLOW !!!")

    elif (op == 2):
        temp = queue.delete()
        if (temp):
            print("# {} was deleted".format(temp))
        else:
            print("# ERROR: queue IS EMPTY")

    elif (op == 3):
        output = queue.clear()
        if (output):
            print("# queue has been cleared")
        else:
            print("# ERROR: queue is already empty")

    elif (op == 4):
        print("# queue size: {}".format(queue.get_size()))

    elif (op == 5):
        queue.clear()
        print("# queue has been cleared")
        print("# Exiting")
        break


from collections import defaultdict

def solution(clothes):
    dict_ = defaultdict(int)
    for i, x in clothes:
        dict_[x] += 1

    vals = list(dict_.values())
    count = 1
    for i in vals:
        count *= i + 1

    return count - 1


import re

from tkinter import *
from tkinter import messagebox as mb
from config.config import reg_rus, reg_eng
from tools.tool import get_gamma

from tools.cipher import Gamma

class MainForm(Frame):
    # Main form init
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.resizable(width=False, height=False)
        self.canvas = Canvas(self.parent)

        self.frame = Frame(self.parent, bg='#fafafa')

        self.form_w = 500
        self.form_h = 400
        self.isRus = True

        self.centerWindow()
        self.initUI()
        self.showUI()

    # Init Widgets
    def initUI(self):
        # Key frame
        self.key_frame = Frame(self.parent, bg='#fafafa')
        self.key_label = Label(self.frame, text='Ввод ключа:', bg='#fafafa', font=20)
        self.scroll_key = Scrollbar(self.key_frame, orient='horizontal')

        # Only upper for Entry
        def to_uppercase_key(*args):
            varKey.set(varKey.get().upper())

        varKey = StringVar(self.parent)
        try:
            varKey.trace_add('write', to_uppercase_key)
        except AttributeError:
            varKey.trace('w', to_uppercase_key)
        self.key_input = Entry(self.key_frame, justify='center', textvariable=varKey,
                               xscrollcommand=self.scroll_key.set)

        # Entering text frame
        self.text_frame = Frame(self.parent, bg='#fafafa')
        self.text_label = Label(self.frame, text='Ввод текста:', bg='#fafafa', font=20)
        self.scroll_txt = Scrollbar(self.text_frame)
        self.text_input = Text(self.text_frame, name="txt_tag", yscrollcommand=self.scroll_txt.set)

        # Output text frame
        self.out_frame = Frame(self.parent, bg='#fafafa')
        self.out_label = Label(self.frame, text='Результат:', bg='#fafafa', font=20)
        self.scroll_out = Scrollbar(self.out_frame)
        self.out_input = Text(self.out_frame, yscrollcommand=self.scroll_out.set)

        # Button call the cipher
        self.btn_enc = Button(self.frame, width=14, text='За/Расшифровать', bg='gray', command=self.btn_encode)
        # Button call the change language
        self.btn_key = Button(self.frame, width=14, text='Случ. ключ', bg='gray', command=self.btn_randkey)
        # Button call the change language
        self.btn_cl = Button(self.frame, width=14, text='Сменить язык', bg='gray', command=self.btn_changlang)
        # Button call the convert chars code to bin
        self.btn_bc = Button(self.frame, width=14, text='Двоичный ключ', bg='gray', command=self.btn_symcode)
        # Button call the convert bin code to chars
        self.btn_sc = Button(self.frame, width=14, text='Символьный ключ', bg='gray', command=self.btn_bincode)
        # Button clear
        self.btn_c = Button(self.frame, width=14, text='Очистка', bg='gray', command=self.btn_clear)

    # Show Widgets
    def showUI(self):
        self.canvas.pack()
        self.parent.title('Шифр Гаммирование')
        self.frame.place(relx=0, rely=0, relwidth=1, relheight=1)

        # Init key block frame
        self.key_frame.place(relx=0.25, rely=0.04, relwidth=0.48, relheight=0.09)
        self.key_label.place(x=20, y=12)
        self.scroll_key.pack(side=BOTTOM, fill=X)
        self.key_input.place(x=0, y=0, width=250)

        # Init Entries block frame
        self.text_frame.place(relx=0.05, rely=0.33, relwidth=0.9, relheight=0.25)
        self.text_label.place(x=20, y=105)
        self.scroll_txt.pack(side=RIGHT, fill=Y)
        self.text_input.place(x=0, y=0, height=100, width=435)

        # Init output frame
        self.out_frame.place(relx=0.05, rely=0.70, relwidth=0.9, relheight=0.25)
        self.out_label.place(x=20, y=250)
        self.scroll_out.pack(side=RIGHT, fill=Y)
        self.out_input.place(x=0, y=0, height=100, width=435)

        # Init buttons
        self.btn_enc.place(x=380, y=20)
        self.btn_key.place(x=380, y=55)
        self.btn_cl.place(x=380, y=90)
        self.btn_bc.place(x=260, y=55)
        self.btn_sc.place(x=260, y=90)
        self.btn_c.place(x=140, y=90)

    # Centring Form window
    def centerWindow(self):
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw - self.form_w) / 2
        y = (sh - self.form_h) / 2
        self.parent.geometry('%dx%d+%d+%d' % (self.form_w, self.form_h, x, y))

    # Click encode/decode
    def btn_encode(self):
        key = self.key_input.get()
        txt = self.text_input.get("1.0", "end-1c").upper()
        self.text_input.delete(1.0, END)
        self.text_input.insert(1.0, txt)

        # Check empty widgets
        if key == '' or txt == '':
            if self.isRus:
                mb.showerror("Ошибка", "Пустая строка!")
            else:
                mb.showerror("Error", "Empty string!")
            return

        # Check outside the alphabet
        if self.isRus:
            reg_val_key = re.sub(reg_rus, '', key)
            reg_val_txt = re.sub(reg_rus, '', txt)
        else:
            reg_val_key = re.sub(reg_eng, '', key)
            reg_val_txt = re.sub(reg_eng, '', txt)

        # There are extra characters
        if len(reg_val_key) > 0 or len(reg_val_txt) > 0:
            if self.isRus:
                mb.showerror("Ошибка",
                             repr(f"Используются посторонние символы: {''.join(set(reg_val_key + reg_val_txt))}"))
            else:
                mb.showerror("Error", repr(f"Foreign characters are used: {''.join(set(reg_val_key + reg_val_txt))}"))
            return

        # Check end line
        txt = txt.replace("\n", "")
        cipher = Gamma(key=key, isRus=self.isRus)

        self.out_input.delete(1.0, END)
        self.out_input.insert(1.0, cipher.encode(txt))

    # Click for random gamma
    def btn_randkey(self):
        txt_lenght = len(self.text_input.get("1.0", "end-1c"))
        if txt_lenght != 0:
            cipher = Gamma(isRus=self.isRus)
            self.key_input.delete(0, END)
            self.key_input.insert(0, cipher.bin2char(get_gamma(txt_lenght * 6)))
        else:
            if self.isRus:
                mb.showerror("Ошибка", "Введите текст!")
            else:
                mb.showerror("Error", "Entry text!")

    # Click for change language
    def btn_changlang(self):
        self.isRus = not self.isRus
        if self.isRus:
            self.parent.title('Шифр Гаммирования')
            self.key_label.config(text='Ввод ключа:')
            self.text_label.config(text='Ввод текста:')
            self.out_label.config(text='Результат:')
            self.btn_enc.config(text='За/Расшифровать')
            self.btn_key.config(text='Случ. ключ')
            self.btn_cl.config(text='Сменить язык')
            self.btn_bc.config(text='Двоичный ключ')
            self.btn_sc.config(text='Символьный ключ')
            self.btn_c.config(text='Очистка')
        else:
            self.parent.title('Cipher Gamming')
            self.key_label.config(text='Entry Key:')
            self.text_label.config(text='Entry Text:')
            self.out_label.config(text='Result:')
            self.btn_enc.config(text='Encode/Decode')
            self.btn_key.config(text='Random Key')
            self.btn_cl.config(text='Change Language')
            self.btn_bc.config(text='Binary key')
            self.btn_sc.config(text='Symbol key')
            self.btn_c.config(text='Clear')

    # Clear Text Widgets
    def btn_clear(self):
        self.key_input.delete(0, END)
        self.text_input.delete("1.0", END)
        self.out_input.delete("1.0", END)

    # Convert binary code to symbols
    def btn_bincode(self):
        key = self.key_input.get()
        txt = self.text_input.get("1.0", "end-1c")
        out = self.out_input.get("1.0", "end-1c")
        if key == '' or txt == '' or out == '':
            if self.isRus:
                mb.showerror("Ошибка", "Пустая строка!")
            else:
                mb.showerror("Error", "Empty string!")
            return

        if len(key) % 6 != 0:
            if self.isRus:
                mb.showerror("Ошибка", "Не правильная длина кода!")
            else:
                mb.showerror("Error", "Incorrect length code!")
            return
        unq_sym = ''.join(set(key))
        if unq_sym != '01' and unq_sym != '10':
            if self.isRus:
                mb.showerror("Ошибка", "Некорректный код!")
            else:
                mb.showerror("Error", "Incorrect code!")
            return

        cipher = Gamma(isRus=self.isRus)
        self.key_input.delete(0, END)
        self.key_input.insert(0, cipher.bin2char(key))

        self.text_input.delete("1.0", END)
        self.text_input.insert("1.0", cipher.bin2char(txt))

        self.out_input.delete("1.0", END)
        self.out_input.insert("1.0", cipher.bin2char(out))

    # Convert symbols code to binary
    def btn_symcode(self):
        key = self.key_input.get()
        txt = self.text_input.get("1.0", "end-1c")
        out = self.out_input.get("1.0", "end-1c")
        if key == '' or txt == '' or out == '':
            if self.isRus:
                mb.showerror("Ошибка", "Пустая строка!")
            else:
                mb.showerror("Error", "Empty string!")
            return

        cipher = Gamma(isRus=self.isRus)
        self.key_input.delete(0, END)
        self.key_input.insert(0, cipher.char2bin(key))

        self.text_input.delete("1.0", END)
        self.text_input.insert("1.0", cipher.char2bin(txt))

        self.out_input.delete("1.0", END)
        self.out_input.insert("1.0", cipher.char2bin(out))


a,b,c = map(int, input().split())
total = 0
if a==b==c:
    total=10000+(a*1000)
elif a==b or a==c:
    total=1000+(a*100)
elif b==c:
    total=1000+(b*100)
else:
    if a>b and a>c:
        total=a*100
    elif b>a and b>c:
        total=b*100
    else:
        total=c*100
print(total)


import pandas as pd
from urllib.request import urlopen
import json

def get_county_geojson():
    # returns a dictionary with geojson data
    with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
        counties = json.load(response)
    return counties

def get_county_fips():
    # returns a dataframe with US counties and its fips
    df_fips = pd.read_csv("./DataVisualization/data/state_and_county_fips_master.csv")
    df_fips["fips"] = df_fips["fips"].astype("str")
    df_fips['fips'] = df_fips['fips'].apply(lambda x: x.zfill(5))
    df_fips = df_fips.dropna()
    df_fips = df_fips.reset_index(drop=True)
    df_fips = df_fips.rename(columns={"name": "county"})
    return df_fips


import os
import re
import shutil
import time

import cpmpy
from termcolor import colored
from storm.parameters import get_supported_theories
from storm.parameters import get_parameters_dict

def get_all_smt_files_recursively(path_to_directory):
    file_paths = list()
    for r, d, f in os.walk(path_to_directory):
        for file in f:
            if ".smt20" in file:
                continue
            if ".smt2" in file:
                file_paths.append(os.path.join(r,file))

    return file_paths

def get_all_seed_files_recursively(path_to_directory):
    file_paths = list()
    for r, d, f in os.walk(path_to_directory):
        for file in f:
            if file.__contains__("."):
                continue
            file_paths.append(os.path.join(r,file))

    return file_paths

def create_smt2_file(path, string):
    file = open(path, "w")
    file.write(string)
    file.close()

def create_file(data, path):
    file = open(path, "w")
    file.write(data)
    file.close()

def append_row(data, path):
    file = open(path, "a")
    file.write(data + "\n")
    file.close()

def create_server_core_directory(temp_dir, server, core):
    if not os.path.exists(temp_dir):
        try:
            os.mkdir(temp_dir)
        except:
            pass
    server_dir = os.path.join(temp_dir, server)
    core_dir = os.path.join(server_dir, "core_" + str(core))
    if not os.path.exists(server_dir):
        os.mkdir(server_dir)

    if os.path.exists(core_dir):
        shutil.rmtree(core_dir)
        os.mkdir(core_dir)
    else:
        os.mkdir(core_dir)
    print("####### [Created core dir] - " + core_dir )
    return core_dir

def get_mutant_paths(temp_dir):
    mutant_paths = list()
    for r, d, f in os.walk(temp_dir):
        mutant_paths = [os.path.join(temp_dir, i) for i in f]
        break
    return mutant_paths

def refresh_directory(dir_path):
    if os.path.exists(dir_path):
        shutil.rmtree(dir_path)
        os.mkdir(dir_path)

def pick_a_supported_theory(path_to_benchmark, solver, seed):
    import random
    random.seed(seed)
    all_theories_in_benchamark_dir = os.listdir(path_to_benchmark)
    while True:
        theory = random.choice(all_theories_in_benchamark_dir)
        if theory in get_supported_theories(solver):
            return theory

def record_soundness(home_directory, seed_file_path, buggy_mutant_path, seed, mutant_number, fuzzing_parameters, parsedArguments):
    temp_dir = os.path.join(home_directory, "temp")
    # check if the soundness folder exists
    path_to_soundness_folder = os.path.join(temp_dir, "soundness")
    number_of_directories = 0
    for r, d, f in os.walk(path_to_soundness_folder):
        number_of_directories = len(d)
        break

    if not os.path.exists(path_to_soundness_folder):
        os.mkdir(path_to_soundness_folder)

    # Create a directory for the bug
    path_to_bug_dir = os.path.join(path_to_soundness_folder, str(number_of_directories))
    os.mkdir(path_to_bug_dir)
    print(colored("Creating a soundness folder at: ", "magenta", attrs=["bold"]) + temp_dir + "/" + path_to_bug_dir)
    print(colored("seed file path: ", "magenta", attrs=["bold"]) + seed_file_path)
    print(colored("buggy mutant file path: ", "magenta", attrs=["bold"]) + buggy_mutant_path)

    # copy the orig file and the mutant to the directory for the bug
    shutil.copy2(seed_file_path, path_to_bug_dir)
    shutil.copy2(buggy_mutant_path, path_to_bug_dir)

    error_logs = "Some info on this bug:\n"
    error_logs += "seed to run_storm() function: " + str(seed) + "\n"
    error_logs += "Path to original file: " + seed_file_path + "\n"
    error_logs += "This was the [" + str(mutant_number) + "]th mutant\n"
    #error_logs += "Seed theory: " + seed_theory + "\n"
    error_logs += "\nConfiguration: " + "\n"
    error_logs += str(fuzzing_parameters)
    error_logs += "\n"
    error_logs += str(parsedArguments)
    error_logs += "\n"
    error_logs += "solver: " + str(parsedArguments["solver"])

    create_file(error_logs, os.path.join(path_to_bug_dir, "error_logs.txt"))

    create_file("epoch time", os.path.join(path_to_bug_dir, str(time.time())+".txt"))

def record_error(home_directory, seed_file_path, buggy_mutant_path, seed, mutant_number, fuzzing_parameters, parsedArguments, errorType):
    temp_dir = os.path.join(home_directory, "temp")

    # check if the error folder exists
    path_to_error_folder = os.path.join(temp_dir, "error")
    number_of_directories = 0
    for r, d, f in os.walk(path_to_error_folder):
        number_of_directories = len(d)
        break

    if not os.path.exists(path_to_error_folder):
        os.mkdir(path_to_error_folder)

    # Create a directory for the bug
    path_to_bug_dir = os.path.join(path_to_error_folder, str(number_of_directories))
    os.mkdir(path_to_bug_dir)
    print(colored("Creating a error folder at: ", "magenta", attrs=["bold"]) + temp_dir + "/" + path_to_bug_dir)
    print(colored("seed file path: ", "magenta", attrs=["bold"]) + seed_file_path)
    print(colored("buggy mutant file path: ", "magenta", attrs=["bold"]) + buggy_mutant_path)

    # copy the orig file and the mutant to the directory for the bug
    shutil.copy2(seed_file_path, path_to_bug_dir)
    shutil.copy2(buggy_mutant_path, path_to_bug_dir)

    error_logs = "Some info on this bug:\n"
    error_logs += "seed to run_storm() function: " + str(seed) + "\n"
    error_logs += "Path to original file: " + seed_file_path + "\n"
    error_logs += "This was the [" + str(mutant_number) + "]th mutant\n"
    #error_logs += "Seed theory: " + seed_theory + "\n"
    error_logs += "\nConfiguration: " + "\n"
    error_logs += str(fuzzing_parameters)
    error_logs += "\n"
    error_logs += str(parsedArguments)
    error_logs += "\n"
    error_logs += "error Type: " + str(errorType)
    error_logs += "\n"
    error_logs += "solver: " + str(parsedArguments["solver"])

    create_file(error_logs, os.path.join(path_to_bug_dir, "error_logs.txt"))

def record_crash(home_directory, cpmpy_Object, seed_file_path, seed, mutant_number, fuzzing_parameters, parsedArguments, crashTrace, errorType):
    temp_dir = os.path.join(home_directory, "temp")

    # check if the crash folder exists
    path_to_crash_folder = os.path.join(temp_dir, "crash")
    number_of_directories = 0
    for r, d, f in os.walk(path_to_crash_folder):
        number_of_directories = len(d)
        break

    if not os.path.exists(path_to_crash_folder):
        os.mkdir(path_to_crash_folder)

    # Create a directory for the crash
    safeErrorType = re.sub('[^a-zA-Z0-9 ]', '', errorType) # remove all non (a-z A-Z 0-9 and " ") characters
    path_to_bug_dir = os.path.join(path_to_crash_folder, safeErrorType + str(number_of_directories))
    os.mkdir(path_to_bug_dir)
    #print(colored("Creating a error folder at: ", "magenta", attrs=["bold"]) + temp_dir + "/" + str(number_of_directories))
    #print(colored("seed file path: ", "magenta", attrs=["bold"]) + seed_file_path)

    # copy the orig file and the mutant to the directory for the bug
    shutil.copy2(seed_file_path, path_to_bug_dir)

    error_logs = "Some info on this crash:\n"
    error_logs += "seed to run_storm() function: " + str(seed) + "\n"
    error_logs += "Path to original file: " + seed_file_path + "\n"
    error_logs += "This was the [" + str(mutant_number) + "]th mutant\n"
    #error_logs += "Seed theory: " + seed_theory + "\n"
    error_logs += "\nConfiguration: " + "\n"
    error_logs += str(fuzzing_parameters)
    error_logs += "\n"
    error_logs += str(parsedArguments)
    error_logs += "\n"
    error_logs += "crash trace: " + "\n" + str(crashTrace)

    create_file(error_logs, os.path.join(path_to_bug_dir, "crash_logs.txt"))
    #cpmpy.Model(cpmpy_Object.get_all_nodes()).to_file(path_to_bug_dir + "allNodes")
    lst = []
    lst.append(cpmpy_Object.get_true_constructed_nodes())
    lst.append(cpmpy_Object.get_false_constructed_nodes())
    #cpmpy.Model(lst).to_file(path_to_bug_dir + "constructed_nodes")


from abc import ABCMeta

from csrank.constants import OBJECT_RANKING
from csrank.numpy_util import scores_to_rankings

__all__ = ["ObjectRanker"]

class ObjectRanker(metaclass=ABCMeta):
    @property
    def learning_problem(self):
        return OBJECT_RANKING

    def predict_for_scores(self, scores, **kwargs):
        """
            The permutation vector :math:`\\pi` represents the ranking amongst the objects in :math:`Q`, such that
            :math:`\\pi(k)` is the position of the :math:`k`-th object :math:`x_k`, and :math:`\\pi^{-1}(k)` is the index
            of the object on position :math:`k`. Predict rankings for the scores for a given collection of sets of
            objects (query sets).

            Parameters
            ----------
            scores : dict or numpy array
                Dictionary with a mapping from query set size to numpy arrays or a single numpy array of size containing
                scores of each object of size: (n_instances, n_objects)

            Returns
            -------
            Y : dict or numpy array
                Dictionary with a mapping from objects size to numpy arrays or a single numpy array containing
                predicted rankings of size: (n_samples, n_objects)
        """

        if isinstance(scores, dict):
            result = dict()
            for n, score in scores.items():
                rankings = scores_to_rankings(score)
                result[n] = rankings
        else:
            result = scores_to_rankings(scores)
        return result


from mindspore.nn import Cell
from mindspore import ops, nn,Parameter,Tensor
import mindspore as ms
import step_lr
from models import model_factory
import sys

class SAM(nn.Optimizer):
    """定义优化器"""
    def __init__(self, params, learning_rate,base_optimizer, rho=0.05,adaptive=False,**kwargs):
        assert rho >= 0.0, f"Invalid rho, should be non-negative: {rho}"

        super(SAM, self).__init__(learning_rate, params)
        self.state = dict()
        self.adaptive = adaptive
        self.rho = Parameter(Tensor(rho, ms.float32), name="rho")
        self.base_optimizer = base_optimizer(params,learning_rate,**kwargs)

        self.parameters = self.base_optimizer.parameters

    def first_step(self,gradients):
        params = self.parameters
        grad_norm = self._grad_norm(gradients)
        scale = self.rho / (grad_norm + 1e-12)
        pow = ops.Pow()
        for i in range(len(params)):
            if gradients[i] is None:continue
            if params[i].name in self.state:
                self.state[params[i].name].update({"old_p": params[i].value().copy()})
            else:
                self.state.update({params[i].name: {"old_p": params[i].value().copy()}})
            self.state[params[i].name].update({"old_g": gradients[i].copy()})
            e_w = (pow(params[i], 2) if self.adaptive else 1.0)
            e_w = e_w * gradients[i]
            e_w = e_w * scale
            update = params[i]+e_w
            ops.assign(params[i], update)

    def construct(self, gradients):
        params = self.parameters
        gradients = list(gradients)
        for i in range(len(params)):
            if gradients[i] is None:continue
            gradients[i] = self.state[str(params[i].name)]["old_g"]+ gradients[i]
            params[i].set_data(self.state[str(params[i].name)]["old_p"])
            ##value = self.state[str(params[i].name)]["old_p"]
            #ops.assign(gradients[i],self.state[str(params[i].name)]["old_g"]+ gradients[i])
            #ops.assign(params[i],self.state[str(params[i].name)]["old_p"])
        gradients = tuple(gradients)
        success = self.base_optimizer(gradients)
        return success

    def _grad_norm(self, gradients):
        params = self.parameters
        stack = ops.Stack()
        test = []
        for i in range(len(params)):
            if gradients[i] is None: continue
            if self.adaptive:
                value = ops.abs(params[i])
            else:
                value = 1.0
            value = value * gradients[i]
            dims = [i for i in range(len(value.shape))]
            dims = tuple(dims)
            value = ops.norm(value)
            test.append(value)
        test = stack(test)
        test = ops.norm(test)
        return test

# net = model_factory.get_network("resnet18")(num_classes=10)
# # 设置优化器待优化的参数和学习率为0.01
# lr = step_lr.stepLR(learning_rate=0.003,steps_per_epoch=100,total_epochs=100)
# opt = SAM(net.trainable_params(), 0.01,base_optimizer=nn.SGD,momentum=0.9,weight_decay=5e-4)
# test =  opt.parameters
# print(0)


import current_detector as cd
import threading
import time
import re
import urllib2
import json

def upload_sensor_data():
    detection_lavel=cd.get_lavel()
    data = {'data': {'push':{
			imageUrl: '/assets/img/fridge/beer.png',
			clickUrl: '/fridge-beer'
		}},
            'eventName': 'user99999/panel'}
    if(detection_lavel == 'none'):
        return
    url = 'https://fy33dypvtg.execute-api.us-west-1.amazonaws.com/prod/v0/panel'
    req = urllib2.Request(url)
    req.add_header('Content-Type', 'application/json')

    response = urllib2.urlopen(req, json.dumps(data))
    t = threading.Timer(0, upload_sensor_data)
    t.start()

def main():
    cd.initialize()
    t = threading.Thread(target=upload_sensor_data)
    t.start()

if __name__ == '__main__':
    main()


#Escribir una función que reciba un texto y para cada caracter presente en el texto
#devuelva la cadena más larga en la que se encuentra ese caracter.

def obtener_cadenas_largas_por_caracter(texto):
    """
    Obtiene una cadena y le asigna a cada caracter la palabra mas larga
    en la cual se encuentran
    """
    diccionario = {}
    lista_aux = texto.lower().split()
    for i in range(len(lista_aux)):
        for j in range(len(lista_aux[i])):
            if lista_aux[i][j] not in diccionario:
                diccionario[lista_aux[i][j]] = lista_aux[i]
            elif len(diccionario[lista_aux[i][j]]) < len(lista_aux[i]):
                diccionario[lista_aux[i][j]] = lista_aux[i]
    return diccionario

print(obtener_cadenas_largas_por_caracter('Pero que hermoso dia hay'))


N, M = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(M)]

dp = [[10**9] * (2 ** N) for _ in range(M+1)]
dp[0][0] = 0
for i in range(1, M+1):
    for j in range(2**N):
        nlist = [None] * N
        for k in range(N):
            if (j // (2 ** k)) % 2 == 0:
                nlist[k] = 0
            else:
                nlist[k] = 1

        v = 0
        for k in range(N):
            if nlist[k] == 1 or A[i-1][k] == 1:
                v += 2 ** k

        dp[i][j] = min(dp[i][j], dp[i-1][j])
        dp[i][v] = min(dp[i][v], dp[i-1][j] + 1)
#print(dp)
if dp[M][-1] == 10**9:
    print(-1)
else:
    print(dp[M][-1])


import logging
import platform
import time
from collections import OrderedDict

from common import checkhost
from common import iptools
from common import nem_exceptions
from common import netstat
from common import profiler
from common.nem_exceptions import SysmonitorException
from mist import system_resource

# Soglie di sistema
# ------------------------------------------------------------------------------
# Massima quantità di host in rete
TH_HOST = 1
# Minima memoria disponibile
th_avMem = 134217728
# Massimo carico percentuale sulla memoria
th_memLoad = 95
# Massimo carico percentuale sulla CPU
th_cpu = 85

logger = logging.getLogger(__name__)

class SysMonitor(object):
    def __init__(self, check_speed=False, bw_up=1000, bw_down=1000, ispid='fub001'):
        self._check_speed = check_speed
        self._bw_up = bw_up
        self._bw_down = bw_down
        self._ispid = ispid
        self._netstat = netstat.Netstat(iptools.get_dev())
        self._checks = OrderedDict([(system_resource.RES_OS, self.check_os),
                                    (system_resource.RES_CPU, self.checkcpu),
                                    (system_resource.RES_RAM, self.checkmem),
                                    (system_resource.RES_ETH, self.is_ethernet_active),
                                    (system_resource.RES_WIFI, self.checkwireless),
                                    (system_resource.RES_HOSTS, self.checkhosts),
                                    (system_resource.RES_TRAFFIC, self.check_traffic)])

    def checkres(self, res):
        return self._checks[res]()

    def log_interfaces(self):
        all_devices = profiler.get_all_devices()
        for device in all_devices:
            logger.info("============================================")
            device_dict = device.dict()
            for key in device_dict:
                logger.info("| %s : %s" % (key, device_dict[key]))
            logger.info("============================================")

    def check_os(self):
        value = 'unknown'
        try:
            value = platform.platform()
            info = ("Sistema Operativo %s" % value)
            status = True
        except Exception as e:
            info = e
            status = False
        return system_resource.SystemResource(system_resource.RES_OS, status, value, info)

    def checkcpu(self):
        value = -1
        try:
            value = profiler.cpu_load()
            if value < 0 or value > 100:
                raise SysmonitorException('Valore di occupazione della cpu non conforme.', nem_exceptions.BADCPU)

            if value > th_cpu:
                raise SysmonitorException('CPU occupata', nem_exceptions.WARNCPU)
            info = 'Utilizzato il %s%% del processore' % value
            status = True
        except Exception as e:
            info = e
            status = False
        return system_resource.SystemResource(system_resource.RES_CPU, status, value, info)

    def checkmem(self):
        try:
            av_mem = profiler.total_memory()
            if av_mem < th_avMem:
                logger.debug("Memoria disponibile: %2f" % av_mem)
                if av_mem < 0:
                    raise SysmonitorException('Valore di memoria disponibile non conforme.', nem_exceptions.BADMEM)
                else:
                    raise SysmonitorException('Memoria disponibile non sufficiente.', nem_exceptions.LOWMEM)

            mem_load = profiler.percentage_ram_usage()
            if mem_load < 0 or mem_load > 100:
                logger.debug("Memoria occupata: %d%%" % mem_load)
                raise SysmonitorException('Valore di occupazione della memoria non conforme.',
                                          nem_exceptions.INVALIDMEM)
            if mem_load > th_memLoad:
                logger.debug("Memoria occupata: %d%%" % mem_load)
                raise SysmonitorException('Memoria occupata.', nem_exceptions.OVERMEM)

            info = 'Utilizzato il %s%% di %d GB della memoria' % (mem_load, av_mem / (1000 * 1000 * 1000))
            status = True
        except Exception as e:
            mem_load = -1
            info = e
            status = False
        return system_resource.SystemResource(system_resource.RES_RAM, status, mem_load, info)

    def checkwireless(self):
        try:
            if profiler.is_wireless_active():
                raise SysmonitorException('Wireless LAN attiva.', nem_exceptions.WARNWLAN)
            else:
                value = 0
                info = 'Dispositivi wireless non attivi.'
                status = True
        except SysmonitorException as e:
            value = 1
            info = e
            status = False
        except Exception as e:
            logger.error("ERRORE", exc_info=True)
            value = -1
            info = e
            status = False
        return system_resource.SystemResource(system_resource.RES_WIFI, status, value, info)

    def checkhosts(self, use_arp=True):
        value = None
        try:
            ip = iptools.getipaddr()
            mask = iptools.get_network_mask(ip)
            dev = iptools.get_dev(ip=ip)

            logger.info("Indirizzo ip/mask: %s/%d, device: %s" % (ip, mask, dev))

            if iptools.is_public_ip(ip):
                status = True
                info = 'La scheda di rete in uso ha un IP pubblico. Non controllo il numero di dispositivi in rete.'
            else:
                if mask != 0:
                    value = checkhost.count_hosts(ip, mask, self._bw_up, self._bw_down, self._ispid, use_arp)
                    logger.info('Trovati %d dispositivi in rete.', value)
                    if value < 0:
                        raise SysmonitorException('Impossibile determinare il numero di dispositivi in rete.',
                                                  nem_exceptions.BADHOST)
                    elif value == 0:
                        if use_arp:
                            logger.warning("Passaggio a PING per controllo dispositivi in rete")
                            return self.checkhosts(False)
                        else:
                            raise SysmonitorException('Non risulta nessun dispositivo collegato in rete, '
                                                      'verifica connessione al router.',
                                                      nem_exceptions.BADHOST)
                    elif value > TH_HOST:
                        raise SysmonitorException('Ci sono {} altri dispositivi collegati alla tua '
                                                  'rete, scollegali.'.format(value - 1), nem_exceptions.TOOHOST)
                    else:
                        status = True
                        info = 'Trovati %d dispositivi in rete.' % value
                else:
                    raise SysmonitorException('Impossibile recuperare il valore della maschera dell\'IP: %s' % ip,
                                              nem_exceptions.BADMASK)
        except Exception as e:
            info = e
            status = False
        return system_resource.SystemResource(system_resource.RES_HOSTS, status, value, info)

    def is_ethernet_active(self):
        value = 0
        status = False
        info = ''
        try:
            devices = profiler.get_all_devices()
            for device in devices:
                dev_type = device.type
                if dev_type == 'Ethernet 802.3':
                    if device.is_enabled and device.is_active:
                        value = 1
                        info = 'Dispositivi ethernet attivi.'
                        status = True
                        if self._check_speed:
                            if (device.speed * 1000 < self._bw_up) or (device.speed * 1000 < self._bw_down):
                                raise SysmonitorException(("Dispositivi ethernet attivi, ma la scheda di rete di "
                                                           "{0}Mb/s non è sufficiente per misurare correttamente il "
                                                           "profilo riportato in fase "
                                                           "di registrazione.").format(device.speed),
                                                          nem_exceptions.WARNETH)
            if value == 0:
                raise SysmonitorException("Dispositivi ethernet non attivi o non presenti.", nem_exceptions.WARNETH)
        except Exception as e:
            info = e
            status = False
        return system_resource.SystemResource(system_resource.RES_ETH, status, value, info)

    def check_traffic(self, sec=2):

        value = 'unknown'
        try:
            # TODO: check for modified ip or dev
            ip = iptools.getipaddr()
            dev = iptools.get_dev(ip=ip)
            logger.debug("getting stats from dev " + dev)
            start_rx_bytes = self._netstat.get_rx_bytes()
            start_tx_bytes = self._netstat.get_tx_bytes()
            logger.debug("start rx %d, start tx %d" % (start_rx_bytes, start_tx_bytes))
            start_time = time.time()
            time.sleep(sec)
            end_rx_bytes = self._netstat.get_rx_bytes()
            end_tx_bytes = self._netstat.get_tx_bytes()
            measure_time_millis = (time.time() - start_time) * 1000
            logger.debug("end rx %d, end tx %d" % (end_rx_bytes, end_tx_bytes))
            logger.debug("total time millis %d" % measure_time_millis)

            up_kbps = (end_tx_bytes - start_tx_bytes) * 8 / measure_time_millis
            down_kbps = (end_rx_bytes - start_rx_bytes) * 8 / measure_time_millis
            if (up_kbps < 0) or (down_kbps < 0):
                raise SysmonitorException("Ottenuto valore di traffico negativo, potrebbe dipendere dall'azzeramento "
                                          "dei contatori.",
                                          nem_exceptions.FAILREADPARAM)
            value = (down_kbps, up_kbps)
            info = ("{0:.1f} kbps in download e {1:.1f} kbps in upload di traffico globale attuale sull'interfaccia "
                    "di rete in uso.".format(down_kbps, up_kbps))

            if int(up_kbps) < 20 and int(down_kbps) < 200:
                value = 'LOW'
            elif int(up_kbps) < 180 and int(down_kbps) < 1800:
                value = 'MEDIUM'
            else:
                value = 'HIGH'
            if value != 'LOW':
                raise Exception(info)
            status = True
        except Exception as e:
            info = e
            status = False
        return system_resource.SystemResource(system_resource.RES_TRAFFIC, status, value, info)

    def mediumcheck(self):
        self.checkcpu()
        self.checkmem()
        self.checkwireless()

    def checkall(self, use_arp=True):
        self.mediumcheck()
        self.checkhosts(use_arp)
        # TODO: Reinserire questo check quanto corretto il problema di determinazione del dato
        # checkdisk()


import math
import random
from absl import logging
import tensorflow as tf

from ...utils.data_queue import DataQueue

def data_loader(dataset_builder, batch_size=16, num_threads=1):
    """ dataloader
    """
    num_samples = len(dataset_builder)
    if num_samples == 0:
        raise ValueError("num samples is empty")

    if num_threads == 1:
        def _gen_data():
            """ multi thread loader """
            for i in range(num_samples):
                yield dataset_builder[i]
    else:
        # multi-thread
        logging.info("loading data using %d threads" % num_threads)
        data_queue = DataQueue(
            lambda i: dataset_builder[i],
            capacity=4096,
            num_threads=num_threads,
            max_index=num_samples
        )
        def _gen_data():
            """ multi thread loader """
            for _ in range(num_samples):
                yield data_queue.get()

    # make dataset using from_generator
    dataset = tf.compat.v2.data.Dataset.from_generator(
        _gen_data,
        output_types=dataset_builder.sample_type,
        output_shapes=dataset_builder.sample_shape,
    )

    # Padding the features to its max length dimensions.
    dataset = dataset.padded_batch(
        batch_size=batch_size,
        padded_shapes=dataset_builder.sample_shape,
        drop_remainder=True,
    )

    # Prefetch to improve speed of input pipeline.
    dataset = dataset.prefetch(buffer_size=500)
    return dataset

class BaseDatasetBuilder:
    """ base dataset """

    def __init__(self):
        self.entries = []
        self.speakers = []

    def __getitem__(self, index):
        raise NotImplementedError

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

    @property
    def entries_list(self):
        """ return the entries list """
        return self.entries

    @property
    def sample_type(self):
        """ example types """
        raise NotImplementedError

    @property
    def sample_shape(self):
        """ examples shapes """
        raise NotImplementedError

    @property
    def sample_signature(self):
        """ examples signature """
        raise NotImplementedError

    def as_dataset(self, batch_size=16, num_threads=1):
        """ return tf.data.Dataset object """
        return data_loader(self, batch_size, num_threads)

    def shard(self, num_shards, index):
        """ Creates a Dataset that includes only 1/num_shards of this dataset """
        if index >= num_shards:
            raise ValueError("the index should smaller the num_shards")
        logging.info("Creates the sub-dataset which is the %d part of %d" % (index, num_shards))
        original_entries = self.entries
        self.entries = []
        total_samples = (len(original_entries) // num_shards) * num_shards
        for i in range(total_samples):
            if i % num_shards == index:
                self.entries.append(original_entries[i])
        return self

    def batch_wise_shuffle(self, batch_size=64):
        """Batch-wise shuffling of the data entries.

        Each data entry is in the format of (audio_file, file_size, transcript).
        If epoch_index is 0 and sortagrad is true, we don't perform shuffling and
        return entries in sorted file_size order. Otherwise, do batch_wise shuffling.

        Args:
            batch_size: an integer for the batch size. default=64
        """
        if len(self.entries) == 0:
            return self
        logging.info("perform batch_wise_shuffle with batch_size %d" % batch_size)
        max_buckets = int(math.floor(len(self.entries) / batch_size))
        total_buckets = [i for i in range(max_buckets)]
        random.shuffle(total_buckets)
        shuffled_entries = []
        for i in total_buckets:
            shuffled_entries.extend(self.entries[i * batch_size : (i + 1) * batch_size])
        shuffled_entries.extend(self.entries[max_buckets * batch_size :])
        self.entries = shuffled_entries
        return self

    # pylint: disable=unused-argument
    def compute_cmvn_if_necessary(self, is_necessary=True):
        """ vitural interface """
        return self


'''
2019/1/1

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.
'''

def yaku(m):
    return sum([i for i in range(1,m-1) if m % i == 0])

dl = []
for i in range(1,10000):
    a = yaku(i)
    b = yaku(a)

    if i == b and i != a:
        dl.append(i)
        set(dl)

print(sum(dl))


import sys
from itertools import *
from util import *

def parse(line):
    return ints(line) + [0]*3

m = map(parse, sys.stdin)
d = dict(enumerate(m))

combs = list(combinations(d.keys(), 2))

for i in range(1000):
    # update velocities
    for a, b in combs:
        m1 = d[a]
        m2 = d[b]
        for i in range(3):
            # x, y, z
            g = sign(m1[i] - m2[i])
            m1[i+3] -= g
            m2[i+3] += g

    # update positions
    for m in d.values():
        for i in range(3):
            m[i] += m[i+3]

    # calculate energies
    t = 0
    for m in d.values():
        p = 0
        k = 0
        for i in range(3):
            p += abs(m[i])
            k += abs(m[i+3])
        t += p * k

# after all the rounds
print(t)


orders = 0
books = ['calculus', 'physics', 'chemistry', 'history', 'litrature', 'french', 'astronomy']
N = len(books)
for i in range(N):
    for j in range(N):
        if i != j:
            for k in books:
                if k != i and k != j:
                    for l in books:
                        if l != i and l != j and l != k:
                            orders += 1
print('Orders: ')
print(orders)


from PyQt5.QtCore import QSize, Qt, QRect
from PyQt5.QtGui import QIcon, QPixmap, QFont
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QGridLayout, QSystemTrayIcon, qApp, QAction, QMenu, QDesktopWidget

from current import Current, History
from lat_lon import lat_lon
from search import Search
from sqlbase import conn
from watch import Watch

class Weather(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(540, 240))
        self.setWindowTitle("Senex")
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setWindowFlags(Qt.SplashScreen | Qt.FramelessWindowHint)
        with conn:
            cur = conn.cursor()
            cur.execute('SELECT * FROM settings;')
            (color, position) = cur.fetchone()
            cur.execute('SELECT timezone, lat, lon FROM info;')
            info = cur.fetchone()
        self.change_color(color)
        self.position(position)
        del color, position

        self.timezone = info[0] if info else 0
        self.geo = (info[1], info[2]) if info else None

        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName("centralwidget")

        self.layoutWidget = QWidget(self.centralwidget)
        self.layoutWidget.setGeometry(QRect(3, 2, 515, 235))
        self.layoutWidget.setObjectName("layoutWidget")

        self.gridLayout = QGridLayout(self.layoutWidget)
        self.gridLayout.setAlignment(Qt.AlignLeft)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")

        tempfont = QFont()
        tempfont.setPointSize(40)
        cityfont = QFont()
        cityfont.setPointSize(16)
        midfont = QFont()
        midfont.setPointSize(12)
        smallfont = QFont()
        smallfont.setPointSize(10)

        self.datetime = QLabel(self.layoutWidget)
        self.datetime.setFont(midfont)
        self.datetime.setObjectName("datetime")
        self.gridLayout.addWidget(self.datetime, 0, 0, 1, 5)

        self.city = QLabel(self.layoutWidget)
        self.city.setFont(cityfont)
        self.city.setObjectName("city")
        self.gridLayout.addWidget(self.city, 1, 0, 1, 5)

        self.temp = QLabel(self.layoutWidget)
        self.temp.setFont(tempfont)
        self.temp.setAlignment(Qt.AlignCenter)
        self.temp.setObjectName("temp")
        self.gridLayout.addWidget(self.temp, 2, 0, 2, 1)

        self.icon = QLabel(self.layoutWidget)
        self.icon.setObjectName("icon")
        self.gridLayout.addWidget(self.icon, 2, 1, 2, 2)

        self.weather = QLabel(self.layoutWidget)
        self.weather.setFont(midfont)
        self.weather.setObjectName("weather")
        self.gridLayout.addWidget(self.weather, 2, 3, 1, 2)

        self.feels = QLabel(self.layoutWidget)
        self.feels.setFont(midfont)
        self.feels.setObjectName("feels")
        self.gridLayout.addWidget(self.feels, 3, 3, 1, 2)

        self.sunrise = QLabel(self.layoutWidget)
        self.sunrise.setFont(midfont)
        self.sunrise.setObjectName("sunrise")
        self.gridLayout.addWidget(self.sunrise, 4, 0, 1, 3)

        self.sunset = QLabel(self.layoutWidget)
        self.sunset.setFont(midfont)
        self.sunset.setObjectName("sunset")
        self.gridLayout.addWidget(self.sunset, 4, 3, 1, 2)

        self.wind = QLabel(self.layoutWidget)
        self.wind.setFont(midfont)
        self.wind.setObjectName("wind")
        self.gridLayout.addWidget(self.wind, 5, 0, 1, 2)

        self.humidity = QLabel(self.layoutWidget)
        self.humidity.setFont(midfont)
        self.humidity.setObjectName("humidity")
        self.gridLayout.addWidget(self.humidity, 5, 2, 1, 2)

        self.pressure = QLabel(self.layoutWidget)
        self.pressure.setFont(midfont)
        self.pressure.setObjectName("pressure")
        self.gridLayout.addWidget(self.pressure, 5, 4, 1, 1)

        self.yandex = QLabel(self.layoutWidget)
        self.yandex.setFont(smallfont)
        self.yandex.setObjectName("yandex")
        self.gridLayout.addWidget(self.yandex, 6, 0, 1, 5)

        self.today = QLabel(self.layoutWidget)
        self.today.setFont(smallfont)
        self.today.setObjectName("today")
        self.gridLayout.addWidget(self.today, 7, 0, 1, 5)

        self.tomorrow = QLabel(self.layoutWidget)
        self.tomorrow.setFont(smallfont)
        self.tomorrow.setObjectName("tomorrow")
        self.gridLayout.addWidget(self.tomorrow, 8, 0, 1, 5)

        self.setCentralWidget(self.centralwidget)

        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QIcon('icons/01d.png'))

        position_action = QMenu("Положение виджета", self)
        color_action = QMenu("Цвет текста", self)
        city_action = QAction("Выбрать город", self)
        update_action = QAction("Обновить местоположение", self)
        quit_action = QAction("Закрыть Senex", self)

        tray_menu = QMenu()
        tray_menu.addMenu(position_action)
        tray_menu.addMenu(color_action)
        tray_menu.addAction(city_action)
        tray_menu.addAction(update_action)
        tray_menu.addAction(quit_action)

        center_action = QAction("По центру", self)
        upleft_action = QAction("Слева вверху", self)
        downleft_action = QAction("Слева внизу", self)
        upright_action = QAction("Справа вверху", self)
        downright_action = QAction("Справа внизу", self)

        position_action.addAction(center_action)
        position_action.addAction(upleft_action)
        position_action.addAction(downleft_action)
        position_action.addAction(upright_action)
        position_action.addAction(downright_action)

        white_action = QAction("Белый", self)
        black_action = QAction("Черный", self)
        gray_action = QAction("Серый", self)
        red_action = QAction("Красный", self)
        orange_action = QAction("Оранжевый", self)
        yellow_action = QAction("Желтый", self)
        green_action = QAction("Зеленый", self)
        blue_action = QAction("Синий", self)
        indigo_action = QAction("Индиго", self)
        violet_action = QAction("Фиолетовый", self)

        color_action.addAction(white_action)
        color_action.addAction(black_action)
        color_action.addAction(gray_action)
        color_action.addAction(red_action)
        color_action.addAction(orange_action)
        color_action.addAction(yellow_action)
        color_action.addAction(green_action)
        color_action.addAction(blue_action)
        color_action.addAction(indigo_action)
        color_action.addAction(violet_action)

        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()

        self.history = History(mainwindow=self)
        self.watch = Watch(mainwindow=self)
        self.current = Current(mainwindow=self)
        self.search = Search(mainwindow=self)

        self.watch.run()
        self.history.run()
        self.current.run()

        center_action.triggered.connect(lambda: self.position('center'))
        upleft_action.triggered.connect(lambda: self.position('upleft'))
        downleft_action.triggered.connect(lambda: self.position('downleft'))
        upright_action.triggered.connect(lambda: self.position('upright'))
        downright_action.triggered.connect(lambda: self.position('downright'))

        white_action.triggered.connect(lambda: self.change_color('white'))
        black_action.triggered.connect(lambda: self.change_color('black'))
        gray_action.triggered.connect(lambda: self.change_color('gray'))
        red_action.triggered.connect(lambda: self.change_color('red'))
        orange_action.triggered.connect(lambda: self.change_color('orange'))
        yellow_action.triggered.connect(lambda: self.change_color('yellow'))
        green_action.triggered.connect(lambda: self.change_color('green'))
        blue_action.triggered.connect(lambda: self.change_color('blue'))
        indigo_action.triggered.connect(lambda: self.change_color('indigo'))
        violet_action.triggered.connect(lambda: self.change_color('violet'))

        city_action.triggered.connect(lambda: self.search.show())

        update_action.triggered.connect(lambda: self.current.new_values())

        quit_action.triggered.connect(qApp.quit)

        self.show()

    def seticon(self, path):
        self.icon.setPixmap(QPixmap(path))
        self.tray_icon.setIcon(QIcon(path))

    def change_color(self, color):
        self.setStyleSheet("QLabel { color: " + color + " }")
        with conn:
            cur = conn.cursor()
            cur.execute(f'UPDATE settings SET color = "{color}";')
            conn.commit()

    def position(self, pos):
        """ 'center'    - по центру
            'upleft'    - левый верхний угол
            'downleft'  - левый нижний угол
            'upright'   - правый верхний угол
            'downright' - правый нижний угол (стандартная позиция)"""

        _screen = QDesktopWidget().availableGeometry()
        width, height = (_screen.width(), _screen.height())
        x = width - 540
        y = height - 240
        if pos == 'center':
            x, y = x // 2, y // 2
        elif pos == 'upleft':
            x, y = 0, 0
        elif pos == 'downleft':
            x, y = 0, y
        elif pos == 'upright':
            x, y = x, 0
        self.move(x, y)
        with conn:
            cur = conn.cursor()
            cur.execute(f'UPDATE settings SET position = "{pos}";')
            conn.commit()
        del _screen, width, height, x, y, pos

if __name__ == "__main__":
    import sys

    from PyQt5.QtWidgets import QApplication

    app = QApplication(sys.argv)
    main = Weather()
    sys.exit(app.exec())


import serial
import socket
import sys
import time

host = 'pbridge.adm.cs.cmu.edu'
#host = '' #fills in address of host machine
port = 15441

#bailiang's computer
#ser = serial.Serial('/dev/cu.usbserial-A403I0LM', 9600)

#marisa's computer
ser = serial.Serial('/dev/ttyUSB0', 9600)

while 1:
    message = ser.readline()
    #message = raw_input("enter something:")

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (host, port)
    sock.connect(server_address)
    print >>sys.stderr, 'connecting to %s port %s' % server_address

    m_arr = message.split(' ')
    sensor = m_arr[0]
    velocity = str(float(m_arr[1]) / 100) #divide by 100 to obtain m/s

    print >>sys.stderr, 'sending: %s' % message
    sock.send(sensor)
    sock.send(velocity)
    time.sleep(1)

    print >>sys.stderr, 'closing socket'
    sock.close()


"""
For this challenge you will transform a string using the Caesar Cipher.

Have the function CaesarCipher(str,num) take the str parameter and perform a Caesar Cipher shift
on it using the num parameter as the shifting number. A Caesar Cipher works by shifting each letter
in the string N places down in the alphabet (in this case N will be num). Punctuation, spaces, and
capitalization should remain intact. For example if the string is "Caesar Cipher" and num is 2
the output should be "Ecguct Ekrjgt".
"""

def CaesarCipher(string: str, num: int):
    res = ""
    for i in range(len(string)):
        char = string[i]
        if not char.isalpha():
            res += char
        else:
            res += chr(ord(char) + num)
    return res

print(CaesarCipher("Caesar Cipher", 2))


# Create a file called test_cities.py that tests the function you just wrote
# (remember that you need to import unittest and the function you want to test).
# Write a method called test_city_country() to verify that calling your function
# with values such as 'santiago' and 'chile' results in the correct string. Run
# test_cities.py, and make sure test_city_country() passes.
import unittest
from city_functions import name_city, name_city_with_pop
print('Exercise 1:')
class CityTestCase(unittest.TestCase):
    """Tests for 'city_functions.py'."""

    def test_city_country(self):
        """Does the city and country return successfully"""
        city_name = name_city('santiago', 'chile')
        self.assertEqual(city_name, 'Santiago, Chile')

# 11-2. Population: Modify your function so it requires a third parameter,
# population. It should now return a single string of the form City, Country –
# population xxx, such as Santiago, Chile – population 5000000. Run
# test_cities.py again. Make sure test_city_country() fails this time.
# Modify the function so the population parameter is optional. Run
# test_cities.py again, and make sure test_city_country() passes again.
# Write a second test called test_city_country_population() that verifies you
# can call your function with the values 'santiago', 'chile', and
# 'population=5000000'. Run test_cities.py again, and make sure this new test
# passes.
    def test_city_with_no_pop(self):
        city_name = name_city_with_pop('santiago', 'chile')
        self.assertEqual(city_name, 'Santiago, Chile')

    def test_city_with_pop(self):
        city_name = name_city_with_pop('santiago', 'chile', 50000)
        self.assertEqual(city_name, 'Santiago, Chile - 50000')

unittest.main()

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


from datetime import datetime, timedelta
import requests
from colorama import Fore

class PolygonAPI:
    def __init__(self, url, key):
        # Inicialización de variables de instancia
        self.end_date = None
        self.start_date = None
        self.ticker = None

        # Declaración de variables privadas
        self.__url = url
        self.__api_key = key

    def get(self):
        self.ticker = self.get_ticker()

        while True:
            self.start_date = self.get_date("Ingrese la fecha de inicio (YYYY-MM-DD):\n")
            self.end_date = self.get_date("Ingrese la fecha de fin (YYYY-MM-DD):\n")
            if self.start_date <= self.end_date:
                break
            else:
                print(f'{Fore.YELLOW}ERROR: La fecha de inicio no puede ser mayor a la fecha de fin{Fore.RESET}')

        header = {
            "Authorization": "Bearer " + self.__api_key
        }

        print("Obteniendo datos...")

        request_url = self.__url + "/aggs/ticker/" + self.ticker + "/range/1/day/" + self.start_date + "/" + \
                             self.end_date + "?adjusted=true&sort=asc&limit=15000"
        try:
            response = requests.get(request_url, headers=header)
            response.raise_for_status()
        except requests.exceptions.Timeout:
            print(f'{Fore.YELLOW}Error de Timeout{Fore.RESET}')
            return 0
        except requests.exceptions.TooManyRedirects as err:
            print(f"{Fore.YELLOW}ERROR:{Fore.RESET}", err)
            return 0
        except requests.exceptions.HTTPError as err:
            print(f"{Fore.YELLOW}ERROR:{Fore.RESET}", err)
            return 0
        except requests.exceptions.RequestException:
            print(f"{Fore.YELLOW}ERROR: El servidor no responde. Verifique la conexión{Fore.RESET}")
            return 0
        except:
            print(f'{Fore.YELLOW}Error desconocido{Fore.RESET}')
            return 0
        else:
            if response.json()['resultsCount'] == 0:
                print(f'{Fore.YELLOW}No se obtuvieron resultados, verifique ticker y rango de fechas{Fore.RESET}')
                return 0
            else:
                return response.json()

    def get_ticker(self):
        ticker = input("Ingrese el ticker a pedir: \n").upper()
        return ticker

    def get_date(self, text):
        while True:
            date = input(text)
            date_now = datetime.today()

            # Se verifica que la fecha ingresada tenga el formato correcto
            try:
                date = datetime.strptime(date, '%Y-%m-%d')
            except ValueError:
                print("Formato de fecha incorrecto, debe ingresarse como YYYY-MM-DD")
            else:
                if date.date() > date_now.date():
                    print("La fecha ingresada no puede ser mayor a la fecha actual")
                if date < (date_now - timedelta(days=2*365)):
                    # Limitación cuenta Polygon
                    print("La subscripción gratuita no entrega registros de más de 2 años de antigüedad")
                else:
                    return str(date.date())


import datetime
import errno
import os
import socket
from typing import List

def port_in_use(port: int):
    """
    Checks whether a port is available on the local system.
    """
    a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    location = ("127.0.0.1", port)
    result_of_check = a_socket.connect_ex(location)

    return result_of_check == 0

def check_ports(port_list: List[int]):
    """
    Takes a list of integers and check whether those ports are available.

    Returns a list of ports which are busy.
    """
    return list(filter(port_in_use, port_list))

def exist_or_create(folder):
    if not os.path.exists(os.path.dirname(folder)):
        try:
            os.makedirs(os.path.dirname(folder))
        except OSError as exc:
            if exc.errno != errno.EEXIST:
                raise

def age_from_timestamp(timestamp):
    delta = datetime.timedelta(seconds=datetime.datetime.now(tz=datetime.timezone.utc).timestamp() - timestamp)
    if delta >= datetime.timedelta(days=1):
        result = f"{delta.days}d"
    elif delta >= datetime.timedelta(hours=1):
        result = f"{delta.seconds // 3600}h"
    elif delta >= datetime.timedelta(minutes=10):
        result = f"{delta.seconds // 60}m"

    elif delta >= datetime.timedelta(minutes=1):
        result = f"{delta.seconds // 60}m{delta.seconds % 60}s"
    else:
        result = f"{delta.seconds}s"
    return result


'''
İşlev: Ses dosyasından metin dosyasına dönüştürme.
Girdi: Ses dosyası (.wav .aiff .aif .aifc .flac)
Çıktı: Metin dosyası (.txt)
İşlem adımları;
1. Başla
2. Ses Dosyası seç
3. Seçilen sesi metne dönüştür
4. Metni dosyaya kaydet
5. Oluşturulan dosya içeriğini dosyayı terminalde göster
6. Dur

Kullandığım kaynaklar
https://www.thepythoncode.com/article/using-speech-recognition-to-convert-speech-to-text-python
https://medium.com/bili%C5%9Fim-hareketi/python-ile-ses-tan%C4%B1ma-uygulamas%C4%B1-olu%C5%9Fturma-3d0d972c62a6
'''

import time
import speech_recognition as sr
import codecs
import tkinter as tk
from tkinter import filedialog
from pathlib import Path

# Ses dosyası seç
root = tk.Tk()
root.withdraw()

# dosya yolu oluştur
file_path = filedialog.askopenfilename(filetypes=[("Ses dosyaları",".wav .aiff .aif .aifc .flac")])

# Seçilen sesi metne dönüştür
r = sr.Recognizer()
file = sr.AudioFile(file_path)
with file as source:
    r.adjust_for_ambient_noise(source)
    audio = r.record(source)
    result = r.recognize_google(audio, language='tr-TR')

# Metni dosyaya kaydet
pathName = Path(file_path)
pathName = pathName.name
fileName = str(int(time.time()))+"-"+pathName+".txt"
f = codecs.open(fileName, "a", "utf-8")
f.write(result)
f.close()

# Oluşturulan dosya içeriğini dosyayı terminalde göster
f = open(fileName, "r", encoding='utf-8')
print(f.read())


def part1():
    aro = []

    arr = []
    for num in open('input.txt'):
        num = num.strip()
        if num != '':
            arr.append(int(num))
        else:
            aro.append(sum(arr))
            arr = []
    aro.sort()
    return sum(aro[-3:])

if __name__ == '__main__':
    print("Part 1: " + str(part1()))


import os
import sys
import scipy.sparse as ssp
from scipy.spatial.distance import cosine
from sklearn.metrics import classification_report

sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")

from pickle import load, dump
from feature_extract.tf_kdl_weight import TFKLD
from feature_extract.dimention_reduction import DimReduction
from feature_extract.preprocess import my_tokenizer

if __name__ == "__main__":

    tfkdl_params_path = "../data/tfkdl_params.pickle"
    tfkdl_params = load(open(tfkdl_params_path, "rb"))

    countvector_model = tfkdl_params["countvector_model"]
    tfkdl_weight = tfkdl_params["weight"]

    tfkdl_object = TFKLD(None)

    dataset_path = "../data/data_tfkdl.txt"
    datasetT, datasetL = tfkdl_object.loadtext(dataset_path)
    datasetT = countvector_model.transform(datasetT)
    datasetT = ssp.lil_matrix(datasetT).todense()

    datasetT_weight = tfkdl_object.weighting_internal(datasetT, tfkdl_weight)

    #dr = DimReduction(datasetT_weight, 200)
    #W, H = dr.svd()
    W = datasetT_weight

    nrow, ndim = W.shape

    pred_val = []
    cosine_sim_list = []

    for index in range(0, nrow, 2):
        sent_1 = W[index, :]
        sent_2 = W[index + 1, :]

        label = datasetL[index // 2]

        cosine_val = 1 - cosine(sent_1, sent_2)

        cosine_sim_list.append(cosine_val)

        if cosine_val >= 0.5:
            pred_val.append(1)
        else:
            pred_val.append(0)

    dump(cosine_sim_list, open("../data/tfkdl_pred_withoutdr", "wb"))

    print(classification_report(datasetL, pred_val))