# Importing required modules
import website
import media

# Creating instances for each movie with title, release date, genre, director
# poster, trailer, and brief description.
hypernorm = media.Movie("HyperNormalisation",
                        "2016",
                        "Documentary",
                        "Adam Curtis",
                        "https://upload.wikimedia.org/wikipedia/en/5/5e/HyperNormalisation.jpg",  # N0QA
                        "https://www.youtube.com/watch?v=-fny99f8amM",
                        "Thought-provoking BBC documentary on power "
                        "and narratives in contemporary society.")

samsara = media.Movie("Samsara",
                      "2011",
                      "Documentary",
                      "Rob Fricke",
                      "https://upload.wikimedia.org/wikipedia/en/7/78/Samsara_Film_Poster.jpg",  # N0QA
                      "https://www.youtube.com/watch?v=P0xVp3N-M84",
                      "Visually stunning meditation on humankind's "
                      "simultaneous majesty and vulnerability.")

m_mambo = media.Movie("Millennium Mambo",
                      "2001",
                      "Drama",
                      "Hou Hsiao-Hsien",
                      "https://upload.wikimedia.org/wikipedia/en/8/89/Millennium_mambo.jpg",  # N0QA
                      "https://www.youtube.com/watch?v=8ubt8JvykiQ",
                      "Taiwanese art house film about the fleeting "
                      "beauty of youth.")

short_term_12 = media.Movie("Short Term 12",
                            "2013",
                            "Drama",
                            "Destin Daniel Cretton",
                            "https://upload.wikimedia.org/wikipedia/en/b/b8/Short_Term_12.jpg",  # N0QA
                            "https://www.youtube.com/watch?v=qhS6tvSb0UQ",
                            "Heart-breaking story of a foster home's employees "
                            "and residents.")

eternal_sunshine = media.Movie("Eternal Sunshine of the Spotless Mind",
                               "2004",
                               "Drama",
                               "Michel Gondry",
                               "https://upload.wikimedia.org/wikipedia/en/6/62/Eternal_sunshine_of_the_spotless_mind_ver3.jpg",  # N0QA
                               "https://www.youtube.com/watch?v=1GiLxkDK8sI",
                               "Is love worth it? Who knows???")

totoro = media.Movie("My Neighbor Totoro",
                     "1988",
                     "Animation",
                     "Hayao Miyazaki",
                     "https://upload.wikimedia.org/wikipedia/en/0/02/My_Neighbor_Totoro_-_Tonari_no_Totoro_%28Movie_Poster%29.jpg",  # N0QA
                     "https://www.youtube.com/watch?v=92a7Hj0ijLs",
                     "Adorable, feel-good cartoon about siblings in the "
                     "Japanese countryside and their mysterious friend.")

# Listing each object in an array
movies = [hypernorm, samsara, m_mambo, short_term_12, eternal_sunshine, totoro]

# Call method to generate movie page in .html
website.open_movies_page(movies)


from __future__ import annotations

import logging
import sys
from typing import Dict, Optional, Any, List

from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse

from same_thing.db import purge_data_dbs
from same_thing.exceptions import UriNotFound
from same_thing.query import get_cluster, UriCluster

debug = '--debug' in sys.argv
if debug:
    # assume this is run in a single process
    purge_data_dbs()

app = Starlette(debug=debug)

@app.on_event('startup')
def log_ready_message() -> None:
    logger = logging.getLogger('uvicorn')
    logger.info('Same Thing Service is ready for lookups.')

@app.route('/lookup/', methods=['GET'])
def lookup(request: Request) -> JSONResponse:
    single_uri = request.query_params.get('uri')
    uris = request.query_params.getlist('uris') or [single_uri]
    if not any(uris):
        return JSONResponse({
            'uri': 'The `uri` parameter must be provided.'
        }, status_code=400)

    fields_by_uri: Dict[str, Optional[UriCluster]] = {}
    for uri in uris:
        try:
            fields_by_uri[uri] = get_cluster(uri)
        except UriNotFound:
            fields_by_uri[uri] = None

    response_fields: Dict[str, Any] = {}
    if not any(fields_by_uri.values()):
        if single_uri:
            return single_uri_not_found(single_uri)
        else:
            return multiple_uris_not_found(uris)
    elif single_uri:
        response_fields = fields_by_uri[single_uri]
    else:
        response_fields['uris'] = fields_by_uri

    meta = request.query_params.get('meta')
    if not (meta and meta == 'off'):
        response_fields['meta'] = {
            'documentation': 'http://dev.dbpedia.org/Global%20IRI%20Resolution%20Service',
            'github': 'https://github.com/dbpedia/dbp-same-thing-service',
            'license': 'http://purl.org/NET/rdflicense/cc-by3.0',
            'license_comment': 'Free service provided by DBpedia. Usage and republication of data implies that you '
                               'attribute either http://dbpedia.org as the source or reference the latest general '
                               'DBpedia paper or the specific paper mentioned in the GitHub Readme.',
            'comment': """
                The service resolves any IRI to its cluster and displays the global IRI and its cluster members.
                Cluster members can change over time as the DBpedia community,
                data providers and professional services curate the linking space.

                Usage note:
                1. Save the global ID AND the local IRI that seems most appropriate.
                   It is recommended that you become a data provider, in which case the local IRI would be your IRI.
                2. Use the global ID to access anything DBpedia.
                3. Use the stored local ID to update and re-validate linking and clusters.
            """,
        }

    return JSONResponse(response_fields)

def single_uri_not_found(uri: str) -> JSONResponse:
    return JSONResponse({
        'uri': uri
    }, status_code=404)

def multiple_uris_not_found(uris: List[str]) -> JSONResponse:
    return JSONResponse({
        'uris': uris
    }, status_code=404)


from argparse import ArgumentParser
import  os

parser = ArgumentParser()

model_path = os.path.join('/models/hubert/', 'hubert.pt')

parser.add_argument('--train_dataset', default='/train/dataset')
parser.add_argument('--process', default='/train/Literature/prepared')
parser.add_argument('--train', default='/train/Literature/ready')

parser.add_argument('--hubert-model', default='./models/hubert/hubert.pt', help='The hubert model to use for preparing the data and later creation of semantic tokens.')
parser.add_argument('--train-save-epochs', default=1, type=int, help='The amount of epochs to train before saving')

args = parser.parse_args()


import tensorflow as tf

class Network:
  def __init__(self, sess):
    self.create_network()
    self.sess = sess

  def train(self, train_images, train_labels, keep_prob):
    ops_to_run = [self.loss, self.percent_correct, self.step]
    return tuple(self.sess.run(ops_to_run, feed_dict={self.x: train_images, self.correct_labels: train_labels, self.keep_prob: keep_prob}))

  def run(self, input):
    ops_to_run = [self.pixels_as_floats, self.actual_prediction]
    return tuple(self.sess.run(ops_to_run, feed_dict={self.x: input, self.keep_prob: 1.0}))

  def evaluate(self, input, expected_output):
    return self.sess.run(network.percent_correct, feed_dict={self.x: input, self.correct_labels: expected_output, self.keep_prob: 1.0})

  def create_network(self):
    filter_conv_1_size = 3
    filter_1_count = 32

    filter_conv_2_size = 3
    filter_2_count = 64

    filter_conv_3_size = 3
    filter_3_count = 64

    fc_1_count = 512

    self.x = tf.placeholder(tf.float32, shape=[None, 32, 32, 3])

    self.pixels_as_floats = tf.divide(self.x, 255.0)
    self.cleaned_x = tf.subtract(self.pixels_as_floats, 0.5)

    self.filters_conv_1 = tf.Variable(tf.truncated_normal(shape=[filter_conv_1_size, filter_conv_1_size, 3, filter_1_count], stddev=0.2))
    self.bias_conv_1 = tf.Variable(tf.truncated_normal(shape=[filter_1_count], stddev=0.2))
    self.conv_1 = tf.nn.max_pool(tf.nn.relu(tf.nn.conv2d(input=self.cleaned_x, filter=self.filters_conv_1, strides=[1, 1, 1, 1], padding='SAME') + self.bias_conv_1), ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    self.filters_conv_2 = tf.Variable(tf.truncated_normal(shape=[filter_conv_2_size, filter_conv_2_size, filter_1_count, filter_2_count], stddev=0.2))
    self.bias_conv_2 = tf.Variable(tf.truncated_normal(shape=[filter_2_count], stddev=0.2))
    self.conv_2 = tf.nn.relu(tf.nn.conv2d(input=self.conv_1, filter=self.filters_conv_2, strides=[1, 1, 1, 1], padding='SAME') + self.bias_conv_2)

    self.filters_conv_3 = tf.Variable(tf.truncated_normal(shape=[filter_conv_3_size, filter_conv_3_size, filter_2_count, filter_3_count], stddev=0.2))
    self.bias_conv_3 = tf.Variable(tf.truncated_normal(shape=[filter_3_count], stddev=0.2))
    self.conv_3 = tf.nn.max_pool(tf.nn.relu(tf.nn.conv2d(input=self.conv_2, filter=self.filters_conv_3, strides=[1, 1, 1, 1], padding='SAME') + self.bias_conv_3), ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    self.keep_prob = tf.placeholder(tf.float32)
    self.fully_connected_w1 = tf.Variable(tf.truncated_normal(shape=[filter_3_count * 8 * 8, fc_1_count], stddev=0.2))
    self.bias_fc_1 = tf.Variable(tf.truncated_normal(shape=[fc_1_count], stddev=0.2))
    self.fully_connected_1 = tf.nn.dropout(tf.nn.relu(tf.matmul(tf.reshape(self.conv_3, shape=[tf.shape(self.x)[0], filter_3_count * 8 * 8]), self.fully_connected_w1) + self.bias_fc_1), self.keep_prob)

    self.fully_connected_w2 = tf.Variable(tf.truncated_normal(shape=[fc_1_count, 10], stddev=0.2))
    self.bias_fc_2 = tf.Variable(tf.truncated_normal(shape=[10], stddev=0.2))
    self.fully_connected_2 = tf.matmul(self.fully_connected_1, self.fully_connected_w2) + self.bias_fc_2

    self.actual_prediction = tf.reshape(tf.arg_max(self.fully_connected_2, 1), shape=[1])

    self.correct_labels = tf.placeholder(tf.int64)
    self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.one_hot(self.correct_labels, 10), logits=self.fully_connected_2))
    self.step = tf.train.AdamOptimizer().minimize(self.loss)

    self.percent_correct = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.fully_connected_2, 1), self.correct_labels), tf.float32))


from selenium import webdriver
import requests
from lxml import etree
import time
from bs4 import BeautifulSoup
import json as js

if __name__ == '__main__':
    chromedriver = "/Users/heweiwen/Downloads/work/Solf/chrome-mac/chromedriver"
    driver = webdriver.Chrome(executable_path=chromedriver)
    home_url = "https://drugs.dxy.cn"
    driver.get(home_url)  # 打开网址
    driver.get(home_url)
    drugs_1 = etree.HTML(driver.page_source)
    drugs_1_list = drugs_1.xpath('//div[@class="category-tab__37us"]/span/text()')
    drugs_1_tab = drugs_1.xpath('//div[@class="ant-tabs-tab"]')

    html = driver.page_source
    # BeautifulSoup转换页面源码
    bs = BeautifulSoup(html, 'lxml')
    # 获取Script标签下的完整json数据，并通过json加载成字典格式
    contents = bs.find("script", {"id": "__NEXT_DATA__"}).contents
    # json 父子级别
    js_test = {}
    pageProps = {}
    # 父级
    firstLevelCategoryList = []
    # 子级
    secondLevelCategoryList = []
    # firstjson
    for i in range(0, len(contents)):
        print(contents[i])
        js_test = js.loads(contents[i])
        pageProps = js_test['props']['pageProps']
        # pageProps = js.dumps(contents[i]).find('props')
    firstLevelCategoryList = pageProps['firstLevelCategoryList']
    secondLevelCategoryList = pageProps['secondLevelCategoryList']

    for f in firstLevelCategoryList:
        id = f['id']
        name = f['name']
        # 获取所有子集
        secondsList = []
        for s in secondLevelCategoryList:
            if s['supId'] == id:
                seconds = {}
                seconds['id'] = s['id']
                seconds['name'] = s['name']
                seconds['supId'] = s['supId']
                seconds['recommendDrugs'] = s['recommendDrugs']
                secondsList.append(seconds)

    for i in range(0, len(drugs_1_tab)):
        driver.find_element_by_xpath('//div[@style="margin-bottom:0"]').click()
    drugs_1_tabpanel = drugs_1.xpath('//div[@role="tabpanel"]')

    for div in drugs_1_tab:
        # driver.find_element_by_xpath('//div[@class="ant-tabs-tab"]').click()
        # bottom = div.xpath('./div[@class="ant-tabs-tab-btn"]/@id')
        id = div.xpath('./div[@class="ant-tabs-tab-btn"]/@id')
        print(id)
    for div in drugs_1_tabpanel:
        tabpanel_names = div.xpath('./ul/li[@class="category-item__ZnzJ"]')
        for div_1 in tabpanel_names:
            nams = div_1.xpath('./h3/a/text()')
            print(nams)


import os
import sys
from configparser import ConfigParser
from n6wells.db import *
from n6wells.container import fixtures
from n6wells.xaction import Xaction
from n6wells.sample import Sample, SampleType, Plating
from n6wells.container import ContainerType, Container, ContainerInst
from configparser import ConfigParser

def get_config():
    fname = os.path.join( os.path.dirname( sys.modules[__name__].__file__ ), 'intgrtest.ini')
    config = ConfigParser()
    config.read( fname )
    return config

@committer
def populate_plate(db):
    xaction = Xaction()
    db.add(xaction)
    db.commit()
    typ1, typC = SampleType(name='patient'), SampleType(name='control')
    s1, s2 = Sample(sample_type=typ1), Sample(sample_type=typC)
    plate96_t = db.query(ContainerType).filter(ContainerType.name=='Plate-96_well').one()
    plate = ContainerInst( name='my_plate', type=plate96_t )
    db.add(plate)
    db.commit()

    well1 = db.query(Container).filter(Container.type == plate96_t).filter(Container.name == 'A01').one()
    well2 = db.query(Container).filter(Container.type == plate96_t).filter(Container.name == 'A02').one()
    p1 = Plating( plate=plate, well=well1, sample=s1, xaction=xaction )
    p2 = Plating( plate=plate, well=well2, sample=s2, xaction=xaction )
    db.add( p1 )
    db.add( p2 )

def main():
    print('@@ helper main')
    config = get_config()
    destroydb(config['DB']['engine'])
    initdb(config['DB']['engine'])
    DB << fixtures.load()
    DB << populate_plate()


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

from django.db import migrations, models
import filebrowser.fields

class Migration(migrations.Migration):

    dependencies = [
        ('newsroom', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Tweet',
            fields=[
                ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
                ('wait_time', models.PositiveIntegerField(help_text='Number of minutes after publication till tweet.')),
                ('status', models.CharField(choices=[('scheduled', 'Scheduled'), ('sent', 'Sent'), ('failed', 'Failed'), ('paused', 'Paused')], max_length=20, default='scheduled')),
                ('tweet_text', models.CharField(max_length=117, blank=True)),
                ('image', filebrowser.fields.FileBrowseField(blank=True, max_length=200, null=True)),
                ('characters_left', models.IntegerField(default=116)),
                ('article', models.ForeignKey(to='newsroom.Article')),
            ],
            options={
                'ordering': ['article__published', 'wait_time'],
            },
        ),
        migrations.CreateModel(
            name='TwitterHandle',
            fields=[
                ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
                ('name', models.CharField(unique=True, max_length=200)),
                ('slug', models.SlugField(unique=True, max_length=200)),
            ],
            options={
                'verbose_name': 'Twitter handle',
                'ordering': ['name'],
                'verbose_name_plural': 'Twitter Handles',
            },
        ),
        migrations.AddField(
            model_name='tweet',
            name='tag_accounts',
            field=models.ManyToManyField(to='socialmedia.TwitterHandle', blank=True),
        ),
    ]


# coding=utf-8
# author:xsl

from bson import ObjectId
from mongoengine import (
        StringField,
        IntField,
        BooleanField,
        ObjectIdField,
        ListField,
        DictField,
        DateTimeField,
        Document,
        )

class Source(Document):
    meta = {
        'db_alias': 'testdb',
        'index_background': True,
        'indexes': [],
    }

    id = ObjectIdField(primary_key=True, default=ObjectId)
    userid = ObjectIdField()
    name = StringField()
    desc = StringField()
    url = StringField()
    type = StringField()
    thirdid = StringField()
    extra = StringField()

    def save(self, *args, **kwargs):
        return super(Source, self).save(*args, **kwargs)


from ai_backend.utils.lr_utils import load_dataset
from ai_backend.neural_network.model import model

def logistic_regression():
    # Loading the data (person/non-person)
    train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()

    train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
    test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T

    train_set_x = train_set_x_flatten/255.
    test_set_x = test_set_x_flatten/255.

    w, b = model(train_set_x, train_set_y, test_set_x, test_set_y,
                 num_iterations=2000, learning_rate=0.005, print_cost=True)

    return w, b


# encoding: utf-8
# Created on 2014-5-22
# @author: binge

from scrapy.selector import Selector
from scrapy import log
from utils.item_helper import ItemHelper
from scrapy.http.request import Request
import datetime
from utils.common import SpiderHelper, TimeHelper
from utils.conns_helper import RedisHelper
from spiders.common_spider import CommonSpider

class K17Spiser(CommonSpider):

    name = 'k17'

    def __init__(self, **kwargs):
        self.start_urls = [
                           'http://all.17k.com/all'
                           ]
        self.source_name = u'17K小说网'
        self.domain = 'http://www.17k.com'
        self.next_page_domain = 'http://all.17k.com'
        self.home_spider = SpiderHelper.get_source_home_spider(self.name)
        last_crawl_time_str = RedisHelper.get_last_crawl_time(self.name)
        if not last_crawl_time_str:
            self.last_crawl_time = TimeHelper.time_2_str(frt='%Y-%m-%d') + ' 00:00:00'
        else:
            self.last_crawl_time = last_crawl_time_str
        next_crawl_time = TimeHelper.time_2_str(delta= -SpiderHelper.get_every_crawl_timedelta_mins(), delta_unit='minutes')
        RedisHelper.set_next_crawl_time(self.name, next_crawl_time)
        self.source_short_name = 'k17'

    def parse(self, response):
        is_continue = True
        hxs = Selector(response)
        book_nodes = hxs.xpath('//div[@class="alltable"]//tr[position() > 2]')
        if not book_nodes:
            self.log(message='%s spider get nothing in home page, current url is %s' % (self.name, response._get_url()), level=log.WARNING)
            is_continue = False
        else:
            for bn in book_nodes:
                u_time = bn.xpath('td[@class="td7"]/child::text()').extract()[0] + ":00"
                if u_time >= self.last_crawl_time:
                    source = bn.xpath('td[@class="td3"]//a/@href').extract()[0]  # first link
                    name = bn.xpath('td[@class="td3"]//a/child::text()').extract()[0]  # book name
                    author = bn.xpath('td[@class="td6"]/a/child::text()').extract()[0]

                    yield ItemHelper.gene_book_item(name, source, author, self.source_name, self.home_spider, self.source_short_name)
                else:
                    is_continue = False  # if the section publish time is less than last crawl time, can't continue.
                    break
        if is_continue:
            next_page_nodes = hxs.xpath('//a[@class="on"]/following-sibling::a')
            if next_page_nodes:
                next_page = self.next_page_domain + next_page_nodes[0].xpath('@href').extract()[0]
                yield Request(next_page, callback=self.parse)
            else:
                self.log(message='%s spider cannot get next page, current url is %s' % (self.name, response._get_url()), level=log.WARNING)
        else:
            self.log(message='%s spider sleep wait for next round.' % self.name, level=log.INFO)
            self.last_crawl_time = RedisHelper.get_last_crawl_time(self.name)
            next_crawl_time = TimeHelper.time_2_str(delta= -SpiderHelper.get_every_crawl_timedelta_mins(), delta_unit='minutes')
            RedisHelper.set_next_crawl_time(self.name, next_crawl_time)
            SpiderHelper.source_spider_sleep()
            yield Request(self.start_urls[0], callback=self.parse)


# System
import argparse
import io
import pickle

# Utils
from tqdm import tqdm, trange
import pandas as pd
import numpy as np
import ijson
import random
from dgl.data.utils import load_graphs

# ML Libraries
import torch
import pytorch_lightning as pl
from sklearn.preprocessing import MultiLabelBinarizer
# from sklearn.model_selection import train_test_split
from transformers import BertTokenizer
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping

# Modules
from bert_data_module import KenmeshDataModule
from bert_classifier_lightning import KenmeshClassifier

# Global Variables
BERT_MODEL_NAME = 'microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract-fulltext'
BATCH_SIZE = 16
MAX_LEN = 512
# LR = 2e-05

def split_train_test_val(texts, labels, mesh_masks, test_size = 0.1):
    """
    * This Custom function can take as much arguments as required which
    * train_test_split from sklearn doesn't support.
    * x_train,x_test,y_train,y_test = train_test_split(texts, yt, test_size=0.1, random_state=42,shuffle=True)
    """
    text_train, label_train, mesh_mask_train, text_test, label_test, mesh_mask_test = [], [], [], [], [], []
    total_len = len(texts)
    test_len = int(total_len * test_size)
    train_len = total_len - test_len

    nums = list(range(0, total_len))
    random.shuffle(nums)
    print(test_len, train_len)

    for i, num in enumerate(nums):
        if i < train_len:
            text_train.append(texts[num])
            label_train.append(labels[num])
            mesh_mask_train.append(mesh_masks[num])
        else:
            text_test.append(texts[num])
            label_test.append(labels[num])
            mesh_mask_test.append(mesh_masks[num])
        # if i == 0:
        #     print("First doc: ", type(label_train), type(mesh_mask_train))
        #     print(label_train[0], type(label_train[0]), np.count_nonzero(label_train[0]))

    print(f"Total number of documents: {total_len}, train set: {len(text_train)}, test set: {len(text_test)}")

    return text_train, label_train, mesh_mask_train, text_test, label_test, mesh_mask_test

def load_dataset(graph_file, device):
    print("Loading data...")

    text_train = pickle.load(open("text_train_full.pkl", 'rb'))
    label_train = pickle.load(open("label_train_full.pkl", 'rb'))
    mesh_mask_train = pickle.load(open("mesh_mask_train_full.pkl", 'rb'))

    text_test = pickle.load(open("text_test_full.pkl", 'rb'))
    label_test = pickle.load(open("label_test_full.pkl", 'rb'))
    mesh_mask_test = pickle.load(open("mesh_mask_test_full.pkl", 'rb'))

    text_val = pickle.load(open("text_val_full.pkl", 'rb'))
    label_val = pickle.load(open("label_val_full.pkl", 'rb'))
    mesh_mask_val = pickle.load(open("mesh_mask_val_full.pkl", 'rb'))

    print("Data Load Done...")

    n_classes = len(mesh_mask_train[0][0])

    print("n_classes: ", n_classes)

    print('Loading graph...')
    G = load_graphs(graph_file)[0][0]

    print("Batch size: ", BATCH_SIZE)
    steps_per_epoch = len(text_train)//BATCH_SIZE

    # Instantiate and set up the data_module
    Bert_tokenizer = BertTokenizer.from_pretrained(BERT_MODEL_NAME)

    kenmesh_data_Module = KenmeshDataModule(text_train, label_train, mesh_mask_train,\
         text_val, label_val, mesh_mask_val, text_test, label_test, mesh_mask_test, Bert_tokenizer,\
          device, G, G.ndata['feat'], BATCH_SIZE, MAX_LEN)
    kenmesh_data_Module.setup()

    print('prepare dataset and labels graph done!')
    # return len(meshIDs), mlb, train_dataset, valid_dataset, vectors, G
    # return text_train, label_train, mesh_mask_train, text_val, label_val, mesh_mask_val, text_test, label_test, mesh_mask_test
    return kenmesh_data_Module, steps_per_epoch, n_classes

def prepare_dataset(dataset_path, MeSH_id_pair_file, graph_file, device):
    """ Load Dataset and Preprocessing """

    print('Start loading training data')

    mesh_mask = []
    texts = []
    label_id = []
    pubmed_ids = []
    titles = []

    f = open(dataset_path, encoding="utf8")
    objects = ijson.items(f, 'articles.item')

    for i, obj in enumerate(tqdm(objects)):
        title = obj["title"]
        abstractText = obj["abstractText"]

        if len(title) < 1 or len(abstractText) < 1:
            continue

        # titles = title.split(" ")
        # abstractTexts = abstractText.split(" ")
        text = title + " " +abstractText
        pubmed_ids.append(obj["pmid"])
        mesh_mask.append(obj["meshMask"])
        texts.append(text)
        label_id.append(list(obj["meshID"].keys()))
        titles.append(title)
        # if i == 0:
        #     # print("Mesh Mask: ", len(mesh_mask[0]), len(mesh_mask[0][0]), mesh_mask[0].count(1), mesh_mask[0][0].count(1))
        #     print("Label: ", obj["meshID"])
        #     print("Label ID: ", len(label_id[0]), label_id[0])

    print('Finish loading training data')
    f.close()

    print('number of training data %d' % len(texts))

    print('load and prepare Mesh')

    mapping_id = {}
    with open(MeSH_id_pair_file, 'r') as f:
        for line in f:
            (key, value) = line.split('=')
            mapping_id[key] = value.strip()
    meshIDs = list(mapping_id.values())

    # print("meshIDs: ", meshIDs)

    n_classes = len(meshIDs)

    print('Total number of labels %d' % n_classes)

    # Encode the tags(labels) in a binary format in order to be used for training

    mlb = MultiLabelBinarizer(classes=meshIDs)
    mlb.fit(meshIDs)
    yt = mlb.fit_transform(label_id)

    # print()
    # print("title: ", titles[0])
    # print("pmid: ", pubmed_ids[0])
    # print("1: ", np.count_nonzero(yt[0])) # yt[0] -> [28415] -> count_of_nonzero == number of lebels for the doc
    # print("2: ", mlb.inverse_transform(yt[0].reshape(1,-1)))
    # print("3: ", mlb.classes_)

    # print("4: ", label_id[0])
    # print("5: ", mesh_mask[0][0].count(1)) # mesh_mask -> [1, 28415]

    # Prepare label features
    print('Loading graph...')
    G = load_graphs(graph_file)[0][0]
    # print('graph', G.ndata['feat'].shape) # [28415, 768]

    # Preparing training and test datasets
    print('prepare training and test sets')

    # First Split for Train and Test
    text_train, label_train, mesh_mask_train, text_test, label_test, mesh_mask_test = split_train_test_val(texts, yt, mesh_mask, test_size = 0.2)
    text_train, label_train, mesh_mask_train, text_val, label_val, mesh_mask_val = split_train_test_val(text_train, label_train, mesh_mask_train, test_size = 0.02)

    # print("text_test, label_test, mesh_mask_test: ", text_test, label_test, mesh_mask_test)
    # Saving test dataset to pickle for using in evaluation
    # pickle.dump(text_train, open("text_train_full.pkl", 'wb'))
    # pickle.dump(label_train, open("label_train_full.pkl", 'wb'))
    # pickle.dump(mesh_mask_train, open("mesh_mask_train_full.pkl", 'wb'))

    pickle.dump(text_test, open("text_test_full.pkl", 'wb'))
    pickle.dump(label_test, open("label_test_full.pkl", 'wb'))
    pickle.dump(mesh_mask_test, open("mesh_mask_test_full.pkl", 'wb'))

    # pickle.dump(text_val, open("text_val_full.pkl", 'wb'))
    # pickle.dump(label_val, open("label_val_full.pkl", 'wb'))
    # pickle.dump(mesh_mask_val, open("mesh_mask_val_full.pkl", 'wb'))

    print("-"*10, "pickle data dumpled", "-"*10)

    print("Batch size: ", BATCH_SIZE)
    steps_per_epoch = len(text_train)//BATCH_SIZE

    # Instantiate and set up the data_module
    Bert_tokenizer = BertTokenizer.from_pretrained(BERT_MODEL_NAME)

    kenmesh_data_Module = KenmeshDataModule(text_train, label_train, mesh_mask_train,\
         text_val, label_val, mesh_mask_val, text_test, label_test, mesh_mask_test, Bert_tokenizer,\
          device, G, G.ndata['feat'], BATCH_SIZE, MAX_LEN)
    kenmesh_data_Module.setup()

    print('prepare dataset and labels graph done!')
    # return len(meshIDs), mlb, train_dataset, valid_dataset, vectors, G
    # return text_train, label_train, mesh_mask_train, text_val, label_val, mesh_mask_val, text_test, label_test, mesh_mask_test
    return kenmesh_data_Module, steps_per_epoch, n_classes

def evaluation():
    pass
def main():
    #region All parser arguments

    parser = argparse.ArgumentParser()

    # data paths
    parser.add_argument('--dataset_path')
    parser.add_argument('----meSH_pair_path')
    parser.add_argument('--word2vec_path')
    parser.add_argument('--meSH_pair_path')
    parser.add_argument('--graph')
    parser.add_argument('--save-model-path')
    parser.add_argument('--model_name', default='Full', type=str)

    # environment
    parser.add_argument('--device', default='cuda', type=str)
    parser.add_argument('--nKernel', type=int, default=768) # Changed here for embed dimension
    parser.add_argument('--ksz', type=int, default=5)
    parser.add_argument('--hidden_gcn_size', type=int, default=768) # Changed here for embed dimension
    parser.add_argument('--embedding_dim', type=int, default=768) # Changed here for embed dimension
    parser.add_argument('--dropout', type=float, default=0.2)
    parser.add_argument('--atten_dropout', type=float, default=0.5)

    # hyper params
    # lr -> 0.001, 0.0001, 0.0003, 0.0005
    parser.add_argument('--num_epochs', type=int, default=10)
    parser.add_argument('--batch_sz', type=int, default=16)
    parser.add_argument('--num_workers', type=int, default=8)
    parser.add_argument('--lr', type=float, default=1e-4)
    parser.add_argument('--momentum', type=float, default=0.9)
    parser.add_argument('--weight_decay', type=float, default=0)
    parser.add_argument('--scheduler_step_sz', type=int, default=2)
    parser.add_argument('--lr_gamma', type=float, default=0.9)

    args = parser.parse_args()

    #endregion

    # GPU Device assignmentt
    torch.backends.cudnn.benchmark = True
    n_gpu = torch.cuda.device_count()  # check if it is multiple gpu
    print('{} gpu is avaliable'.format(n_gpu))
    torch.set_float32_matmul_precision('medium')
    device = torch.device(args.device if torch.cuda.is_available() else "cpu")
    print('Device:{}'.format(device))

    global BATCH_SIZE
    BATCH_SIZE = args.batch_sz
    num_epochs = args.num_epochs
    # Get dataset and label graph & Load pre-trained embeddings
    kenmesh_data_Module, steps_per_epoch, n_classes= prepare_dataset(args.dataset_path, args.meSH_pair_path, args.graph, device)
    # kenmesh_data_Module, steps_per_epoch, n_classes= load_dataset(args.graph, device)

    # Inittialising Bert Classifier Model
    model = KenmeshClassifier(num_labels=n_classes, ksz=args.ksz, steps_per_epoch=steps_per_epoch, n_epochs=num_epochs, lr=args.lr)

    model.to(device)

    #Initialize Pytorch Lightning callback for Model checkpointing

    # saves a file like: input/QTag-epoch=02-val_loss=0.32.ckpt
    checkpoint_callback = ModelCheckpoint(
        monitor='val_loss',# monitored quantity
        filename='QTag-{epoch:02d}-{val_loss:.2f}',
        save_top_k=3, #  save the top 3 models
        mode='min', # mode of the monitored quantity  for optimization
    )

    # Instantiate the Model Trainer
    trainer = pl.Trainer(max_epochs = num_epochs , devices = 1, accelerator='gpu', callbacks=[EarlyStopping(monitor="val_loss", mode="min", patience=3), checkpoint_callback])

    # trainer with more configurations:
    # trainer = pl.Trainer(max_epochs = N_EPOCHS , precision=32, auto_scale_batch_size='binsearch', devices = 1, accelerator='gpu', profiler="simple", callbacks=[EarlyStopping(monitor="val_loss", mode="min"), checkpoint_callback])

    # print("Best checkpoint path: ", checkpoint_callback.best_model_path)
    # pickle.dump(checkpoint_callback.best_model_path, open("checkpoint.pkl", "wb"))

    # For optimal learning rate:
    # lr_finder = trainer.tuner.lr_find(model,
    #                     min_lr=0.0005,
    #                     max_lr=0.005,
    #                     mode='linear')
    # model.learning_rate = lr_finder.suggestion()
    # trainer.tune(model) # for optimal batch size

    # Train the Classifier Model
    print("Training...")
    trainer.fit(model, kenmesh_data_Module)

    torch.save(model.state_dict(), args.save_model_path)

    # Evaluate the model performance on the test dataset
    print("Evaluation: ")
    print(trainer.test(model,datamodule=kenmesh_data_Module))

if __name__ == "__main__":
    main()


from peephole.util import IdleObject
import logging
from gettext import gettext as _
import gobject

# yes, I am polling instead of actually using asyncronous I/O.
# PyUSB doesn't support asynchronous operation, even though libusb
# has fairly comprehensive asynchronous support.
class EventListener(gobject.GObject):

    __gsignals__ = {
        'buttonPressed' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                           (gobject.TYPE_INT,))}

    def __init__(self, lcd):
        gobject.GObject.__init__(self)
        self.lcd = lcd
        self.please_stop = False
        self.timer = None

    def start(self):
        # register glib timeout
        self.timer = gobject.timeout_add(50, self.check_button_press)

    def check_button_press(self):
        button = self.lcd.get_event_nonblock()
        if button is not None:
            logging.debug("Button was: %s" % button)
            self.emit('buttonPressed', button)
        return True

#     def run(self):
#         '''This is what is run in the Thread when it is started.'''
#         logging.debug(_("PicoLCD button listener thread now running."))
#         while True:
#             if self.please_stop:
#                 return
#             button = self.lcd.get_event(self.check_if_time_to_stop)
#             if button is not None:
#                 logging.debug("Button was: %s" % button)
#                 self.emit('buttonPressed', button)

    def shutdown(self):
        # unregister glib timeout
        if self.timer is not None:
            gobject.source_remove(self.timer)


# -*- coding: utf-8 -*-
# @Time    : 07/11/2021 19:37
# @Author  : Ming

import pickle
import json
import numpy as np
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--dataset', type=str, default='dunnhumby', help='Dataset')
    parser.add_argument('--avg_type', type=str, default='mean', help='x')
    parser.add_argument('--aug_pos', type=int, default=1, help='x')
    parser.add_argument('--adj_neg', type=int, default=1, help='x')
    parser.add_argument('--cfm', type=int, default=1, help='x')
    parser.add_argument('--freq', type=int, default=1, help='x')
    args = parser.parse_args()
    dataset = args.dataset
    candidate_filter = args.cfm
    freq_signal =args.freq
    aug_pos=args.aug_pos
    adjust_neg=args.adj_neg
    val_can_num = 50
    avg_type = args.avg_type

    def get_performance_dict(results_data):
        all_gather_dict = dict()
        # for can_num in [20, 50, 100, 200, 500]:
        for can_num in [20, 50, 100, 200, 500]:
            recall = []
            ndcg = []
            ihr = []
            ihn = []
            gather_dict = dict()
            for foldk in range(5):
                result = results_data[str(foldk)][str(can_num)]
                recall.append(result['Recall'])
                ndcg.append(result['NDCG'])
                ihr.append(result['HitRatio'])
                ihn.append(result['Correct'])
            gather_dict['Recall'] = np.mean(recall)
            gather_dict['NDCG'] = np.mean(ndcg)
            gather_dict['IHR'] = np.mean(ihr)
            gather_dict['IHN'] = np.mean(ihn)
            all_gather_dict[can_num] = gather_dict
        return all_gather_dict

    print(dataset)
    save_folder = f"test_results_{avg_type}/{dataset}/cand{candidate_filter}_freq{freq_signal}_aug{aug_pos}_adjust{adjust_neg}/"

    val_best_performance = 0
    for epoch in range(7):
        val_results_file = f'test_results_{avg_type}/{dataset}/cand{candidate_filter}_freq{freq_signal}_aug{aug_pos}_adjust{adjust_neg}/val_epoch_{epoch}.json'
        with open(val_results_file, 'r') as f:
            val_result_data = json.load(f)
        val_performance_dict = get_performance_dict(val_result_data)

        test_results_file = f'test_results_{avg_type}/{dataset}/cand{candidate_filter}_freq{freq_signal}_aug{aug_pos}_adjust{adjust_neg}/test_epoch_{epoch}.json'
        with open(test_results_file, 'r') as f:
            test_result_data = json.load(f)
        test_performance_dict = get_performance_dict(test_result_data)
        if val_performance_dict[val_can_num]['Recall'] > val_best_performance:
            val_best_performance = val_performance_dict[val_can_num]['Recall']
            print('Epoch:{}'.format(epoch))
            print(test_performance_dict)


from keras.applications import ResNet50
from keras.layers import (
    Activation,
    BatchNormalization,
    Conv2D,
    Conv2DTranspose,
    UpSampling2D,
    add,
)
from tensorflow import keras

def Encoder():
    """
    Encoder returns a singular model that is setup to take in an image
    and then a decoder undoes it.
    """
    input_shape = (256, 256, 3)
    inputs = keras.Input(shape=input_shape)

    outputs = ResNet50(
        include_top=False,
        weights="imagenet",
        input_shape=input_shape
    )(inputs)

    model = keras.Model(inputs=inputs, outputs=outputs, name="encoder")
    return model

def Decoder():
    """
    This takes the output of the Encoder and attempts to recreate the
    input.
    """
    # The output shape of the ResNet50 top layers is(batch, 8, 8, 2048)
    input_shape = (8, 8, 2048)
    inputs = keras.Input(shape=input_shape)

    net = Conv2D(1024, 3, padding="same")(inputs)
    net = BatchNormalization()(net)
    net = Activation("leaky_relu")(net)

    skip_memory = net

    # Let's build up and outwards
    for filters in [512, 256, 128, 64, 32]:
        net = Conv2DTranspose(filters, 3, padding="same",
                              activation="leaky_relu")(net)
        net = BatchNormalization()(net)
        net = Conv2DTranspose(filters, 3, padding="same",
                              activation="leaky_relu")(net)
        net = BatchNormalization()(net)
        net = UpSampling2D(2)(net)

        # Handle skip layer
        skip_memory = UpSampling2D(2)(skip_memory)
        skip_memory = Conv2D(filters, 1, padding="same")(skip_memory)
        net = add([net, skip_memory])
        skip_memory = net

    # 3 filters for 3 channels of our output
    outputs = Conv2DTranspose(3, 3, padding="same", activation="tanh")(net)

    model = keras.Model(inputs=inputs, outputs=outputs, name="decoder")

    return model

def EncoderDecoder(encoder, decoder):
    encoder_input = keras.Input((256, 256, 3), name="encoder input")
    encoder_output = encoder(encoder_input)
    decoder_output = decoder(encoder_output)
    return keras.Model(encoder_input, decoder_output, name="encoder/decoder")


import numpy as np
from dataclasses import dataclass

@dataclass
class Wave:
    frequency: int
    num_samples: int
    sampling_rate: int
    amplitude: float

    def create_sine(self) -> np.array:
        sine_wave = np.zeros((self.num_samples,), dtype=float)
        for x in range(self.num_samples):
            sine_wave[x] = np.sin(2 * np.pi * self.frequency * x/self.sampling_rate)
        return sine_wave

    def create_fm_sine(self, freq_fm_mod) -> np.array:
        fm_sine_wave = np.zeros((self.num_samples,), dtype=float)
        modulator_index = 0
        if freq_fm_mod != 0.0:
            modulator_index = self.frequency / freq_fm_mod
        shift = lambda t, fmod, fs : np.cos(2.0 * np.pi * t * fmod / fs)
        for x in range(self.num_samples):
            fm_sine_wave[x] = np.sin(2 * np.pi * self.frequency * x/self.sampling_rate + modulator_index* shift(x,freq_fm_mod, self.sampling_rate))
        return fm_sine_wave

def limit_signal(signal: np.array, max: float = 1.0, min: float = -1.0) -> np.array:
    limit_signal = np.zeros((signal.size,), dtype=float)
    for idx in range(0,signal.size):
        sample = signal[idx]
        if sample > max:
            sample = max
        if sample < min:
            sample = min
        limit_signal[idx] = sample
    return limit_signal

def generate_white_noise(nsamples: int) -> np.array:
    mean = 0.0
    scale = 1.0
    noise_signal = np.zeros((nsamples,), dtype=float)
    for idx in range(0,nsamples):
        noise_signal[idx] = np.random.normal(mean,scale)
    return noise_signal

def mix_signals(signals: [np.array]) -> np.array:
    num_signals = len(signals)
    num_samples = signals[0].size
    mixed_signal = np.zeros((num_samples,), dtype=float)

    for sample_idx in range(0,num_samples):
        sum_sample: float = 0.0
        mul_sample: float = 1.0
        for sign_idx in range(0,num_signals):
            sum_sample += signals[sign_idx][sample_idx]
            mul_sample *= signals[sign_idx][sample_idx]
        mixed_signal[sample_idx] = sum_sample - mul_sample * num_signals
    return mixed_signal


from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('headless')

try:
    driver = webdriver.Remote(
        command_executor='http://chrome:4444/wd/hub',
        options=chrome_options
    )
    driver.get("http://www.baidu.com")
    print(driver.title)
    driver.quit()
except Exception as e:
    print("An error occurred: ", e)


import time
import requests
import datetime
from multiprocessing.pool import ThreadPool
from .config import n_threads, spot_region_map

def call_end_point(url):
    return requests.get(url).json()['Items']

multi_result = {}
def pull_price(region_name, sizes, start, end, now_time=str(datetime.datetime.now()), is_windows_instance=False):
    is_windows_instance = is_windows_instance

    data = []
    end_point = "https://prices.azure.com/api/retail/prices?$filter="
    params = ''
    for count, instance_size in enumerate(sizes):
        params += "skuName eq '" + str(instance_size).replace('Standard_', '').replace('_', ' ') + " Spot' or "
        if (count+1)%19 == 0:
            spot_end_point = end_point + params[:-3] + "and armRegionName eq '" + str(region_name) + "'"
            data += call_end_point(spot_end_point)
            params = ''

    if params:
        spot_end_point = end_point + params[:-3] + "and armRegionName eq '" + str(region_name) + "'"
        data += call_end_point(spot_end_point)

    params = ''
    for count, instance_size in enumerate(sizes):
        params += "skuName eq '" + str(instance_size).replace('Standard_', '').replace('_', ' ') + "' or "
        if (count+1)%19 == 0:
            regular_end_point = end_point + params[:-3] + "and armRegionName eq '" + str(region_name) + "'"
            data += call_end_point(regular_end_point)
            params = ''

    if params:
        regular_end_point = end_point + params[:-3] + "and armRegionName eq '" + str(region_name) + "'"
        data += call_end_point(regular_end_point)

    if region_name not in multi_result:
        multi_result [region_name] = {}

    for each_instance in data:
        instance_size = each_instance['armSkuName']

        if instance_size not in multi_result[region_name]:
            multi_result[region_name][instance_size] = [now_time, region_name, instance_size, float('-inf'), float('-inf'), float('-inf'), float('-inf')]

        if not is_windows_instance and 'windows' not in each_instance['productName'].lower() and \
            'spot' in each_instance['meterName'].lower() and each_instance['type'] == 'Consumption':
            multi_result[region_name][instance_size][3] = each_instance['unitPrice']

        if not is_windows_instance and 'windows' not in each_instance['productName'].lower() and \
            'spot' not in each_instance['meterName'].lower() and each_instance['type'] == 'Consumption':
            multi_result[region_name][instance_size][4] = each_instance['unitPrice']

        if not is_windows_instance and 'windows' not in each_instance['productName'].lower() and \
            each_instance['type'] == 'Reservation' and each_instance['reservationTerm'] == '1 Year':
            multi_result[region_name][instance_size][5] = each_instance['unitPrice']/(365*24)

        if not is_windows_instance and 'windows' not in each_instance['productName'].lower() and \
            each_instance['type'] == 'Reservation' and each_instance['reservationTerm'] == '3 Years':
            multi_result[region_name][instance_size][6] = each_instance['unitPrice']/(365*24*3)

def process_savings(data):
    per_saving_pay_as_you_go = float('-inf')
    if data[4] and data[3]:
        per_saving_pay_as_you_go = (data[4] - data[3])/data[4]*100

    per_saving_1y_reserved = float('-inf')
    if data[5] and data[3]:
        per_saving_1y_reserved = (data[5] - data[3])/data[5]*100

    per_saving_3y_reserved = float('-inf')
    if data[6] and data[3]:
        per_saving_3y_reserved = (data[6] - data[3])/data[6]*100

    if data[3] > 0 and data[4] > 0:
        return {
            'time': data[0],
            'region': data[1],
            'size': data[2],
            'api_price': data[3],
            'cli_price': float('-inf'),
            'pay_as_you_go_price': data[4],
            '1_year_reserved_price': data[5],
            '3_year_reserved_price': data[6],
            '%_saving_pay_as_you_go': per_saving_pay_as_you_go,
            '%_saving_1y_reserved': per_saving_1y_reserved,
            '%_saving_3y_reserved': per_saving_3y_reserved
        }

def pull_multiple(now_time, is_windows_instances=False):
    global multi_result
    multi_result = {}

    p = ThreadPool(n_threads)

    return_data = []
    count = 0
    for region in spot_region_map.keys():
        price = p.apply_async(pull_price, args=(region, spot_region_map[region], now_time, is_windows_instances, ))

    p.close()
    p.join()

    for region  in multi_result.keys():
        for size in multi_result[region].keys():
            result = process_savings(multi_result[region][size])
            if result:
                return_data.append(result)

    return return_data


def JSONEncoder(messages):
    ''' Serialize collection in each message '''
    msg_list = []
    for message in messages:
        new_dict = dict(
            tarball=message.tarball,
            md5sum=message.md5sum,
            sha256sum=message.sha256sum,
            pkg_name=message.pkg_name,
            filename=message.filename,
            tar_sum=message.tar_sum,
            sha1sum=message.sha1sum,
        )
        msg_list.append(new_dict)
    return msg_list

def to_dict(messages):
    msg_dict = {}
    for message in messages:
        msg_dict[message.sha256sum] = message.filename

    return msg_dict


def policy_eval(policy, env, discount_factor=1.0, theta=0.00001):
    """
    Evaluate a policy given an environment and a full description of the environment's dynamics.

    Args:
        policy: [S, A] shaped matrix representing the policy.
        env: OpenAI env. env.P represents the transition probabilities of the environment.
            env.P[s][a] is a list of transition tuples (prob, next_state, reward, done).
        theta: We stop evaluation once our value function change is less than theta for all states.
        discount_factor: gamma discount factor.

    Returns:
        Vector of length env.nS representing the value function.
    """
    # Start with a random (all 0) value function
    import numpy as np
    V = np.zeros(env.nS)
    while True:
        delta = 0.0
        for s in range(env.nS):
            v = 0
            for a, prob_a in enumerate(policy[s]):
                for prob_t, next_state, reward, done in env.P[s][a]:
                    v += prob_a * prob_t * (reward + discount_factor * V[next_state])
            delta = max(delta, abs(v - V[s]))
            V[s] = v
        if delta < theta:
            break
    return np.array(V)


import os

try:
    from qgis.PyQt import uic
    from qgis.PyQt import QtWidgets
except:
    from PyQt5 import uic, QtWidgets

# This loads your .ui file so that PyQt can populate your plugin with the elements from Qt Designer
FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), r'ui\config_dialog.ui'))

class ConfigDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, controller, parent=None):
        """Constructor."""
        super(ConfigDialog, self).__init__(parent)

        self.setupUi(self)

        self.setWindowTitle(f"Configurações - {self.windowTitle()}")

        self.controller = controller


# NOTES:
# 1 is left, 0 is right
# 1 is back, 0 is front
# 1 is IR sees black or any sufficiently dark color,
# 0 is IR sees white or any sufficiently light color

# Black magic don't touch
pins.set_pull(DigitalPin.P20, PinPullMode.PULL_UP)

# MODIFIES: state
def move():
    global active, state
    global direction, speed
    global curr_time, move_elapsed, adjust_elapsed

    state = 0

    set_gb(direction, speed, 1 - direction, speed)

    '''
    else:
        move_elapsed = 0

        last_move_time = control.millis()

        while move_elapsed <= time:
            set_gb(direction, speed, 1 - direction, speed)

            move_elapsed += curr_time - last_move_time

            if (adjust_elapsed != 0):
                move_elapsed -= adjust_elapsed
                adjust_elapsed = 0

        stop()
    '''

# MODIFIES: state
def turn():
    global active, state, count
    global turn_direction, turn_speed
    global ir1_read, ir2_read

    state = 1

    ir1_read_last = ir1_read
    ir2_read_last = ir2_read

    counter1 = 0
    counter2 = 0

    counter = 0

    while counter != count :
        basic.pause(40)

        stop()

        # Don't delete this
        basic.show_number(counter1 + counter2)

        if (counter1 + counter2 >= 4 and counter >= 10):
            stop()
            return

        if (ir1_read != ir1_read_last):
            ir1_read_last = ir1_read

            if (counter1 == 0):
                counter1 = 1

            elif (counter1 == 1):
                counter1 = 2

        if (ir2_read != ir2_read_last):
            ir2_read_last = ir2_read

            if (counter2 == 0):
                counter2 = 1

            elif (counter2 == 1):
                counter2 = 2

        set_gb(turn_direction, turn_speed, turn_direction, turn_speed)

        counter += 1

    stop()

# MODIFIES: state
def stop():
    global active, state

    basic.pause(10)

    state = 2

    set_gb(0, 0, 0, 0)

# MODIFIES: turn_direction
def adjust():
    global ir1_read, ir2_read
    global adjust_ac
    global intersection_seen
    global active, state
    global adjust_speed
    global last_adjust_time, curr_time, adjust_elapsed

    if active != 1:
        return

    if adjust_ac != 1:
        return

    if state != 0:
        return

    if (check_inter()):
        intersection_seen = 1
        return

    elif (check_angle()):
        stop()

        # last_adjust_time = control.millis()

        if (ir1_read == 0 and ir2_read == 1):
            set_gb(0, adjust_speed, 0, adjust_speed)
            state = 0

        if (ir1_read == 1 and ir2_read == 0):
            set_gb(1, adjust_speed, 1, adjust_speed)
            state = 0

        basic.pause(100)

        move()

        # adjust_elapsed += curr_time - last_adjust_time

    else:
        move()

# For use with adjusting
def check_angle():
    global ir1_read, ir2_read

    # Time for sensors to update
    basic.pause(10)

    if (ir1_read == 0 and ir2_read == 0):
        return 0

    elif (ir1_read == 0 or ir2_read == 0):
        return 1

    return 0

# MODIFIES: ir1_read, ir2_read, ir3_read, ir4_read, force_read
def read_pins():
    global ir1_read, ir2_read, ir3_read, ir4_read, force_read

    ir1_read = pins.digital_read_pin(ir1)
    ir2_read = pins.digital_read_pin(ir2)
    ir3_read = pins.digital_read_pin(ir3)
    ir4_read = pins.digital_read_pin(ir4)

    force_read = pins.digital_read_pin(force)

# MODIFIES: curr_time
def update_time():
    global curr_time, last_time

    curr_time = control.millis()

# Utility function to set both gearboxes at the same time
def set_gb(dir1, spd1, dir2, spd2):
    sensors.dd_mmotor(gb1_direction, dir1, gb1_speed, spd1)
    sensors.dd_mmotor(gb2_direction, dir2, gb2_speed, spd2)

# Check if its at intersection
def check_inter():
    global ir1_read, ir2_read

    if (ir1_read == 1 and ir2_read == 1):
        music.play_tone(Note.C, 50)
        return True

    return False

def check_food():
    global ir3_read, ir4_read

    if (ir3_read == 0):
        return 1

    elif (ir4_read == 0):
        return 1

    else:
        return 0

# --- PINS ---
force = DigitalPin.P20

# 2 follow line sensors
ir1 = DigitalPin.P1
ir2 = DigitalPin.P8

# Front sensor
ir3 = DigitalPin.P12
ir5 = DigitalPin.P0

# Back sensor
ir4 = DigitalPin.P2
ir6 = DigitalPin.P0

# Right gearbox
gb1_speed = AnalogPin.P14
gb1_direction = AnalogPin.P13

# Left gearbox
gb2_speed = AnalogPin.P16
gb2_direction = AnalogPin.P15
# ---------

# Pin values
force_read = 0
ir1_read = 0
ir2_read = 0
ir3_read = 0
ir4_read = 0
ir5_read = 0
ir6_read = 0

# Directions for turning and moving (0 is right, 1 is left)
direction = 0
turn_direction = 0

# Speeds
speed = 78
turn_speed = 220
adjust_speed = 110

# Flags (0 -> false, 1 -> true)
active = 0
adjust_ac = 1
intersection_seen = 0

# State (0 -> moving, 1 -> turning, 2 -> still, 3 -> special)
state = 0

# Intersection count
intersection_count = 0

# Current and last time for counting time elapsed
curr_time = control.millis()
last_time = control.millis()

# Time it took for robot to finish one move or adjust operation
move_elapsed = 0
adjust_elapsed = 0

last_move_time = 0
last_adjust_time = 0

count = 0

# Run these functions in the background
basic.forever(read_pins)
# basic.forever(update_time)
basic.forever(adjust)

def reset_var():
    global adjust_ac, intersection_seen

    adjust_ac = 1
    intersection_seen = 0

def start():
    global force_read
    global active

    # Once the button is pressed activate
    if (force_read == 0 and active == 0):
        active = 1
        basic.pause(500)
        first()

    elif (force_read == 0 and active == 1):
        # Reset
        control.reset()

def main():
    global ir1_read, ir2_read, force_read
    global active, state
    global intersection_count

    basic.show_number(state)

    first()

basic.forever(start)

# Algorithms for each section
def first():
    global adjust_ac, intersection_seen, count
    global direction, turn_direction
    global intersection_count

    adjust_ac = 0

    direction = 0
    move()

    basic.pause(500)

    basic.show_number(9)

    adjust_ac = 1

    direction = 0
    move()

    intersection_seen = 0

    while True:
        move()
        basic.pause(20)
        if (check_inter() or intersection_seen):
            intersection_seen = 0

            adjust_ac = 0

            # Move forward a little
            direction = 0
            move()
            basic.pause(1200)

            stop()

            # Left food
            count = 10
            turn_direction = 1
            turn()

            adjust_ac = 1

            direction = 0
            move()

            basic.pause(600)

            while not check_food():
                basic.pause(10)

            stop()

            adjust_ac = 0

            direction = 0
            move()
            basic.pause(1000)

            stop()

            # Right food

            direction = 1
            move()

            basic.pause(1000)

            while not check_food():
                basic.pause(10)

            stop()

            direction = 1
            move()
            basic.pause(900)

            stop()

            direction = 0
            move()
            basic.pause(700)

            adjust_ac = 0

            direction = 0
            move()
            basic.pause(1300)

            stop()

            count = 11

            turn_direction = 0
            turn()

            intersection_count += 1

            break

    second()

def second():
    global adjust_ac, intersection_seen
    global direction, turn_direction
    global intersection_count, count

    reset_var()

    basic.show_number(8)

    stop()

    direction = 0
    move()

    while True:
        move()
        basic.pause(20)
        if (check_inter() or intersection_seen):
            intersection_seen = 0

            adjust_ac = 0

            direction = 0
            move()
            basic.pause(1400)

            stop()
            count = 12
            turn_direction = 1
            turn()

            adjust_ac = 1

            direction = 0
            move()

            while not check_food():
                basic.pause(20)

            adjust_ac = 0

            direction = 0
            move()
            basic.pause(2000)

            stop()

            direction = 1
            move()

            basic.pause(3000)

            direction = 0
            move()
            basic.pause(1300)

            stop()

            turn_direction = 0
            turn()

            intersection_count += 1

    third()

def third():
    global adjust_ac, intersection_seen
    global direction, turn_direction
    global intersection_count, count

    reset_var()

    basic.show_number(7)

    stop()

    direction = 0
    move()

    while True:
        move()
        basic.pause(20)
        if (check_inter() or intersection_seen):
            intersection_seen = 0

            adjust_ac = 0

            direction = 0
            move()
            basic.pause(1600)

            stop()

            count = 12

            turn_direction = 1
            turn()

            adjust_ac = 1

            direction = 0
            move()

            while not check_food():
                basic.pause(20)

            adjust_ac = 0

            direction = 0
            move()
            basic.pause(1500)

            stop()

            direction = 1
            move()
            basic.pause(3000)

            direction = 0
            move()
            basic.pause(1500)

            stop()

            turn_direction = 0
            turn()

            intersection_count += 1

    fourth()

def fourth():
    global adjust_ac, intersection_seen
    global direction, turn_direction
    global intersection_count, count

    reset_var()

    basic.show_number(6)

    stop()

    direction = 1
    move()
    basic.pause(1000)

    stop()

    direction = 0
    move()

    while True:
        move()
        basic.pause(20)
        if (check_inter() or intersection_seen):
            stop()

            direction = 0
            move()
            basic.pause(1500)

            turn_direction = 1
            turn()

            stop()

            direction = 0
            move()

            while not check_food():
                basic.pause(20)

            direction = 0
            move()
            basic.pause(1500)

            stop()

            direction = 1
            move()

            while not check_food():
                basic.pause(10)

            basic.pause(1500)
            stop()

            direction = 0
            move()

            while not (check_inter() or intersection_seen):
                basic.pause(20)

            basic.pause(1400)

            stop()

            turn_direction = 0
            turn()

    last()

def last():
    global adjust_ac, intersection_seen
    global direction, turn_direction
    global intersection_count, count

    reset_var()

    basic.show_number(5)

    stop()

    direction = 0
    move()

    while True:
        move()
        basic.pause(20)
        if check_inter() or intersection_seen:
            stop()

            direction = 0
            move()
            basic.pause(1500)

            turn_direction = 1
            turn()

            stop()

            direction = 0
            move()

            intersection_seen = 0
            while not (check_inter() or intersection_seen):
                basic.pause(20)

            basic.pause(1500)

            stop()

    active = 0
    return


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:

        node = head; count = 0
        while node.next != None:
            node = node.next
            count += 1

        node = head; total = 0
        while node.next != None:

            if node.val != 0: # don't add zero digits
                total += pow(2, count)  # 2 ^ count
            node = node.next
            count -= 1

        # while node.next == None:  # final
        if node.val != 0: # don't add zero digits
            total += pow(2, count)  # 2 ^ count

        return total


import sys
import asyncio
import logging
import argparse
import socket
import signal

from . import IRC, Server

logging.basicConfig(
    level=logging.DEBUG,
    format='[%(asctime)s] %(name)s - %(levelname)s - %(message)s',
)

log = logging.getLogger("ircd.main")

CLIENT_PORT = "9999"
CLIENT_LISTEN_ADDRESS = "0.0.0.0:" + CLIENT_PORT

LINK_PORT = "6666"
LINK_LISTEN_ADDRESS = "0.0.0.0:" + LINK_PORT

def parse_address(s):
    parts = s.split(":")
    host, port = parts
    return host, int(port)

async def resolve_address(host, port):
    addresses = await asyncio.get_event_loop().getaddrinfo(host, port)
    return addresses[0][-1][0] if addresses else host

async def main(args):
    addr, port = args.listen
    irc = IRC(args.host)
    server = Server(irc)

    async def _shutdown():
        log.info("shutdown")
        await server.shutdown()

    for sig in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM):
        asyncio.get_running_loop().add_signal_handler(sig, lambda: asyncio.create_task(_shutdown()))

    await server.run(
        client_listen_addr=args.listen[0],
        client_listen_port=args.listen[1],
        link_listen_addr=args.link[0],
        link_listen_port=args.link[1],
        peer_addr=await resolve_address(args.peer[0], args.peer[1]) if args.peer else None,
        peer_port=args.peer[1] if args.peer else None,
        ws_addr=args.ws[0] if args.ws else None,
        ws_port=args.ws[1] if args.ws else None,
    )

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="irc server")
    parser.add_argument("--host", help="host name", default=socket.gethostname())
    parser.add_argument("--listen", help="listen address", type=parse_address, default=CLIENT_LISTEN_ADDRESS)
    parser.add_argument("--link", help="link address", type=parse_address, default=LINK_LISTEN_ADDRESS)
    parser.add_argument("--peer", help="peer address", type=parse_address)
    parser.add_argument("--ws", help="websocket listen address", type=parse_address)
    parser.add_argument("--verbose", help="verbose mode", action="store_true")
    args = parser.parse_args(sys.argv[1:])

    try:
        asyncio.run(main(args), debug=args.verbose)
    except asyncio.CancelledError:
        pass


import unittest

# navigate to the Features folder
import sys
sys.path.append(sys.path[0]+'/../Features')

# UNIVERSAL IMPORT
from universal_imports import *

# import other features
import helper

# Import testing specific libraries
from pandas.testing import assert_frame_equal

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

class test_get_study_sets(unittest.TestCase):

    def setUp(self):

        # test user
        self.user = "sample_user_1"

        # the expected sets to be returned from test user
        self.expected_sets = ["Food", "French Elementary", "Simple English", "Weather"]

        # sort the list in the default order of sort() function
        self.expected_sets.sort()

    def test_get_study_sets(self):

        # get the output from the function we're testing
        found_sets = helper.get_study_sets(self.user)

        # sort the list in the default order of sort() function
        found_sets.sort()

        # check if the produced dataframe and the processed dataframe are the same
        self.assertEqual(found_sets, self.expected_sets)

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

if __name__ == '__main__':
    unittest.main()


import asyncio
import hashlib
import hmac
import json
from unittest import TestCase
from unittest.mock import MagicMock

from typing_extensions import Awaitable

from hummingbot.connector.exchange.woo_x.woo_x_auth import WooXAuth
from hummingbot.core.web_assistant.connections.data_types import RESTMethod, RESTRequest

class WooXAuthTests(TestCase):
    def setUp(self) -> None:
        self._api_key = "testApiKey"
        self._secret = "testSecret"

    def async_run_with_timeout(self, coroutine: Awaitable, timeout: float = 1):
        ret = asyncio.get_event_loop().run_until_complete(asyncio.wait_for(coroutine, timeout))

        return ret

    def test_rest_authenticate(self):
        mock_time_provider = MagicMock()

        mock_time_provider.time.return_value = 1686452155.0

        data = {
            "symbol": "SPOT_BTC_USDT",
            "order_type": "LIMIT",
            "side": "BUY",
            "order_price": 20000,
            "order_quantity": 1,
        }

        timestamp = str(int(mock_time_provider.time.return_value * 1e3))

        auth = WooXAuth(api_key=self._api_key, secret_key=self._secret, time_provider=mock_time_provider)

        request = RESTRequest(method=RESTMethod.POST, data=json.dumps(data), is_auth_required=True)

        configured_request = self.async_run_with_timeout(auth.rest_authenticate(request))

        signable = '&'.join([f"{key}={value}" for key, value in sorted(data.items())]) + f"|{timestamp}"

        signature = (
            hmac.new(
                bytes(self._secret, "utf-8"),
                bytes(signable, "utf-8"),
                hashlib.sha256
            ).hexdigest().upper()
        )

        headers = {
            'x-api-key': self._api_key,
            'x-api-signature': signature,
            'x-api-timestamp': timestamp,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cache-Control': 'no-cache',
        }

        self.assertEqual(timestamp, configured_request.headers['x-api-timestamp'])

        self.assertEqual(signature, configured_request.headers['x-api-signature'])

        self.assertEqual(headers, configured_request.headers)


from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.decorators import permission_required
from .forms import CreatePollForm
from .models import Poll
from django.contrib.auth.admin import User

def index(request):
    polls = Poll.objects.all()
    context = {
        'polls' : polls
    }
    return render(request, 'polls/index.html', context)

@permission_required('polls.poll_can_create', '/login')
def create(request):
    if request.method == 'POST':
        form = CreatePollForm(request.POST)
        if form.is_valid():
            poll = form.save(commit=False);
            current_user = request.user

            poll.author = current_user
            poll.save()
            return redirect('polls:index')
    else:
        form = CreatePollForm()
    context = {
        'form' : form
    }
    return render(request, 'polls/create.html', context)

def vote(request, id):
    poll = Poll.objects.get(pk=id)

    if request.method == 'POST':
        selected_option = request.POST['poll']
        current_user = request.user

        poll.voter.add(current_user)
        poll.save()
        if selected_option == 'option1':
            poll.option_one_count += 1
        elif selected_option == 'option2':
            poll.option_two_count += 1
        elif selected_option == 'option3':
            poll.option_three_count += 1
        else:
            return HttpResponse(400, 'Invalid form')

        poll.save()

        return redirect('polls:index')

    context = {
        'poll' : poll
    }
    return render(request, 'polls/vote.html', context)

def results(request, id):
    poll = Poll.objects.get(pk=id)
    context = {
        'poll' : poll
    }
    return render(request, 'polls/results.html', context)


# 2070. 큰 놈, 작은 놈, 같은 놈
# 난이도 : D1

T = int(input())

for test_case in range(1, T+1):
    a, b = map(int, input().split())

    if a > b:
        answer = ">"
    elif a == b:
        answer = "="
    else:
        answer = "<"

    print("#{} {}".format(test_case, answer))

SWEA/D1/2070. 큰 놈， 작은 놈， 같은 놈/큰 놈， 작은 놈， 같은 놈.py

큰 놈， 작은 놈， 같은 놈.py


import sqlite3 as lite
import json
import sys
from secrets import WHITELISTED_USERS
import subreddit_notifications

def connect():
    db = lite.connect('users.db')
    cur = db.cursor()
    cur.execute(
        "create table if not exists users (username text, subreddits text)")
    cur.execute(
        "create table if not exists filters (username text, filter text, subreddit text)")
    db.commit()
    return db

def users(con):
    cur = con.cursor()
    cur.execute("select * from users")
    rows = cur.fetchall()
    return rows

def get_most_recent_time():
    try:
        file = open("most_recent_time.txt", 'r')
        text = file.read()
        file.close()
        return float(text)
    except:
        file = open("most_recent_time.txt", 'a')
        file.close()
        return 0

def set_most_recent_time(most_recent_time):
    file = open("most_recent_time.txt", 'w')
    file.write(str(most_recent_time))
    file.close()

def get_filter(db, username, sub):
    cur = db.cursor()
    cur.execute('select filter from filters where username="{}" and subreddit="{}"'.format(
        username, sub))
    return cur.fetchone()

def subreddits(db):
    cur = db.cursor()
    cur.execute('select subreddits from users')
    subs = []
    for subreddit_group in cur.fetchall():
        subs = subs + subreddit_group[0].split(',')
    return subs

def update_user(user_data, db):
    cur = db.cursor()
    username = user_data['username']
    subreddit_filter_list = user_data['subreddits']
    if username not in WHITELISTED_USERS:
        subreddit_notifications.log(
            "The user {} is not whitelisted".format(username))
        return
    subreddit_list = []
    for subreddit in subreddit_filter_list:
        subreddit_list.append(subreddit[0])

    subreddit_list = ','.join(subreddit_list)
    cur.execute(
        'select username from users where username="{}"'.format(username))
    if cur.fetchall():
        subreddit_notifications.log("Updating user: " + username)
        cur.execute('update users set subreddits="{}" where username="{}"'.format(
            subreddit_list, username))
        cur.execute('delete from filters where username="{}"'.format(username))
    else:
        subreddit_notifications.log("Creating new user: " + username)
        cur.execute('insert into users values ("{}", "{}")'.format(
            username, subreddit_list))
    for subreddit in subreddit_filter_list:
        cur.execute('insert into filters values ("{}", "(?i)({})", "{}")'.format(
            username, subreddit[1], subreddit[0]))
    db.commit()

def remove_user(user, con):
    cur = con.cursor()
    cur.execute("drop {} from users".format(user))
    con.commit()


import math

"""
Python Challenges
"""

"""
This is a Python Program to find those numbers which are divisible by 7 and multiple of 5 in a given range of numbers.

Problem Description
The program takes an upper range and lower range and finds those numbers that are divisible by 7 and multiple of 5.

Problem Solution
1. Take in the upper and lower range and store it in separate variables.
2. Use a for loop which ranges from the lower range to the upper range.
3. Then find the numbers which are divisible by both 5 and 7.
4. Print those numbers
5. Exit.
"""

def fetch_integer_divisible_multiple():
    print()
    user_input_start_range = int(input("Enter the starting range value for this program: "))
    user_input_end_range = int(input("Enter the ending range value for this program: "))
    building_range = range(user_input_start_range, user_input_end_range + 1)
    for each_int in building_range:
        if each_int % 7 == 0 and each_int % 5 == 0:
            print(each_int, "= divisible by 7 and it's a multiple of 5")

fetch_integer_divisible_multiple()

"""
This is a Python Program to check if a number is an Armstrong number.

Problem Description
The program takes a number and checks if it is an Armstrong number.

Problem Solution
1. Take in an integer and store it in a variable.
2. Convert each digit of the number to a string variable and store it in a list.
3. Then cube each of the digits and store it in another list.
4. Find the sum of the cube of digits in the list and check if it is equal to the original number.
5. Print the final result.
6. Exit.
"""

def validate_armstrong_feature():
    print()

    total_sum = 0
    try:
        user_input = input("Enter any number of your choice: ")
        for each_digit in user_input:
            int_conversion_val = int(each_digit)
            cube_value = int_conversion_val ** 3
            total_sum = total_sum + cube_value
        print("Total sum of all integers calculated after raising it to power 3 for each digit: ", total_sum)

        if total_sum == int(user_input):
            print("So, number entered in an input matches with Armstrong criteria")
        else:
            print("Hence, number entered in an input doesn't matches with Armstrong criteria")
    except ValueError as ve:
        print("Value Error: ", ve)

validate_armstrong_feature()

"""
This is a Python Program to check if a number is a Perfect number.

Problem Description
The program takes a number and checks if it is a Perfect number.

Problem Solution
1. Take in an integer and store it in a variable.
2. Initialize a variable to count the sum of the proper divisors to 0.
3. Use a for loop and an if statement to add the proper divisors of the integer to the sum variable.
4. Check if the sum of the proper divisors of the number is equal to the variable.
5. Print the final result.
6. Exit.
"""

def perform_perfect_number_validation():
    print()
    try:
        user_input = input("Enter any number of your choice: ")
        total_sum = 0
        for each_digit in user_input:
            int_converted_val = int(each_digit)
            if int(user_input) % int_converted_val == 0:
                total_sum = total_sum + int_converted_val
        print("Completed looping activities")

        if total_sum == int(user_input):
            print("Wow, you entered a Perfect number!")
        else:
            print("Cool, try again to identify a Perfect number!")
    except ValueError as ve:
        print("Value Error: ", ve)

perform_perfect_number_validation()

"""
This is a Python Program to check if a number is a strong number.

Problem Description
The program takes a number and checks if it is a strong number.

Problem Solution
1. Take in an integer and store it in a variable.
2. Using two while loops, find the factorial of each of the digits in the number.
3. Then sum up all the factorials of the digits.
4. Check if the sum of the factorials of the digits is equal to the number.
5. Print the final result.
6. Exit.
"""

def perform_strong_number_validation():
    print()
    user_number = int(input("Enter any number of your choice for Strong number identification: "))
    sum_val = 0
    temp_val = user_number
    while temp_val > 0:
        factorial = 1
        iteration_val = 1
        reminder = temp_val % 10

        while iteration_val <= reminder:
            factorial = factorial * iteration_val
            iteration_val = iteration_val + 1

        print("\n Factorial of %d = %d" % (reminder, factorial))
        sum_val = sum_val + factorial
        temp_val = temp_val // 10

    print("\n Sum of Factorials of a given number %d = %d" % (user_number, sum_val))

    if sum_val == user_number:
        print("%d is a Strong number" % user_number)
    else:
        print("%d is not a Strong number" % user_number)

perform_strong_number_validation()

"""
This is a Python Program to find the LCM of two numbers.

Problem Description
The program takes two numbers and prints the LCM of two numbers.

Problem Solution
1. Take in both the integers and store it in separate variables.
2. Find which of the integer among the two is smaller and store it in a separate variable.
3. Use a while loop whose condition is always True until break is used.
4. Use an if statement to check if both the numbers are divisible by the minimum number and increment otherwise.
5. Print the final LCM.
6. Exit.

Program Explanation
1. User must enter both the numbers and store it in separate variables.
2. An if statement is used to find out which of the numbers is smaller and store in a minimum variable.
3. Then a while loop is used whose condition is always true (or 1) unless break is used.
4. Then an if statement within the loop is used to check whether the value in the minimum variable is divisible by both the numbers.
5. If it is divisible, break statement breaks out of the loop.
6. If it is not divisible, the value in the minimum variable is incremented.
7. The final LCM is printed.
"""

def finding_lcm_value():
    first_val = int(input("Enter the first number of your choice for LCM value: "))
    second_val = int(input("Enter the first number of your choice for LCM value: "))

    if first_val > second_val:
        min1 = first_val
    else:
        min1 = second_val

    while 1:
        if min1 % first_val == 0 and min1 % second_val == 0:
            print("LCM is: ", min1)
            break
        min1 = min1 + 1

finding_lcm_value()

"""
Problem Description
The program takes two numbers and prints the GCD of two numbers.

Problem Solution
1. Import the fractions module.
2. Take in both the integers and store it in separate variables.
3. Use the in-built function to find the GCD of both the numbers.
4. Print the GCD.
5. Exit.
"""

def finding_gcd_value():
    a = int(input("Enter the first number:"))
    b = int(input("Enter the second number:"))
    print("The GCD of the two numbers is", math.gcd(a, b))

finding_gcd_value()


class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        counts = {}
        mostFreqChar = 0
        left = 0

        for right, ch in enumerate(s):
            counts[ch] = 1 + counts.get(ch, 0)
            mostFreqChar = max(mostFreqChar, counts[ch])
            while (right - left + 1) - mostFreqChar > k:
                counts[s[left]] -= 1
                left += 1

        return len(s) - left


import cv2
import numpy as np

dim = (300,300)

def verifique(imagem, ponto, conectividade):

    if conectividade == 4:
        print (ponto)
        if imagem[ponto[0]-1, ponto[1]] == 255:
            imagem[ponto[0]-1,ponto[1]] = 0
            print('0')
            return (ponto[0]-1, ponto[1])
        elif imagem[ponto[0], ponto[1]+1] == 255:
                imagem[ponto[0],ponto[1]+1] = 0
                print('1')
                return (ponto[0], ponto[1]+1)
        elif imagem[ponto[0]+1, ponto[1]] == 255:
                imagem[ponto[0]+1,ponto[1]] = 0
                print('2')
                return (ponto[0]+1, ponto[1])
        elif imagem[ponto[0], ponto[1]-1] == 255:
                imagem[ponto[0],ponto[1]-1] = 0
                print('3')
                return (ponto[0], ponto[1]-1)
        else:
            print('none')
    else:
        return ponto

def normalizaImagem(v):
    v = (v - v.min()) / (v.max() - v.min())
    resultado = (v * 255).astype(np.uint8)
    return resultado

imagem = cv2.imread('1_5.jpg')
imagemBin = 255 - imagem[:,:,0]

novaImagem = np.zeros(np.shape(imagemBin))
kernel = np.ones((3,3), np.uint8)
novaImagem = normalizaImagem((imagemBin>100)*1)

imCopy = np.copy(novaImagem)
imPlot = np.zeros(np.shape(imagem))
imPlot[:,:,0] = imPlot[:,:,1] = imPlot[:,:,2] = imCopy

novaImagem = cv2.dilate(novaImagem, kernel, iterations=1) - novaImagem
cv2.imshow('Imagem', imPlot)
cv2.waitKey(0)

max_xy = np.where(novaImagem == 255)
print (max_xy[0][0], max_xy[1][0])

novaImagemRGB = np.zeros(np.shape(imagem))
novaImagemRGB[:,:,0] = novaImagemRGB[:,:,1] = novaImagemRGB[:,:,2] = novaImagem

cv2.circle(novaImagemRGB, (max_xy[1][0], max_xy[0][0]), int(3), (0,0,255), 2)
iniciarPonto = (max_xy[0][0], max_xy[1][0])
ponto = verifique(novaImagem, iniciarPonto, 4)

while(ponto!=iniciarPonto):
    cv2.circle(novaImagemRGB, (ponto[1], ponto[0]), int(3), (0,0,255), 4)
    cv2.imshow('Imagem', imPlot)
    cv2.waitKey(1)

    cv2.circle(imPlot, (ponto[1], ponto[0]), int(3), (0,255,255), 6)
    ponto = verifique(novaImagem, ponto, 4)

cv2.imshow('Imagem', imPlot)
cv2.waitKey(0)


from constants import *
import pygame
from bullet import Bullet

class Player(pygame.sprite.Sprite):
    def __init__(self, color, width, height, world):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.vel = [0,0]                   #speed of player
        self.face_right = True
        self.health = 100
        #group to hold bullets that fired by player
        self.bullet_group = pygame.sprite.Group()
        #world that hold player
        self.world = world
        #acc of the player's vel
        self.acc = 0.005
    def move_right(self):
        self.vel[0] = 0.8
        self.face_right = True
    def move_left(self):
        self.vel[0] = -0.8
        self.face_right = False
    def stop(self):
        self.vel[0] = 0
    def jump(self):
        self.rect.y += 2
        hit_list = pygame.sprite.spritecollide(self, self.world.platfrom_group, False)
        self.rect.y -= 2
        for sprite in hit_list:
            self.vel[1] = -1.5
    def fire(self):
        bullet = Bullet(RED, 20, 5, self)
        self.bullet_group.add(bullet)
    def update(self):
        ##############################################################################
        #handle collide, very important!!!!!!!!!
        ##############################################################################
        #first test the left and right
        self.rect.x += self.vel[0]*self.world.dt
        hit_list = pygame.sprite.spritecollide(self, self.world.platfrom_group, False)
        for sprite in hit_list:
            if self.vel[0] > 0:
                self.rect.right = sprite.rect.left
            if self.vel[0] < 0:
                self.rect.left = sprite.rect.right
        #then test the up and down
        self.vel[1] += self.acc * self.world.dt                        #gravity effect
        self.rect.y += self.vel[1]*self.world.dt
        hit_list = pygame.sprite.spritecollide(self, self.world.platfrom_group, False)
        for sprite in hit_list:
            if self.vel[1] > 0:
                self.rect.bottom = sprite.rect.top
            if self.vel[1] < 0:
                self.rect.top = sprite.rect.bottom
            self.vel[1] = 0
        ###############################################################################

        #update bullets
        for bullet in self.bullet_group:
            bullet.update()
            if bullet.rect.x < -1000 or bullet.rect.x > 20000:
                self.bullet_group.remove(bullet)


import io
import sys

from django.shortcuts import render

from django.views.decorators.csrf import csrf_protect
from .forms import UserCreationForm
from Main import schedulingAlgorithm

@csrf_protect
def openSimulator(request) :
    # for printing the console into a variable
    old_stdout = sys.stdout
    new_stdout = io.StringIO()
    sys.stdout = new_stdout

    if request.method == 'POST':
        form = UserCreationForm()
        final_array = request.POST.get('final_array')
        interval = request.POST.get('interval')
        noOfTasks = request.POST.get('noOfTasks')
        #form['interval'].initial = interval

        # splitting the input into desired format
        algorithmInputArray = arraySplit(final_array)
        # calculating rate monotonic scheduling algorithm
        rmsArray, edfArray, fcfsArray, sjfArray = schedulingAlgorithm.schedule(algorithmInputArray)
        # formating the input array to send it back to screen
        algorithmInputArray = returnInputArray(algorithmInputArray)

        # writing standard output to variable
        outputConsole = new_stdout.getvalue()
        sys.stdout = old_stdout  # setting the standard output back to console

        return render(request, 'index.html',{'sjfArray': sjfArray, 'fcfsArray': fcfsArray, 'edfArray': edfArray, 'rmsArray': rmsArray, 'noOfTasks': noOfTasks,'algorithmInputArray': algorithmInputArray, 'form': form, 'outputConsole': outputConsole})
    else:
        form = UserCreationForm()
        outputConsole = new_stdout.getvalue()
        sys.stdout = old_stdout  # setting the standard output back to console
        return render(request, 'index.html', {'sjfArray': [], 'fcfsArray': [], 'edfArray': [], 'rmsArray': [], 'noOfTasks': [],'algorithmInputArray': [], 'form': form, 'outputConsole': outputConsole})

def arraySplit(algorithmInputs):
    algorithmInputs = algorithmInputs[:-1]
    algorithmInputs = algorithmInputs.split("|")
    algorithmInputArray = []
    for algorithmInput in algorithmInputs:
        algorithmInput = algorithmInput[:-1]
        algorithmInputArray.append(list(map(int, algorithmInput.split(",", -1))))
    return algorithmInputArray

def returnInputArray(algorithmInputArray):
    algorithmInputArray.sort(key=lambda x: x[1])
    for inputArray in algorithmInputArray:
        inputArray[1:]
    return algorithmInputArray


""" Test case for service functions of firestorm app of project ten. """
import logging

from django.test import TestCase
from django.test.client import RequestFactory

from advertiser.factories.advertiser_factory import ADVERTISER_FACTORY
from common.test_utils import EnhancedTestCase
from firestorm.factories.ad_rep_factory import AD_REP_FACTORY
from firestorm.models import AdRepAdvertiser
from firestorm.service import build_adv_url_with_ad_rep, get_consumer_bonus_pool

LOG = logging.getLogger('ten.%s' % __name__)
LOG.setLevel(logging.INFO)

class TestGetConsumerBonusPool(TestCase):
    """ Test case for get_consumer_bonus_pool. """

    def test_get_consumer_bonus_pool(self):
        """ Assert the consumer bonus pool is calculated correctly. """
        ad_rep = AD_REP_FACTORY.create_ad_rep()
        pool = get_consumer_bonus_pool()
        self.assertEqual(pool, 0)
        AD_REP_FACTORY.qualify_ad_rep(ad_rep)
        self.assertEqual(ad_rep.verified_consumers().count(), 10)
        ad_rep.consumer_points = '100'
        ad_rep.save()
        pool = get_consumer_bonus_pool()
        self.assertEqual(pool, 100)

class TestBuildURLForAdRepLoading(EnhancedTestCase):
    """ Test cases for service function build_adv_url_with_ad_rep that builds
    a url that calls join-me view and then redirects to final destination URL
    (after loading ad rep in session). If there is no ad rep, for advertiser
    (and no url supplied), then just pass back the destination URL.
    """

    def prep_test(self, ad_rep_advertiser=False):
        """ Create a request to test with. """
        self.advertiser = ADVERTISER_FACTORY.create_advertiser()
        self.ad_rep = AD_REP_FACTORY.create_ad_rep()
        factory = RequestFactory()
        self.request = factory.get('/hudson-valley/', follow=True)
        self.request.session = self.session
        self.request.session['ad_rep_id'] = self.ad_rep.id
        self.request.session['referring_ad_rep_dict'] = self.ad_rep
        if ad_rep_advertiser:
            AdRepAdvertiser.objects.create_update_rep(
                self.request, self.advertiser, self.ad_rep)

    def test_no_ad_rep_no_ad_rep_url(self):
        """ Assert when advertiser does not have an ad rep and no ad rep url
        supplied as a parameter, the destination URL is passed back.
        """
        self.prep_test()
        test_url = '/omega/alpha/pluralis/'
        formatted_url = build_adv_url_with_ad_rep(self.advertiser, test_url)
        self.assertEqual(formatted_url, test_url)

    def test_ad_rep_no_ad_rep_url(self):
        """ Assert when advertise  has an ad rep the link is formatted and
        returned correctly.
        """
        self.prep_test(True)
        test_url = '/omega/alpha/pluralis/'
        formatted_url = build_adv_url_with_ad_rep(self.advertiser, test_url)
        self.assertEqual(formatted_url,
            '/join-me/omega/alpha/pluralis/%s/' % self.ad_rep.url)

    def test_ad_rep_url(self):
        """ Assert whatever is passed at the ad rep url is used in the finally
        return (minimizes db hits).
        """
        self.prep_test(False)
        test_url = '/omega/alpha/pluralis/'
        formatted_url = build_adv_url_with_ad_rep(
            self.advertiser, test_url, self.ad_rep.url)
        self.assertEqual(formatted_url,
            '/join-me/omega/alpha/pluralis/%s/' % self.ad_rep.url)


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

"""Contains the functions for handling the user interface

This file contains the functions for handling the command line user interface.
It mainly processses the command line arguments, loads the settings,
initializes a HugoPhotoSwipe instance, and passes the command to this instance.

Author: Gertjan van den Burg
License: GPL v3.

"""

import argparse
import logging
import os
import sys

from . import __version__
from .config import SETTINGS_FILENAME
from .config import settings
from .hugophotoswipe import HugoPhotoSwipe

def main():
    """Main HugoPhotoSwipe function to be called to run the program"""
    command, album = parse_args()

    if command == "init":
        logging.info("Dumping settings file.")
        settings.dump(".")
        print("Created settings file: %s" % SETTINGS_FILENAME)
        return

    if not os.path.exists(SETTINGS_FILENAME):
        print(
            "Can't find %s, please run `hps init` to create it"
            % SETTINGS_FILENAME
        )
        raise SystemExit(1)

    if not settings.validate():
        return

    hps = HugoPhotoSwipe()
    if command == "new":
        logging.info("Creating new album")
        hps.new(name=album)
    elif command == "update":
        logging.info("Running album update")
        hps.update(name=album)
    elif command == "clean":
        logging.info("Running clean")
        hps.clean(name=album)
    else:
        raise ValueError("Unknown command: %s" % command)
    logging.info("Dumping settings file.")
    settings.dump(".")

def parse_args():
    """Parse the command line arguments"""
    parser = argparse.ArgumentParser(
        prog="HugoPhotoSwipe", description="Integrate Hugo and PhotoSwipe"
    )
    parser.add_argument(
        "-v",
        "--verbose",
        help="Verbose mode",
        action="store_const",
        dest="loglevel",
        const=logging.INFO,
        default=logging.WARNING,
    )
    parser.add_argument(
        "-f",
        "--fast",
        action="store_true",
        help=("Fast mode (attempts fewer potential crops for thumbnails)"),
    )
    parser.add_argument(
        "-V",
        "--version",
        action="version",
        version=__version__,
    )
    parser.add_argument(
        "command",
        choices=["new", "update", "clean", "init"],
        help="action to do",
    )
    parser.add_argument(
        "album", nargs="?", help="album to apply the action to"
    )
    args = parser.parse_args()
    logging.basicConfig(
        level=args.loglevel,
        datefmt="[%Y-%m-%d %H:%M:%S]",
        format="%(asctime)s - %(message)s",
    )
    settings.verbose = args.loglevel == logging.INFO
    settings.fast = args.fast
    return args.command, args.album

if __name__ == "__main__":
    sys.exit(main())


from losscape.plot import *
from losscape.models import *

import math

import torchvision
import matplotlib.pyplot as plt

cifar_data = torchvision.datasets.CIFAR10('sample_data/cifar/', download=True)

plt.imshow(cifar_data[1000][0])
plt.show()

CIFAR_MEAN = [0.4913997551666284, 0.48215855929893703, 0.4465309133731618]
CIFAR_STD = [0.24703225141799082, 0.24348516474564, 0.26158783926049628]

class CifarResnet(LandscapeProblem):
  def dataset(self, idx):
    img, label = self.data[self.batch_size*idx:self.batch_size*(idx+1)]
    img = jnp.array(img) / 255.
    img = (img - jnp.array(CIFAR_MEAN)[None,None,...]) / jnp.array(CIFAR_STD)[None,None,...]
    img = img[None,...]
    return img, label

  def dataset_len(self):
    return math.floor(len(cifar_data) / 10)

  def load_dataset(self):
    self.data = cifar_data

  def eval_params(self, params, batch, label):
    logits = self.model.apply(params, batch)
    return optax.softmax_cross_entropy_with_integer_labels(logits, label[None,...]).mean()

cifar_landscape = CifarResnet(ResNet50(num_classes=10), batch_size=2)
optimizer = optax.MultiSteps(optax.adam(1e-4), 2)
parameter_path = cifar_landscape.train_path(optimizer, epochs=10)

fig = LossVisualizer().plotly_plot(cifar_landscape, parameter_path, resolution=101)
fig.show()


'''bdpy.evals.metrics'''

import warnings

import numpy as np
from scipy.spatial.distance import cdist

def profile_correlation(x, y):
    '''Profile correlation.'''

    sample_axis = 0

    orig_shape = x.shape
    n_sample = orig_shape[sample_axis]

    _x = x.reshape(n_sample, -1)
    _y = y.reshape(n_sample, -1)

    n_feat = _y.shape[1]

    r = np.array(
        [
            np.corrcoef(
                _x[:, j].flatten(),
                _y[:, j].flatten()
            )[0, 1]
            for j in range(n_feat)
        ]
    )

    r = r.reshape((1,) + orig_shape[1:])

    return r

def pattern_correlation(x, y, mean=None, std=None, remove_nan=True):
    '''Pattern correlation.'''

    sample_axis = 0

    orig_shape = x.shape
    n_sample = orig_shape[sample_axis]

    _x = x.reshape(n_sample, -1)
    _y = y.reshape(n_sample, -1)

    if mean is not None and std is not None:
        m = mean.reshape(-1)
        s = std.reshape(-1)

        _x = (_x - m) / s
        _y = (_y - m) / s

    if remove_nan:
        # Remove nan columns based on the decoded features
        nan_cols = np.isnan(_x).any(axis=0) | np.isnan(_y).any(axis=0)
        if nan_cols.any():
            warnings.warn('NaN column removed ({})'.format(np.sum(nan_cols)))
        _x = _x[:, ~nan_cols]
        _y = _y[:, ~nan_cols]

    r = np.array(
        [
            np.corrcoef(
                _x[i, :].flatten(),
                _y[i, :].flatten()
            )[0, 1]
            for i in range(n_sample)
        ]
    )

    return r

def pairwise_identification(pred, true, metric='correlation', remove_nan=True, remove_nan_dist=True, single_trial=False, pred_labels=None, true_labels=None):
    '''Pair-wise identification.'''

    p = pred.reshape(pred.shape[0], -1)
    t = true.reshape(true.shape[0], -1)

    if remove_nan:
        # Remove nan columns based on the decoded features
        nan_cols = np.isnan(p).any(axis=0) | np.isnan(t).any(axis=0)
        if nan_cols.any():
            warnings.warn('NaN column removed ({})'.format(np.sum(nan_cols)))
        p = p[:, ~nan_cols]
        t = t[:, ~nan_cols]

    if single_trial:
        cr = []
        for i in range(p.shape[0]):
            d = 1 - cdist(p[i][np.newaxis], t, metric=metric)
            # label の情報
            ind = np.where(np.array(true_labels) == pred_labels[i])[0][0]

            s = (d - d[0, ind]).flatten()
            if remove_nan_dist and np.isnan(s).any():
                warnings.warn('NaN value detected in the distance matrix ({}).'.format(np.sum(np.isnan(s))))
                s = s[~np.isnan(s)]
            ac = np.sum(s < 0) / (len(s) - 1)
            cr.append(ac)
        cr = np.asarray(cr)
    else:
        d = 1 - cdist(p, t, metric=metric)

        if remove_nan_dist:
            cr = []
            for d_ind in range(d.shape[0]):
                pef = d[d_ind, :] - d[d_ind, d_ind]
                if np.isnan(pef).any():
                    warnings.warn('NaN value detected in the distance matrix ({}).'.format(np.sum(np.isnan(pef))))
                    pef = pef[~np.isnan(pef)] # Remove nan value from the comparison for identification
                pef = np.sum(pef < 0) / (len(pef) - 1)
                cr.append(pef)
            cr = np.asarray(cr)
        else:
            cr = np.sum(d - np.diag(d)[:, np.newaxis] < 0, axis=1) / (d.shape[1] - 1)

    return cr

def remove_nan_value(array, nan_flag=None, return_nan_flag=False):
    '''Helper function:
    Remove columns (units) which contain nan values

    array (numpy.array) ... shape should be [sample x units]
    nan_flag (numpy.array or list) ... if exist, remove columns according to the nan_flag
    return_nan_flag (bool) ... if True, return nan_flag to remove columns of the array.

    '''

    if nan_flag is None:
        nan_flag = np.isnan(array).any(axis=0)
    nan_removed_array = array[:, ~nan_flag]

    if return_nan_flag:
        return nan_removed_array, nan_flag
    else:
        return nan_removed_array