import Analyze
import System, System.IO

###################### COPYRIGHT FIKRIMF & GEMA @IMMOBI TECHNOLOGY SDN BHD #####################

# sdjhsakdhsajkdhkahsdsadhasdjhashdkjashjkd

#exportfolder = "E:\\Export Plot DT\\UMOBILE - NOKIA\\KUAT\\"        #TARGET FOLDER .JPG/.PNG
#workbookname = 'PAC'

#ExportTargetPath = "E:\\Export Plot DT\\Q2 ALL HIGHWAY\\GUTHRIE\\TAB\\"               #TARGET FOLDER .TAB
#ExportTargetName = 'Q2 ALL HIGHWAY GUTHRIE'

warningtext = 'Please wait until the workbook finisihed loading'
Windows.MessageBox(warningtext, 'Loading the logfiles...', 'yes')

#if not System.IO.Directory.Exists( exportfolder ):
#	System.IO.Directory.CreateDirectory( exportfolder )

Width = 260 #280

# Set workspace's DataViewAdded-event handler.
#Analyze.Workspace.DataViewAdded += lambda sender, args: dataviewadded(args.dataview)
Longitude = float(103.0851)
Latitude = float(5.3364)
# get all workbooks check type and set width
index=0
workbooks = Analyze.Workspace.Workbooks
for workbook in workbooks:
	#filename = '{0} {1}'.format(workbookname,index)
	pages = workbook.GetAllPages()
	index2=0
	for page in pages:
		dataviews = page.Views
		namaPage = page.Title
		for dataview in dataviews:
			if isinstance(dataview, MapDataView):
				dataview.ResizeSidepanel(Width)
				dataview.BestFitZoom()
				#dataview.ZoomTo(abcde)
				dataview.SetDrawingMode("line")
				dataview.SetShowScaleBar(False)
				dataview.ResizeSidepanel(Width)
				frames = dataview.Frames
				for frame in frames:
					frame.ResizeFrame(200,0,270,150)
				#workbook.ExportPage(index2,exportfolder+str(index2)+str(workbook)+"_"+workbookname+"_"+namaPage+".jpg")
				#workbook.ExportToWord(exportfolder, "A.docx",'','')
			    #Log.Write(namaPage+" "+"successfully exported !!!")
		index2=index2+1
	index=index+1
	#workbook.ExportToWord(exportfolder, "A.docx",'','')
#zzzz = dataview.GetCenter()
#bv = str(zzzz)
#Windows.MessageBox(bv, 'campret', 'as')
#################################################### EXPORT MAP TO TAB #######################################################
# Creates MapInfo (.tab) files from all layers in all map views and export files to given folder.
#def exportMapsFromWorkboobPage(page, index):
#	dataviews = page.Views
#	datahalaman = page.Title
#	for dataview in dataviews:
#		# check that dataview is MapDataView type
#		if isinstance(dataview, MapDataView):
#			filename = '{1} {0}'.format(index,ExportTargetName+" "+datahalaman)
#			pathAndFileName = '{0} {1}'.format(ExportTargetPath,filename)
#			dataview.ExportToMapInfo(pathAndFileName,'')
#			index = index +1
#	return index

## Create the folder if it does not exist.
#if not System.IO.Directory.Exists( ExportTargetPath ):
#	System.IO.Directory.CreateDirectory( ExportTargetPath )

## Get all workbooks and go through all pages.
#workbooks = Analyze.Workspace.Workbooks
#index = 1
#for workbook in workbooks:
#	workbookpageindex = 0
#	workbookpages = workbook.GetAllPages()
#	for workbookpage in workbookpages:
#		index = exportMapsFromWorkboobPage(workbookpage, index)


"""
  ___________________________________________________
 |  _____                       _____ _ _       _    |
 | |  __ \                     |  __ (_) |     | |   |
 | | |__) |__ _ __   __ _ _   _| |__) || | ___ | |_  |
 | |  ___/ _ \ '_ \ / _` | | | |  ___/ | |/ _ \| __| |
 | | |  |  __/ | | | (_| | |_| | |   | | | (_) | |_  |
 | |_|   \___|_| |_|\__, |\__,_|_|   |_|_|\___/ \__| |
 |                   __/ |                           |
 |  GNU/Linux based |___/  Multi-Rotor UAV Autopilot |
 |___________________________________________________|

 Takeoff Activity Class

 Copyright (C) 2014 Tobias Simon, Ilmenau University of Technology

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details. """

from pilot_pb2 import *
from activity import Activity, StabMixIn

from logging import debug as log_debug, info as log_info, warning as log_warn, error as log_err

class TakeoffActivity(Activity, StabMixIn):

   LOW_ALT_SETPOINT = -10.0
   STD_HOVERING_ALT = 3.0

   def __init__(self, fsm, icarus):
      Activity.__init__(self, icarus)
      self.canceled = False
      self.fsm = fsm

   def _cancel(self):
      self.canceled = True

   def run(self):
      arg = self.icarus.arg
      pilot = self.icarus.pilot
      mon_data = self.icarus.mon_data
      params = self.icarus.pilot.params

      if arg.HasField('move_data'):
         z_setpoint = arg.move_data.z
         if arg.HasField('rel'):
            log_warn('rel field ignored for take-off')
         if arg.HasField('glob'):
            if not arg.glob:
               if z_setpoint < pilot.params.start_alt + mon_data.z + 3.0:
                  msg = 'absolute z setpoint %f is below current altitude' % z_setpoint
                  log_err(msg)
                  raise ValueError(msg)
               log_info('taking off to absolute altitude %f' % z_setpoint)
            else:
               z_setpoint = mon_data.z + z_setpoint
               log_info('taking off to relative altitude %f' % z_setpoint)
      else:
         z_setpoint = self.STD_HOVERING_ALT

      pilot.start_motors()

      if self.canceled:
         pilot.stop_motors()
         log_error('take-off canceled');
         return

      # "point of no return":
      # reset controllers:
      pilot.set_ctrl_param(POS_YAW, mon_data.yaw)
      pilot.set_ctrl_param(POS_E, mon_data.e)
      pilot.set_ctrl_param(POS_N, mon_data.n)
      pilot.reset_ctrl()

      # set new altitude setpoint and stabilize:
      pilot.set_ctrl_param(POS_U, u_setpoint)
      self.stabilize()
      self.fsm.handle('done')


from typing import Sequence

from hypothesis import given

from sect.core.contracts import is_point_inside_circumcircle
from sect.core.utils import (contour_to_segments,
                             normalize_contour,
                             to_convex_hull)
from sect.hints import (Point,
                        Triangle)
from sect.triangulation import delaunay_triangles
from tests.utils import (to_boundary_endpoints,
                         to_convex_border)
from . import strategies

@given(strategies.points_lists)
def test_basic(points: Sequence[Point]) -> None:
    result = delaunay_triangles(points)

    assert isinstance(result, list)
    assert all(isinstance(element, tuple)
               for element in result)

@given(strategies.points_lists)
def test_sizes(points: Sequence[Point]) -> None:
    result = delaunay_triangles(points)

    assert 0 < len(result) <= (2 * (len(points) - 1)
                               - len(to_convex_hull(points)))
    assert all(len(element) == 3
               for element in result)

@given(strategies.points_lists)
def test_delaunay_criterion(points: Sequence[Point]) -> None:
    result = delaunay_triangles(points)

    assert all(not any(is_point_inside_circumcircle(*triangle_contour, point)
                       for triangle_contour in result)
               for point in points)

@given(strategies.points_lists)
def test_boundary(points: Sequence[Point]) -> None:
    result = delaunay_triangles(points)

    assert (to_boundary_endpoints(result)
            == set(map(frozenset,
                       contour_to_segments(to_convex_border(points)))))

@given(strategies.triangles)
def test_base_case(triangle: Triangle) -> None:
    result = delaunay_triangles(triangle)

    assert len(result) == 1
    assert normalize_contour(triangle) in result

@given(strategies.non_triangle_points_lists)
def test_step(next_points: Sequence[Point]) -> None:
    points = next_points[:-1]
    next_point = next_points[-1]

    result = delaunay_triangles(points)
    next_result = delaunay_triangles(next_points)

    assert len(result) <= len(next_result) + 2
    assert all(triangle not in next_result
               for triangle in result
               if is_point_inside_circumcircle(*triangle, next_point))


"""Write a program which can compute the factorial of a given numbers."""
fact = 1
while True:
    a = int(input("Enter a number: "))
    if a >= 0:
        break
if a != 0:
    for x in range(1,a+1):
        fact *= x
print(fact)


# coding=UTF8
# encoding=utf8

# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#		 http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

from __future__ import absolute_import
from __future__ import print_function
# import tensorflow.python.platform
import collections
import math
import numpy as np
# import os
import random
# from six.moves import urllib
from six.moves import xrange	# pylint: disable=redefined-builtin
import tensorflow as tf
import codecs
import jieba.analyse
import sys
import re
import sklearn.preprocessing
from numpy import array
import chroma
# import matplotlib.pyplot as plt
# import matplotlib.colors as colors
# import matplotlib.cm as cmx

import sqlite3

reload(sys)
sys.setdefaultencoding('utf8')

#const
top_n_articles = 20
vocabulary_size = 3000 #top n words to be trained
#num_steps = 10001 #training steps, ex. 100001
num_steps = 100001
plot_only = 500 #ploting data pts
output_model = "model/tars-mode-c-v4"
output_filename = "img/tsne-c4.png"

# Read the data into a string.
def read_data():
	jieba.set_dictionary('dict.txt.big')
	stop1 = u"[，。、「」（）\(\)\.【】『』：；・．～？＝＼／！＠\@＄\$％＆\&\%\-\/\\\>\<\~\:\,\[\]\?\!\=\+＋\*＊]*"
	stop2 = "http[a-zA-Z\.\:\/\-\?\#]*"
	stop3 = "[0-9\.]*"
	result = []

	word_cate = {}
	color_dict = {}

	'''
	#read color dict
	header = True
	f = codecs.open('category_color.csv', 'r', encoding='utf8')
	for row in f:
		if(header):
			header = False
			continue
		row = row.replace('"', '').split(',')
		color_dict[row[0]] = None

	arr = color_dict.keys()
	cNorm  = colors.Normalize(vmin=-0.1, vmax=1)
	scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=plt.get_cmap('nipy_spectral') )
	for i in range(len(arr)):
		color = scalarMap.to_rgba(i/float(len(arr)))
		color_dict[arr[i]] = chroma.Color(color, format="RGB")
		print(arr[i]+', '+str(color_dict[arr[i]]))
	'''

	#read article
	conn = sqlite3.connect('ptt_course.db')
	c = conn.cursor()

	for i, article in enumerate(c.execute('SELECT Content FROM Article_Directory WHERE Category = "評價" AND Content not null')):
		print('reading %i' % i)
		result += ['UNK']
		text = article[0].replace('  ', '')
		text = re.sub(stop1, "", text)
		text = re.sub(stop2, "_URL_", text)
		text = re.sub(stop3, "", text)
		seg_list = jieba.lcut(text, cut_all=False)
		word_list = []
		for seg in seg_list:
			if(len(seg) == 1):
				continue
			word_list.append(seg)
		result += word_list
	'''
	for partition in range(0, 10000, 1000):
		count = 0
		filename = 'article_v2_%s_%s.arff' % (str(partition), str(partition+1000))
		print(filename)
		f = codecs.open(filename, 'r', encoding='utf8')
		for row in f:
			if(row[0]=='@'): continue
			#if(count > 100): break
			if(count > top_n_articles): break
			print("T: "+row.split(',')[4].replace('"', ''))
			temp_cate_list = row.split(',')[1].replace('"', '').split(';')
			cate_list = []
			for cate in temp_cate_list:
				if cate in color_dict.keys():
					cate_list.append(cate)
			text = row.split(',')[5].replace('"', '')
			#print(text)
			text = re.sub(stop1, "", text)
			text = re.sub(stop2, "_URL_", text)
			text = re.sub(stop3, "", text)
			seg_list = jieba.lcut(text, cut_all=False)
			word_list = []
			for seg in seg_list:
				if(len(seg) == 1):
					continue
				word_list.append(seg)
			#print("/ ".join(seg_list))

			score_list = jieba.analyse.textrank(text, topK=20, withWeight=True, allowPOS=('ns', 'n', 'vn', 'v'))
			#here to normalize
			key_word_list = []
			norm_score_list = []

			for word, score in score_list:
				if (len(word) == 1):
					continue
				key_word_list.append(word)
				norm_score_list.append([score])

			a = array(norm_score_list, dtype='f')
			if(len(norm_score_list)>0):
				norm_score_list = sklearn.preprocessing.normalize(a, axis=0)

			for i in range(len(score_list)):
				word = key_word_list[i]
				score = norm_score_list[i][0]
				for cate in cate_list:
					try:
						word_cate[word][cate] += [score]
					except:
						try:
							word_cate[word][cate] = [score]
						except:
							word_cate[word] = {}
							word_cate[word][cate] = [score]

			result = result + word_list
			count += 1

	word_color = {}
	for word, cate_list in word_cate.iteritems():

		color_list = []
		for cate, score_list in cate_list.iteritems():
			score = sum(score_list) / float(len(score_list))
			#color = chroma.Color(color_dict[cate])
			color = color_dict[cate]
			color.alpha = score
			color_list.append(color)

		word_color[word] = chroma.Color('#000000')
		for color in color_list:
			word_color[word] += color

		if(word_color[word]==chroma.Color('#000000')):
			word_color[word] = chroma.Color('#FFFFFF')
	'''

	return result

words = read_data()
print('Data size', len(words))
# Step 2: Build the dictionary and replace rare words with UNK token.
#vocabulary_size = 1000

def build_dataset(words):
	count = [['UNK', -1]]
	count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
	dictionary = dict()
	for word, _ in count:
		dictionary[word] = len(dictionary) - 1
	data = list()
	unk_count = 0
	for word in words:
		if word in dictionary:
			index = dictionary[word]
		else:
			index = 0	# dictionary['UNK']
			unk_count = unk_count + 1
		data.append(index)
	count[0][1] = unk_count
	reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
	return data, count, dictionary, reverse_dictionary
data, count, dictionary, reverse_dictionary = build_dataset(words)
del words	# Hint to reduce memory.
print('Most common words (+UNK)', count[:10])
print('Sample data', data[:20])
data_index = 0
# Step 4: Function to generate a training batch for the skip-gram model.
def generate_batch(batch_size, num_skips, skip_window):
	global data_index
	assert batch_size % num_skips == 0
	assert num_skips <= 2 * skip_window
	batch = np.ndarray(shape=(batch_size), dtype=np.int32)
	labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
	span = 2 * skip_window + 1 # [ skip_window target skip_window ]
	buffer = collections.deque(maxlen=span)
	for _ in range(span):
		buffer.append(data[data_index])
		data_index = (data_index + 1) % len(data)
	for i in range(batch_size // num_skips):
		target = skip_window	# target label at the center of the buffer
		targets_to_avoid = [ skip_window ]
		for j in range(num_skips):
			while target in targets_to_avoid:
				target = random.randint(0, span - 1)
			targets_to_avoid.append(target)
			batch[i * num_skips + j] = buffer[skip_window]
			labels[i * num_skips + j, 0] = buffer[target]
		buffer.append(data[data_index])
		data_index = (data_index + 1) % len(data)
	return batch, labels
batch, labels = generate_batch(batch_size=8, num_skips=2, skip_window=1)
for i in range(8):
	print(batch[i], '->', labels[i, 0])
	print(reverse_dictionary[batch[i]])
	print(reverse_dictionary[batch[i]], '->', reverse_dictionary[labels[i, 0]])
# Step 5: Build and train a skip-gram model.
batch_size = 128
embedding_size = 128	# Dimension of the embedding vector.
skip_window = 1			 # How many words to consider left and right.
num_skips = 2				 # How many times to reuse an input to generate a label.
# We pick a random validation set to sample nearest neighbors. Here we limit the
# validation samples to the words that have a low numeric ID, which by
# construction are also the most frequent.
valid_size = 16		 # Random set of words to evaluate similarity on.
valid_window = 100	# Only pick dev samples in the head of the distribution.
valid_examples = np.array(random.sample(np.arange(valid_window), valid_size))
num_sampled = 64		# Number of negative examples to sample.
graph = tf.Graph()
with graph.as_default():
	# Input data.
	train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
	train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
	valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
	# Ops and variables pinned to the CPU because of missing GPU implementation
	with tf.device('/gpu:0'):
		# Look up embeddings for inputs.
		embeddings = tf.Variable(
				tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
		embed = tf.nn.embedding_lookup(embeddings, train_inputs)
		# Construct the variables for the NCE loss
		nce_weights = tf.Variable(
				tf.truncated_normal([vocabulary_size, embedding_size],
														stddev=1.0 / math.sqrt(embedding_size)))
		nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
	# Compute the average NCE loss for the batch.
	# tf.nce_loss automatically draws a new sample of the negative labels each
	# time we evaluate the loss.
	loss = tf.reduce_mean(
			tf.nn.nce_loss(nce_weights, nce_biases, embed, train_labels,
										 num_sampled, vocabulary_size))
	# Construct the SGD optimizer using a learning rate of 1.0.
	optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss)
	# Compute the cosine similarity between minibatch examples and all embeddings.
	norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
	normalized_embeddings = embeddings / norm
	valid_embeddings = tf.nn.embedding_lookup(
			normalized_embeddings, valid_dataset)
	similarity = tf.matmul(
			valid_embeddings, normalized_embeddings, transpose_b=True)
# Step 6: Begin training
#num_steps = 100001

with tf.Session(graph=graph) as session:
	# We must initialize all variables before we use them.
	tf.initialize_all_variables().run()
	saver = tf.train.Saver()  # defaults to saving all variables - in this case w and b
	print("Initialized")
	average_loss = 0
	for step in xrange(num_steps):
		batch_inputs, batch_labels = generate_batch(
				batch_size, num_skips, skip_window)
		feed_dict = {train_inputs : batch_inputs, train_labels : batch_labels}
		# We perform one update step by evaluating the optimizer op (including it
		# in the list of returned values for session.run()
		_, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)
		average_loss += loss_val
		if step % 2000 == 0:
			if step > 0:
				average_loss = average_loss / 2000
			# The average loss is an estimate of the loss over the last 2000 batches.
			print("Average loss at step ", step, ": ", average_loss)
			saver.save(session, output_model, global_step=step)
			average_loss = 0
		# note that this is expensive (~20% slowdown if computed every 500 steps)
		if step % 10000 == 0:
			sim = similarity.eval()
			for i in xrange(valid_size):
				valid_word = reverse_dictionary[valid_examples[i]]
				top_k = 8 # number of nearest neighbors
				nearest = (-sim[i, :]).argsort()[1:top_k+1]
				log_str = "Nearest to %s:" % valid_word
				for k in xrange(top_k):
					close_word = reverse_dictionary[nearest[k]]
					log_str = "%s %s," % (log_str, close_word)
				print(log_str)
	final_embeddings = normalized_embeddings.eval()
# Step 7: Visualize the embeddings.
def plot_with_labels(low_dim_embs, labels, filename=output_filename):
	assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
	font = FontProperties(fname="NotoSansCJKtc-Medium.otf", size=14)
	plt.figure(figsize=(32, 32))	#in inches
	plt.axis([-30, 30, -30, 30])
	for i, label in enumerate(labels):
		x, y = low_dim_embs[i,:]
		kwcolor = 'black'
		plt.scatter(x, y)
		plt.annotate(label,
								 xy=(x, y),
								 xytext=(5, 2),
								 textcoords='offset points',
								 ha='right',
								 va='bottom',
								 fontproperties=font,
								 color = kwcolor)
	'''
	count = 0
	for word, color in color_dict.iteritems():
		plt.text(-29, 25-1*count, word, ha='left', va='bottom', fontproperties=font, color=str(color)[:7])
		count += 1
	'''
	plt.savefig(filename)
try:
	from sklearn.manifold import TSNE
	from matplotlib.font_manager import FontProperties
	import matplotlib
	matplotlib.use('Agg') #no display
	import matplotlib.pyplot as plt
	tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
	low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only,:])
	labels = [reverse_dictionary[i] for i in xrange(plot_only)]
	plot_with_labels(low_dim_embs, labels)
except ImportError:
	print("Please install sklearn and matplotlib to visualize embeddings.")


# -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 13:14:12 2017

@author: Anne
"""
def cipherfunc(myparam):
# Take each letter from user input and in each case:

    upper = myparam.upper()
        # - Convert to upper case

    alnum = [i for i in upper if i.isalnum() == True]
        # - Ignore any other (non-alpha) characters

    cipher=""

    for i in alnum:
        cipher+=str(i)
    # - In each case, add result to a string variable

    # - Change numbers to words

    print(cipher)
    # print out the new string


'''
Created on Jan. 11, 2021

@author: rboruk
'''
try:
    from tkinter import *
    import tkinter.scrolledtext as st
except ImportError:
    from Tkinter import *

class InfoWindow:
    def __init__(self, master):

        #Creating a not resizable window
        self.rootHelp = Toplevel(master)
        self.rootHelp.title("RedisGUI About")
        self.rootHelp.geometry("600x440+500+100")
        self.rootHelp.resizable(False, False)

        #game rules describedhere
        guideText="""This GUI was built to provide basic capabilities to work with Redis DB mostly for learning purposes.
In the current version, RedisGUI supports the simple CLI and commands like:
        SET Key : Value pair
        GET Key : Value pair
        Modify Key
        Modify Value
        Delete Key : Value pair

Enjoy!!!
"""

        #frame to provide information
        self.frameHelpInfo = Frame(self.rootHelp, borderwidth=5, relief="ridge", height=395, width=395)
        self.frameHelpInfo.grid(row=0, column=0, sticky=(N, S, E, W))

        self.frameHelpInfogameRules = st.ScrolledText(self.frameHelpInfo, fg="#3366CC", width=70)
        self.frameHelpInfogameRules.grid(row=0, column = 0, pady = 5, padx = 5, sticky=(N, S, E, W))
        self.frameHelpInfogameRules.insert(INSERT, guideText)
        self.frameHelpInfogameRules.config(state=DISABLED)

        #button to close the game
        self.closeHelpButton = Button(self.rootHelp, borderwidth=5, text = "Close", command=self.endHelp)
        self.closeHelpButton.grid(row=1, column=0, sticky=(N, S, E, W))

    #close Help window
    def endHelp(self):
        self.rootHelp.destroy()

        self.rootHelp.mainloop()


from random import randint
from time import sleep

jogar = 'S'
jogador_ganha = 0
comp_ganha = 0
empate = 0

while jogar == 'S':
    itens = ('Pedra', 'Papel', 'Tesoura')
    comp = randint(0, 2)
    print('Suas opções: [0] PEDRA [1] PAPEL [2] TESOURA')

# Validando se o usuário informou o tipo de dado correto
    continua = True
    while continua:
        try:
            jogador = int(input('Qual é a sua jogada? '))
        except ValueError:
            print('O valor informado é de um tipo inválido, tente novamente digitando 0, 1 ou 2')
        else:
            continua = False

    print('JO')
    sleep(0.5)
    print('KEN')
    sleep(0.5)
    print('PO!')
    sleep(0.5)
    print(f'O computador jogou {itens[comp]}')
    print(f'Você jogou {itens[jogador]}')

    if comp == 0:
        if jogador == 0:
            print('EMPATE!')
        elif jogador == 1:
            print('JOGADOR VENCEU!')
        elif jogador == 2:
            print('COMPUTADOR VENCEU!')
        else:
            print('JOGAGA INVÁLIDA')

    elif comp == 1:
        if jogador == 0:
            print('COMPUTADOR VENCEU!')
        elif jogador == 1:
            print('EMPATE!')
        elif jogador == 2:
            print('JOGADOR VENCEU!')
        else:
            print('JOGAGA INVÁLIDA')

    elif comp == 2:
        if jogador == 0:
            print('JOGADOR VENCEU!')
        elif jogador == 1:
            print('COMPUTADOR VENCEU!')
        elif jogador == 2:
            print('EMPATE!')
        else:
            print('JOGAGA INVÁLIDA')

# Contador do placar
    if comp == 0:
        if jogador == 0:
            empate = empate + 1
        elif jogador == 1:
            jogador_ganha = jogador_ganha + 1
        elif jogador == 2:
            comp_ganha = comp_ganha + 1

    elif comp == 1:
        if jogador == 0:
            comp_ganha = comp_ganha + 1
        elif jogador == 1:
            empate = empate + 1
        elif jogador == 2:
            jogador_ganha = jogador_ganha + 1

    elif comp == 2:
        if jogador == 0:
            jogador_ganha = jogador_ganha + 1
        elif jogador == 1:
            comp_ganha = comp_ganha + 1
        elif jogador == 2:
            empate = empate + 1

    print('-=-' * 15)
    print(f'Placar atual: Jogador {jogador_ganha} x {comp_ganha} Computador')
    print('-=-' * 15)

    jogar = str(input('Deseja continuar a jogar? [S/N]')).upper()
    while jogar not in 'SN':
        jogar = str(input(
            'Digite um dado válido. Deseja continuar a jogar? [S/N] ')).upper()

else:
    if jogador_ganha > comp_ganha:
        print(f'Você venceu o computador por {jogador_ganha} a {comp_ganha}.')
    elif jogador_ganha < comp_ganha:
        print(f'O computador venceu você por {jogador_ganha} a {comp_ganha}.')
    elif jogador_ganha == comp_ganha:
        print('Vocês empataram.')


import soundfile as sf
import sounddevice as sd
import time
import os

#ham ghi am
def sync_record(filename, duration, sr, channels):
    print('recording')
    my_rec = sd.rec(samplerate=sr, channels=channels, frames=int(duration*sr))
    sd.wait()

    sf.write(filename + '.wav', data=my_rec, samplerate=sr)
    print('done recording')

#đọc file "news.txt"
def readfile(news):
    f = open("./output/" + news + "/news.txt", "r", encoding="utf-8")
    sentences = f.read().replace("\n", "").split(". ") #xóa xuống dòng và tách câu
    f.close()
    return sentences

#chọn chủ đề theo danh sách trong folder
def select_topic():
    topic = os.listdir("output")
    print("chon 1 chu de de ghi am: ")
    i = 0
    for news in topic:
        print(str(i) + '-' + news + ', ')
        i+=1
    num = input("chon chu de so: ")
    return topic[int(num)]

#hàm chính
def start_record():
    i=1
    print("Enter (y/n) to record")
    topic = select_topic()  #chọn chủ đề

    sentences = readfile(topic) #đọc bài báo theo chủ đề đã chọn
    print(topic)
    w = open("./output/" + topic + "/sentence_path.txt", "a", encoding='utf-8')

    for sentence in sentences:
        inp = input("you want to record: ")
        if inp == 'y':
            print('Record sentence: ' + sentence)
            filename = "./output/" + topic +"/wav" + str(i)

            w.write('\n'+"wav"+str(i)+ ".wav" )   #ghi tên file âm thanh
            w.write("\n"+sentence)  #ghi câu vào file

            second = len(sentence) / 15 #thời gian tính theo độ dài chuỗi
            print("thoi gian ghi am: "+str(second)+"s")

            sync_record(filename, second , 22050, 1)    #ghi âm
            i+=1
        elif inp == 'n' :
            break

    w.close()

start_record()


import caffe
import surgery, score
import pdb
import numpy as np
import os, sys
import setproctitle
setproctitle.setproctitle(os.path.basename(os.getcwd()))

# set gpu mode
caffe.set_mode_gpu()
caffe.set_device(0);

# RGB AlexNet architecture prototxt path
prototxt_file = 'alex_original.prototxt'
# Pre-trained weights path of RGB model
weights = 'fcn-alexnet-pascal.caffemodel'

# Initialize RGB model to copy 3 input filter weights (corresponding to RGB)
base_net = caffe.Net(prototxt_file, weights, caffe.TRAIN)

# Initialize SGD solver for the RGBD CNN
solver = caffe.SGDSolver('solver.prototxt')

# copy filter weights from the RGB model to the RGBD model
# this will copy weights from the parameters with the same
# name in the RGB and RGBD model. Since the input layer will
# be 4-channel instead of 3-channel (RGBD instead of RGB), it
# has a different name, so the weights will not be copied
surgery.transplant(solver.net, base_net)

# Resize blobs corresponding to deconvolutions
interp_layers = [k for k in solver.net.params.keys() if 'up' in k]
surgery.interp(solver.net, interp_layers)

# Copy the filters of RGB input to the first 3 filters of the RGBD CNN input
solver.net.params['conv1_1_bgrd'][0].data[:, :3] = base_net.params['conv1'][0].data
# Initialize the depth channel filter weights with the average of the RGB weights
solver.net.params['conv1_1_bgrd'][0].data[:, 3] = np.mean(base_net.params['conv1'][0].data, axis=1)
# Copy the filter bias terms
solver.net.params['conv1_1_bgrd'][1].data[...] = base_net.params['conv1'][1].data

del base_net

# Train
solver.solve()


import time
import numpy as np
from sklearn import svm

from robo.task.base_task import BaseTask

class SupportVectorMachineTask(BaseTask):

    def __init__(self, train, train_targets,
                     valid, valid_targets,
                     test, test_targets,
                 multi_task=False, with_costs=False, fabolas_task=False):
        """
        Hyperparameter optimization task to optimize the regularization
        parameter C and the kernel parameter gamma of a support vector machine.
        Both hyperparameters are optimized on a log scale [-10, 10].

        The test dataset is only used for a final offline evaluation of
        a configuration. For that the validation and training data is
        concatenated to form the whole training dataset.

        MultiTaskBO: 1/4 of the training data is used for the auxillary task
        Fabolas: The dataset size s is also optimized on a
                log scale [s_min, s_max], where s_min is 10 * the number of
                classes and s_max is the number of datapoints of the whole
                training dataset.

        Parameters
        ----------
        train : np.ndarray(N, D)
            Training data
        train_targets : np.ndarray(N, 1)
            Labels of the training data
        valid : np.ndarray(N, D)
            Validation data that is used to optimize the hyperparameters
        valid targets: np.ndarray(N, 1)
            Labels of the validation data
        test : np.ndarray(N, D)
            Test data that is used for an offline evaluation of a configuration
        test targets: np.ndarray(N, 1)
            Labels of the test data
        multi_task: bool
            True means that we consider the multitask BO case with one
            auxillary task and one primary task
        fabolas_task: bool
            If true than we optimize across different subsets. See the paper
            for more explaination.
        with_costs: bool
            If true, than also the the time (seconds) that was needed for
            evaluation is returned.

        """
        X_lower = np.array([-10, -10])
        X_upper = np.array([10, 10])

        self.multi_task = multi_task
        self.with_costs = with_costs
        self.fabolas_task = fabolas_task
        self.train = train
        self.train_targets = train_targets
        self.valid = valid
        self.valid_targets = valid_targets
        self.test = test
        self.test_targets = test_targets

        if self.fabolas_task:
            #Use 10 time the number of classes as lower bound
            self.n_classes = np.unique(self.train_targets).shape[0]

            self.s_min = np.log(10 * self.n_classes)
            self.s_max = np.log(self.train_targets.shape[0])
            X_lower = np.concatenate((X_lower,
                                  np.array([self.s_min])))
            X_upper = np.concatenate((X_upper,
                                  np.array([self.s_max])))
            self.is_env = np.array([0, 0, 1])

        if self.multi_task:
            # Add dimension for the tasks
            X_lower = np.concatenate((X_lower,
                                  np.array([0])))
            X_upper = np.concatenate((X_upper,
                                  np.array([1])))
            # The auxillary task consists of 1/4 of the original data set
            self.auxillary_task_size = int(self.train.shape[0] * 0.25)
            self.is_env = np.array([0, 0, 1])
        super(SupportVectorMachineTask, self).__init__(X_lower, X_upper)

    def objective_function(self, x):
        start_time = time.time()
        if self.multi_task:
            # Evaluate the config on the auxillary task
            if np.round(x[0, -1]) == 0:

                train = self.train[:self.auxillary_task_size]
                train_targets = self.train_targets[:self.auxillary_task_size]

                err = self._train_and_validate(x[:, :2], train, train_targets,
                                  self.valid, self.valid_targets)
            # Evaluate on whole data set
            elif np.round(x[0, -1]) == 1:
                err = self._train_and_validate(x[:, :2], self.train, self.train_targets,
                                  self.valid, self.valid_targets)

        elif self.fabolas_task:

            size = int(np.exp(x[0, -1]))
            shuffle = np.random.permutation(np.arange(int(np.exp(self.s_max))))

            train = self.train[shuffle[:size]]
            train_targets = self.train_targets[shuffle[:size]]

            i = 0
            # Check if we have a sample of each class in the subset
            while True:
                if (np.unique(train_targets).shape[0] == self.n_classes):
                    break
                shuffle = np.random.permutation(np.arange(int(np.exp(self.s_max))))
                train = self.train[shuffle[:size]]
                train_targets = self.train_targets[shuffle[:size]]
                i += 1
                # Sanity check if we can actually find a valid shuffled split
                if i == 20:
                    raise("Couldn't find a valid split that contains a \
                    sample from each class after 20 iterations. \
                    Maybe increase your bounds!")

            err = self._train_and_validate(x[:, :2], train, train_targets,
                                  self.valid, self.valid_targets)

        else:
            err = self._train_and_validate(x, self.train, self.train_targets,
                                  self.valid, self.valid_targets)

        if self.with_costs:
            t = time.time() - start_time
            return err, np.array([[t]])
        else:
            return err

    def _train_and_validate(self, x, train, train_targets, valid, valid_targets):
        C = np.exp(float(x[0, 0]))
        gamma = np.exp(float(x[0, 1]))

        clf = svm.SVC(gamma=gamma, C=C)

        clf.fit(train, train_targets)
        y = 1 - clf.score(valid, valid_targets)
        y = np.log(y)
        return np.array([[y]])

    def objective_function_test(self, x):
        if self.multi_task:
            x_ = x[:, :2]
        elif self.fabolas_task:
            x_ = x[:, :2]
        else:
            x_ = x

        # Concatenate training and validation data
        train = np.concatenate((self.train, self.valid), axis=0)
        train_targets = np.concatenate((self.train_targets,
                                        self.valid_targets), axis=0)
        return self._train_and_validate(x_, train, train_targets,
                                        self.test, self.test_targets)


"""
1103:分糖果
排排坐，分糖果。
我们买了一些糖果 candies，打算把它们分给排好队的 n = num_people 个小朋友。
给第一个小朋友 1 颗糖果，第二个小朋友 2 颗，依此类推，直到给最后一个小朋友 n 颗糖果。
然后，我们再回到队伍的起点，给第一个小朋友 n + 1 颗糖果，第二个小朋友 n + 2 颗，依此类推，直到给最后一个小朋友 2 * n 颗糖果。
重复上述过程（每次都比上一次多给出一颗糖果，当到达队伍终点后再次从队伍起点开始），直到我们分完所有的糖果。注意，就算我们手中的剩下糖果数不够（不比前一次发出的糖果多），这些糖果也会全部发给当前的小朋友。
返回一个长度为 num_people、元素之和为 candies 的数组，以表示糖果的最终分发情况（即 ans[i] 表示第 i 个小朋友分到的糖果数）。
示例 1：
输入：candies = 7, num_people = 4
输出：[1,2,3,1]
解释：
第一次，ans[0] += 1，数组变为 [1,0,0,0]。
第二次，ans[1] += 2，数组变为 [1,2,0,0]。
第三次，ans[2] += 3，数组变为 [1,2,3,0]。
第四次，ans[3] += 1（因为此时只剩下 1 颗糖果），最终数组变为 [1,2,3,1]。
示例 2：
输入：candies = 10, num_people = 3
输出：[5,2,3]
解释：
第一次，ans[0] += 1，数组变为 [1,0,0]。
第二次，ans[1] += 2，数组变为 [1,2,0]。
第三次，ans[2] += 3，数组变为 [1,2,3]。
第四次，ans[0] += 4，最终数组变为 [5,2,3]。
提示：
1 <= candies <= 10^9
1 <= num_people <= 1000
来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/distribute-candies-to-people
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""
'''
1、累计求和算出共有几次操作
2、通过操作数计算循环次数
3、循环外的剩余糖果数依次分发
'''
class Solution:
    def distributeCandies(self, candies: int, num_people: int):
        sum = 0
        result = [0] * num_people
        temp = 1
        i = 0
        while sum < candies :
            result[i % num_people] += temp
            sum += temp
            temp += 1
            i += 1
            if i == num_people:
                i = 0
        result[i-1] -= sum - candies
        return result

    #简化上面，但是更慢
    def distributeCandies(self, candies: int, num_people: int):
        result = [0] * num_people
        i = 0
        while candies != 0:
            result[i % num_people] += min(i + 1, candies)
            candies -= min(i + 1, candies)
            i += 1
        return result

s=Solution()
print(s.distributeCandies(10,3))
# print(s.distributeCandies(10,3))
# print(s.distributeCandies(5,3))


n=int(input())

phonebook={}

for i in range(n):
    name,phonenum=input().strip().split(' ')
    phonebook[name]=phonenum

for i in range(n):
    search=input()
    if (search in phonebook):
        print (search+'='+phonebook[search])
    else:
        print ('Not found')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Copyright (c) 2020 Ondrej Kyjanek <ondrej.kyjanek@gmail.com>
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse MIT license
# which accompanies this distribution.
#
# Contributors:
#    Ondrej Kyjanek - initial implementation

# This shows a simple example of a request/response pattern with MQTT.
# First start the Responser (python 03_responser.py) and then the Requester (python 03_requester.py)
# Runs forever. To stop press ctrl+c

import paho.mqtt.properties as properties
import paho.mqtt.client as mqttc
import time
from collections import deque
import uuid
import logging

logging.basicConfig(level=logging.DEBUG)

HOST = "localhost"
PORT = 1883
TOPIC = "ITECH_COM_2020/service"

msg_queue = deque()

def on_message(client, userdata, message):
    logging.info("Received request on: {} with correlation data: {}".format(message.topic, message.properties.CorrelationData))
    msg_queue.append(message)

user_id = "res-"+uuid.uuid4().hex[:16]
res_client = mqttc.Client(user_id,userdata=user_id, protocol=mqttc.MQTTv5)
res_client.enable_logger(logging.getLogger())
res_client.connect(HOST,PORT)
res_client.on_message = on_message
res_client.loop_start()
res_client.subscribe([(TOPIC+"/req",2)])
logging.info("Client started")

try:
    while True:
        if len(msg_queue)>0:
            request = msg_queue.popleft()
            logging.info("Request payload: {}".format(request.payload))
            res_client.publish(
                request.properties.ResponseTopic,
                payload="Response to: {}".format(request.payload.decode('utf-8')),
                properties=request.properties)
        else:
            time.sleep(0.01)

except KeyboardInterrupt:
    logging.info("Ctrl+c pressed")
except Exception as e:
    logging.error(e)
finally:
    res_client.disconnect()
    time.sleep(2)
    res_client.loop_stop()
    logging.info("Client stopped")


#!/usr/bin/env python

import argparse
import csv
import sys
import time

parser = argparse.ArgumentParser()
parser.add_argument('-p', default='')
parser.add_argument('--path', default='imdb/')
parser.add_argument('-db', default='films')
args = parser.parse_args(sys.argv[1:])

# Actor
file = open(args.path + 'actor.tsv','w')
print("> Openning file Actors")
with open(args.path + 'name.basics.tsv', 'r') as csvfile:
	actores = csv.reader(csvfile, delimiter='\t')
	print("    % Success")
	print("> Writing File Actors")
	first = 1
	for row in actores:
		if first == 1:
			first = 0
			continue
		info = (int(row[0][2:]),row[1])
		file.write("%s\t%s\n" % info)
	print("    % Success")
file.close()

# Film
# First retrieve ratings into a dictionary
film_rating = {}
with open(args.path + 'title.ratings.tsv', 'r') as csvfile:
	csvfile.readline()
	ratings = csv.reader(csvfile, delimiter='\t')
	for row in ratings:
		film_rating[int(row[0][2:])] = (float(row[1]), int(row[2]))

file = open(args.path + 'film.tsv','w')
file2 = open(args.path + 'genre.tsv','w')
file3 = open(args.path + 'genre_group.tsv','w')
print("> Openning file Films")
with open(args.path + 'title.basics.tsv', 'r') as csvfile:
	films = csv.reader(csvfile, delimiter='\t')
	print("    % Success")
	print("> Writing File Film")
	first = 1
	for row in films:
		if first == 1:
			first = 0
			continue
		if row[1] != 'movie':
			continue
		year = 0
		if row[5] != '0' and not '\\N' in row[5]:
			year = int(row[5])
		elif not '\\N' in row[6]:
			year = int(row[6])
		duration = 0
		if not '\\N' in row[7]:
			duration = int(row[7])
		id_pelicula = int(row[0][2:])
		if not id_pelicula in film_rating:
			film_rating[id_pelicula] = (0.0, 0)
		info = (id_pelicula,row[2].replace('\'','\\\''),year,duration,film_rating[id_pelicula][0], film_rating[id_pelicula][1])
		file.write("%s\t%s\t%s\t%s\t%s\t%s\n" % info)
		genres = row[8].split(',')
		for genre in genres:
			file2.write("%s\n" % (genre,))
			file3.write("%s\t%s\n" % (genre,id_pelicula))
	print("    % Success")
file.close()
file2.close()
file3.close()

# film_cast
file = open(args.path + 'film_cast.tsv','w')
print("> Openning file Film_Cast")
with open(args.path + 'title.principals.tsv', 'r') as csvfile:
	actores = csv.reader(csvfile, delimiter='\t')
	print("    % Success")
	print("> Writing File film_cast")
	first = 1
	for row in actores:
		if first == 1:
			first = 0
			continue
		if row[3] == 'actor' or row[3] == 'actress':
			info = (int(row[2][2:]),int(row[0][2:]),row[5][2:-2])
			file.write("%s\t%s\t%s\n" % info)
	print("    % Success")
file.close()

id_ml_imdb = {}
print("> Openning file links")
with open(args.path + 'links.csv', 'r') as csvfile:
	movies = csv.reader(csvfile, delimiter=',')
	print("    % Success")
	print("> Searching IDs")
	first = 1
	for row in movies:
		if first == 1:
			first = 0
			continue
		id_ml = int(row[0])
		id_imdb = int(row[1])
		id_ml_imdb[id_ml] = id_imdb
	csvfile.close()

# Ratings
file_rat = open(args.path + 'ratings.tsv','w')
file_us = open(args.path + 'users.tsv','w')
file_time = open(args.path + 'timestamp.tsv','w')
print("> Openning file Film_Cast")
with open(args.path + 'ratings.csv', 'r') as csvfile:
	ratings = csv.reader(csvfile, delimiter=',')
	print("    % Success")
	print("> Writing File ratings")
	first = 1
	user_prev = 0
	count = 1
	for row in ratings:
		if first == 1:
			first = 0
			continue
		user_id = int(row[0])
		movie_id = int(row[1])
		rating = float(row[2])
		time_epoch = int(row[3])
		tm = time.localtime(time_epoch)
		if user_prev != user_id:
			file_us.write("%s\n" % (user_id,))
			user_prev = user_id
		file_time.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (count,tm.tm_mday, tm.tm_mon, tm.tm_year, tm.tm_hour, tm.tm_min, tm.tm_sec))
		file_rat.write("%s\t%s\t%s\t%s\n" % (id_ml_imdb[movie_id],user_id,count,rating))
		count = count + 1

file_rat.close()
file_us.close()
file_time.close()

'''
##########################################
Example of query for the bridge table:
##########################################
    select F.title, A.name
    FROM actor A
    JOIN film_cast B
    ON A.actor_ID = B.actor_ID
    JOIN film F
    ON F.film_ID = B.film_ID
    WHERE F.title LIKE 'Thor';
##########################################
    select F.title, G.name
	FROM genre G
	JOIN genre_group B
	ON G.name = B.genre_name
	JOIN film F
	ON F.film_ID = B.film_ID
	where F.title LIKE 'Jumanji';
##########################################
'''


import pandas as pd
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.autograd.variable import Variable
from torchvision import transforms, datasets
import torchvision.datasets as dsets
import matplotlib.pyplot as plt
import torchvision.utils as vutils
import numpy as np

# configure training config
num_epochs = 50
batch_size = 100
img_size = 784
dis_output_size = 1
z_size = 128
lr = 0.0002
loss = nn.BCELoss()

class Discriminator(nn.Module):

    def __init__(self):
        super(Discriminator, self).__init__()

        # define network
        self.fc1 = nn.Sequential(
            nn.Linear(img_size, 512),
            nn.LeakyReLU(0.2)
        )
        self.fc2 = nn.Sequential(
            nn.Linear(512, 256),
            nn.LeakyReLU(0.2)
        )
        self.fc3 = nn.Sequential(
            nn.Linear(256, dis_output_size),
            torch.nn.Sigmoid()
        )

    def forward(self, x):
        x = self.fc1(x)
        x = self.fc2(x)
        x = self.fc3(x)

        return x

class Generator(nn.Module):

    def __init__(self):
        super(Generator, self).__init__()

        # define network
        self.fc1 = nn.Sequential(
            nn.Linear(z_size, 256),
            nn.LeakyReLU(0.2)
        )
        self.fc2 = nn.Sequential(
            nn.Linear(256, 512),
            nn.LeakyReLU(0.2)
        )
        self.fc3 = nn.Sequential(
            nn.Linear(512, img_size),
            nn.Tanh()
        )

    def forward(self, x):
        x = self.fc1(x)
        x = self.fc2(x)
        x = self.fc3(x)

        return x

def plot_losses(gen_loss, dis_losses):
    # plot losses vs epochs
    plt.plot(range(len(gen_loss)+1)[1:], gen_loss, label="Generator loss")
    plt.plot(range(len(gen_loss)+1)[1:], dis_losses, label="Discriminator loss")
    plt.title("Loss vs Epochs")
    plt.xlabel('Loss')
    plt.ylabel('Epochs')
    plt.legend()
    plt.show()

def plot_generated_images(images_gen):
    # plot the figures
    for imgs in images_gen:
        horizontal_grid = vutils.make_grid(imgs, normalize=True, scale_each=True,nrow=4)
        fig = plt.figure(figsize=(4, 4))
        plt.imshow(np.moveaxis(horizontal_grid.detach().numpy(), 0, -1))
        plt.show()

def train_discriminator(discriminator, optimizer, real_data, fake_data, noise_decay):
    # reset gradients
    optimizer.zero_grad()

    # initializing real data with noise * decay
    noise1 = noise_decay * torch.distributions.Uniform(0,1).sample_n(real_data.size(0)*img_size).view(real_data.size(0),img_size)
    noise2 = noise_decay * torch.distributions.Uniform(0,1).sample_n(real_data.size(0)*img_size).view(real_data.size(0),img_size)

    prediction_real = discriminator(real_data+noise1)

    # calculate error and backpropagate, using label smoothing
    error_real = loss(prediction_real, Variable(torch.ones(real_data.size(0), 1)*0.9))
    error_real.backward()

    # initializing fake data with noise * decay
    prediction_fake = discriminator(fake_data+noise2)

    # calculate error and backpropagate
    error_fake = loss(prediction_fake, Variable(torch.zeros(real_data.size(0), 1)))
    error_fake.backward()

    # update weights
    optimizer.step()

    return error_real + error_fake, prediction_real, prediction_fake

def train_generator(discriminator, optimizer, fake_data, noise_decay):
    # reset gradients
    optimizer.zero_grad()

    # initializing fake data with noise * decay
    noise = noise_decay * torch.distributions.Uniform(0,1).sample_n(fake_data.size(0)*img_size).view(fake_data.size(0),img_size)
    prediction = discriminator(fake_data+noise)

    # calculate error and backpropagate, using label smoothing
    error = loss(prediction, torch.ones(fake_data.size(0), 1)*0.9)
    error.backward()

    # update weights
    optimizer.step()

    return error

def train_GAN(train_loader):
    # initialization
    dis_losses = []
    gen_losses = []
    images_gen = []
    discriminator = Discriminator()
    generator = Generator()

    dis_optimizer = optim.Adam(discriminator.parameters(), lr)
    gen_optimizer = optim.Adam(generator.parameters(), lr)

    for epoch in range(num_epochs):
        avg_gen_loss = 0
        avg_dis_loss = 0
        noise_decay = 0

        for n_batch, (real_batch,_) in enumerate(train_loader, 0):
            # decaying noise
            noise_decay = 0.1*noise_decay

            N = real_batch.size(0)

            # vecorize image
            real_data = Variable(real_batch.view(N, img_size))

            # generate fake data
            fake_data = generator(Variable(torch.randn(N, 128))).detach()

            # train Discriminator
            dis_loss, d_pred_real, d_pred_fake = train_discriminator(discriminator, dis_optimizer, real_data, fake_data, noise_decay)

            # generate fake data, with random z
            fake_data = generator(Variable(torch.randn(N, 128)))

            # train Generator
            gen_loss = train_generator(discriminator, gen_optimizer, fake_data, noise_decay)

            avg_gen_loss += gen_loss.item()
            avg_dis_loss += dis_loss.item()

        gen_losses.append(avg_gen_loss)
        dis_losses.append(dis_loss)

        if (epoch+1) % 10 == 0:
            # generate images using generator
            fake_data = generator(Variable(torch.randn(16, 128)))
            images_gen.append(fake_data.view(fake_data.size(0), 1, 28, 28))

    return generator, discriminator, gen_losses, dis_losses, images_gen

if __name__ == "__main__":
    data = dsets.MNIST(root='./data',
                                train=True,
                                transform=transforms.ToTensor(),
                                download=True)
    train_loader = torch.utils.data.DataLoader(data, batch_size=100, shuffle=True)

    generator, discriminator, gen_losses, dis_losses, images_gen  = train_GAN(train_loader)
    torch.save(generator, "hw5_gan_gen.pth")
    torch.save(discriminator, "hw5_gan_dis.pth")

    plot_losses(gen_losses, dis_losses)
    plot_generated_images(images_gen)


import shutil
from collections import OrderedDict
from os.path import join, basename

from variant_filtering.vcf import vcf_one_per_line, get_sample_column_index, vcf_parser

from ngs_utils.file_utils import intermediate_fname, splitext_plus, file_transaction, file_exists
from ngs_utils.logger import step_greetings, info, warn

def make_tsv(cnf, vcf_fpath, samplename, main_sample_index=None):
    step_greetings('Exporting to TSV...')

    vcf_fpath = vcf_one_per_line(cnf, vcf_fpath)

    if main_sample_index is None:
        main_sample_index = get_sample_column_index(vcf_fpath, samplename) or 0

    tsv_fpath = _extract_fields(cnf, vcf_fpath, samplename, main_sample_index)
    if not tsv_fpath:
        return tsv_fpath

    return tsv_fpath

def _extract_fields(cnf, vcf_fpath, samplename, main_sample_index=0):
    fname, _ = splitext_plus(basename(vcf_fpath))
    tsv_fpath = join(cnf.work_dir, fname + '.tsv')

    if cnf.get('reuse_intermediate'):
        if file_exists(tsv_fpath):
            info(tsv_fpath + ' exists, reusing')
            return tsv_fpath

    manual_tsv_fields = cnf.annotation['tsv_fields']
    if not manual_tsv_fields:
        return None

    all_fields = []
    basic_fields = []
    info_fields = []
    eff_fields = []
    gt_fields = []
    tumor_gt = 'GEN[' + str(main_sample_index) + '].'
    normal_gt = 'GEN[' + str(1 - main_sample_index) + '].'

    lines = []

    with open(vcf_fpath) as inp:
        reader = vcf_parser.Reader(inp)

        info('TSV saver: Building field list')
        for f in [list(rec.keys())[0] for rec in manual_tsv_fields]:
            if f.startswith('GEN'):
                _f = f.split('.')[1]
                if len(reader.samples) > 0:
                    if _f in reader.formats:
                        gt_fields.append(_f)
                        all_fields.append(f.replace('GEN[*].', tumor_gt))
                        if len(reader.samples) > 1:
                            all_fields.append(f.replace('GEN[*].', normal_gt))
                else:
                    warn('TSV Saver: Warning: ' + f + ' is not in VCF header FORMAT records')

            elif f in ['CHROM', 'POS', 'REF', 'ALT', 'ID', 'FILTER', 'QUAL']:
                all_fields.append(f)
                basic_fields.append(f)

            elif any(f.startswith(af) and af in reader.infos for af in ['EFF', 'ANN']):
                all_fields.append(f)
                eff_fields.append(f)

            else:
                if f in reader.infos:
                    info_fields.append(f)
                    all_fields.append(f)
                elif f == 'SAMPLE':
                    all_fields.append(f)
                else:
                    warn('TSV Saver: Warning: ' + f + ' is not in VCF header INFO records')

        info('TSV saver: Iterating over records...')
        d = OrderedDict()
        for rec in reader:
            for f in basic_fields:
                d[f] = rec.__dict__[f]

            for f in info_fields:
                d[f] = rec.INFO[f] if f in rec.INFO else ''

            if 'SAMPLE' not in d:
                d['SAMPLE'] = samplename

            if eff_fields:
                eff = rec.INFO.get(eff_fields[0][:3])
                if not eff:
                    for f in eff_fields:
                        d[f] = ''
                else:
                    eff_fs = eff[0].split('|')
                    eff_d = dict()
                    for val, header in zip(eff_fs, ['ALLELE', 'EFFECT', 'IMPACT', 'GENE', 'GENEID', 'FEATURE', 'FEATUREID', 'BIOTYPE', 'RANK', 'HGVS_C', 'HGVS_P', 'CDNA_POSLEN', 'CDS_POSLEN', 'AA_POSLEN', 'DISTANCE', 'LOG']):
                        if 'POSLEN' in header:
                            eff_d[header.split('_')[0] + '_POS'] = val.split('/')[0] if val else ''
                            eff_d[header.split('_')[0] + '_LEN'] = val.split('/')[1] if val else ''
                        else:
                            eff_d[header] = val
                    #ANN=GA |3_prime_UTR_variant|MODIFIER|RPL22|RPL22|transcript|NM_000983.3|Coding|4/4|c.*173dupT|||||173|;
                    #Allele | Annotation | Annotation_Impact | Gene_Name | Gene_ID | Feature_Type | Feature_ID | Transcript_BioType | Rank | HGVS.c | HGVS.p | cDNA.pos / cDNA.length | CDS.pos / CDS.length | AA.pos / AA.length | Distance | ERRORS / WARNINGS / INFO'
                    for f in eff_fields:
                        d[f] = eff_d[f.split('.')[1]]

            if rec.FORMAT:
                for _f in gt_fields:
                    if _f in rec.FORMAT:
                        d[tumor_gt + _f] = rec.samples[main_sample_index][_f]
                        if len(rec.samples) > 1 - main_sample_index:
                            d[normal_gt + _f] = rec.samples[1 - main_sample_index][_f]
                        else:
                            d[normal_gt + _f] = ''
                    else:
                        d[tumor_gt + _f] = ''
                        d[normal_gt + _f] = ''

            fs = []
            for f in all_fields:
                v = d[f]
                fs.append(v if v != '.' else '')
            lines.append(fs)

    info('TSV saver: Adding GEN[*] fields both for sample and for matched normal...')
    field_map = dict()
    for rec in manual_tsv_fields:
        k = list(rec.keys())[0]
        v = list(rec.values())[0]
        if k.startswith('GEN[*].'):
            _f = k.split('.')[1]
            field_map[tumor_gt + _f] = v
            field_map[normal_gt + _f] = 'Matched_' + v
        else:
            field_map[k] = v

    info('TSV saver: Writing TSV to ' + tsv_fpath)
    with file_transaction(cnf.work_dir, tsv_fpath) as tx:
        with open(tx, 'w') as out:
            out.write('\t'.join(field_map[f] for f in all_fields) + '\n')
            for fs in lines:
                new_fs = []
                for f in fs:
                    if isinstance(f, list):
                        new_fs.append(','.join(map(str, f)))
                    elif f is None:
                        new_fs.append('')
                    else:
                        new_fs.append(str(f))
                out.write('\t'.join(new_fs) + '\n')

    info('TSV saver: saved ' + tsv_fpath)
    return tsv_fpath

def _rename_fields(cnf, inp_tsv_fpath, field_map):
    if cnf.get('keep_intermediate'):
        step_greetings('Renaming fields.')

    with open(inp_tsv_fpath) as f:
        first_line = f.readline()
    fields = first_line.split()
    new_fields = [field_map.get(f) or f for f in fields]
    new_first_line = '\t'.join(new_fields)

    if cnf.get('keep_intermediate'):
        out_tsv_fpath = intermediate_fname(cnf, inp_tsv_fpath, 'renamed')
    else:
        out_tsv_fpath = inp_tsv_fpath

    with file_transaction(cnf.work_dir, out_tsv_fpath) as tx_out_fpath:
        with open(tx_out_fpath, 'w') as out:
            out.write(new_first_line + '\n')
            with open(inp_tsv_fpath) as f:
                for i, l in enumerate(f):
                    if i >= 1:
                        out.write(l)

    if not cnf.get('keep_intermediate'):
        shutil.move(out_tsv_fpath, inp_tsv_fpath)
        return inp_tsv_fpath
    else:
        return out_tsv_fpath


import os
import importlib
import importlib.machinery
import inspect
import torch
import json
import errno
import warnings

class ModelStorage(object):
    """ ModelStorage represents a storage object for PyTorch models with a
    corresponding folder and configuration file where the models are stored.
    """
    def __init__(self, path='.', exhaustive=True, override=False):
        """
        :param path: path to the folder where the storage is [to be] located
        :param use_relative: defines if the relative imports are considered when storing the source code
        :param override: if True, allows the creation of a new ModelStorage in a folder that already contains an initialized ModelStorage
        """
        self.path = path
        self.source_path = os.path.join(path, 'source.py')
        self.config_path = os.path.join(path, 'config.json')

        self.loaded = False
        self.saved = False
        self.models = []

        self.cfg = dict()
        self.cfg['exhaustive'] = exhaustive
        self.cfg['defined'] = []
        self.cfg['model_list'] = []
        self.cfg['checkpoint_list'] = []
        self.cfg['extra_imports'] = []

        if not os.path.exists(self.path):
            try:
                os.makedirs(self.path)
            except OSError as exc:
                if exc.errno != errno.EEXIST:
                    raise RuntimeError('Couldn\'t create the necessary directory structure')
        else:
            if not override:
                self._read_config()
                self._import_config()

    @staticmethod
    def from_folder(path):
        """
        Recreates a ModelStorge given a directory folder of a previously initialized ModelStorage
        :param path: path to the directory
        :return:
        """
        st = ModelStorage(path=path, override=False)
        return st

    def clear(self):
        """
        Clears the model storage. Does not delete any weight files
        :return: None
        """
        self.cfg = {}
        self.models = []
        self.loaded = False
        self.saved = False

    def set_description(self, desc):
        self.cfg['description'] = desc

    def get_description(self):
        return self.cfg.get('description', '')

    def add_extra_import(self, extra_imports):
        if type(extra_imports) is not list:
            extra_imports = [extra_imports]
        for imp in extra_imports:
            self.cfg['extra_imports'].append(imp)

    # ---------------------- Saving methods ------------------------

    def add(self, new, rename_to=None):
        """ Stores the provided models in the ModelStorage
        :param new: model or list of models to add to the ModelStorage
        :param rename_to: optionally provided list of tuples (old, new) to rename any class with the name 'old' to 'new'
        :return:
        """
        try:
            for i in iter(new):
                self.models.append(i)
        except TypeError:
            self.models.append(new)

        if len(self.models) > 0:
            self.loaded = True
            class_list = []
            for m in self.models:
                class_list.append(m.__class__.__name__)
            self.cfg['model_list'] = class_list
        self.save()

    def _make_filename(self, model, name):
        if not isinstance(model, str):
            model = model.__class__.__name__
        return os.path.join(self.path, model + '_' + name + '.chk')

    def _save_config(self):
        with open(self.config_path, 'w+') as f:
            json.dump(self.cfg, f)

    @staticmethod
    def _save_module(net, path):
        torch.save(net.state_dict(), path)

    def save(self):
        """
        Saves the configuration file, sources of the models and the current model weights as the default weight.
        Overrides the previous default weights.
        :return: None
        """
        self.save_checkpoint('default')

    def save_checkpoint(self, name):
        """
        Saves the current weights of the model as a new, named checkpoint
        :param name: name of the checkpoint to be retrieved later
        :return: None
        """

        if not self.loaded:
            warnings.warn('ModelStorage saved without any stored model')

        self.cfg['checkpoint_list'].append(name)
        self._save_config()

        for mdl in self.models:
            path = self._make_filename(mdl, name)
            self._save_module(mdl, path)

        if not self.saved:
            self._save_sources()
            self.saved = True

    def _save_sources(self):
        if not self.loaded:
            return

        final_source, visited, defined = extract_sources(self.models, self.cfg['extra_imports'], self.cfg['exhaustive'])
        with open(self.source_path, 'w+') as source_file:
            source_file.write(final_source)

        self.cfg['visited'] = list(visited)
        self.cfg['defined'] = list(defined)

    # ---------------------- Loading methods ------------------------

    def _read_config(self):
        """
        Reads the configuration file of the directory in which the ModelStorage was initialized in
        :return: None
        """
        with open(self.config_path, 'r+') as f:
            self.cfg = json.load(f)

    def _import_config(self):
        mod = self._dynamic_load_source()
        self.models.clear()
        for m in self.cfg['model_list']:
            class_ = getattr(mod, m)
            self.models.append(class_())
        if len(self.models) > 1:
            self.loaded = True

    def get_model_list(self):
        return self.models

    def get(self, models=None):
        """
        Retrieves the stored models in the same order as stored, or as requested in the models parameter, with the
         default weights
        :param models: when provided, specifies the model(s) to be retrieved and their order. Must be iterable
        :return: the stored models
        """
        return self.get_checkpoint('default', models)

    def get_checkpoint(self, name, models=None):
        """
        Retrieves the stored models in the same order as stored, or as requested in the models parameter, with the
         weights of the named checkpoint provided
        :param name: name of the checkpoint to retrieve
        :param models: when provided, specifies the model(s) to be retrieved and their order. Must be iterable
        :return: the stored models with the checkpoint weights loaded
        """
        if len(self.cfg['model_list']) == 0:
            warnings.warn('Checkpoint requested for empty ModelStorage. Pre-existing Storages should be loaded using ModelStorage.from_folder(path)')
            return None

        to_retrieve = self.models
        if models is not None:
            to_retrieve = []
            # Could be simpler, but the order of the retrieved models should match the models argument
            if type(models) is not list:
                models = [models]
            for cls in models:
                for m in self.models:
                    if m.__class__.__name__ == cls:
                        to_retrieve.append(m)
                        break
            if len(to_retrieve) != len(models):
                raise Exception('Not all requested models were found in the ModelStorage')
        for m in to_retrieve:
            file_path = self._make_filename(m, name)
            self._load_module_state(m, file_path)

        if len(to_retrieve) > 1:
            return tuple(to_retrieve)
        return to_retrieve[0]

    @staticmethod
    def _load_module_state(net, filename):
        net.load_state_dict(torch.load(filename))
        return net

    def _dynamic_load_source(self):
        loader = importlib.machinery.SourceFileLoader('source', self.source_path)
        mod = loader.load_module()
        return mod

def _is_relative(imp):
    if imp.startswith(('from', 'import')) and imp.split()[1].startswith('.'):
        return True
    return False

def _extract_imports(filename):
    imports = []
    with open(filename, 'r+') as file:
        for line in file.readlines():
            if line.startswith(('from', 'import')):
                imports.append(line)
    return imports

def _get_relative_module(imp, parent):
    relative_mod = imp.split()[1]
    root = '.'.join(parent.__name__.split('.')[:-1])
    return importlib.import_module(relative_mod, root)

def _extract_module_source(mod, visited, defined):
    sources = []

    src_path = inspect.getsourcefile(mod)
    if src_path in visited:
        return [], set()
    visited.add(src_path)

    imports = set()
    for imp in set(_extract_imports(src_path)):
        if _is_relative(imp):
            rel_mod = _get_relative_module(imp, mod)
            extra, imps = _extract_module_source(rel_mod, visited, defined)
            sources = sources + extra
            imports.update(imps)
        else:
            imports.add(imp)

    for name, obj in inspect.getmembers(mod):
        if inspect.isclass(obj) and name not in defined:
            if inspect.getsourcefile(obj) == src_path:
                src = inspect.getsource(obj)
                sources.append(src)
                defined.append(name)

    return sources, imports

def extract_sources(nets, extra_imports=None, exhaustive=True):
    final_source = ''
    sources = []
    defined = []
    imports = set()
    visited = set()

    for net in nets:
        if exhaustive:
            mod = inspect.getmodule(net)
            mod_sources, mod_imports = _extract_module_source(mod, visited, defined)
            sources = sources + mod_sources
            imports.update(mod_imports)
        else:
            src = inspect.getsource(net.__class__)
            src_path = inspect.getsourcefile(net.__class__)
            sources.append(src)
            imports.update(_extract_imports(src_path))

    for imp in sorted(imports, reverse=True):
        final_source += imp
    if extra_imports is not None:
        for imp in extra_imports:
            final_source += imp

    final_source += '\n'
    for cl in sources:
        final_source += cl + '\n\n'

    return final_source, visited, defined


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Labstep <dev@labstep.com>

from labstep.generic.entity.model import Entity
from labstep.constants import UNSPECIFIED

class EntityWithMetadata(Entity):
    def addMetadata(
        self,
        fieldName,
        fieldType="default",
        value=UNSPECIFIED,
        date=UNSPECIFIED,
        number=UNSPECIFIED,
        unit=UNSPECIFIED,
        filepath=UNSPECIFIED,
        extraParams={},
    ):
        """
        Add Metadata to a Labstep Entity.

        Parameters
        ----------
        fieldName (str)
            The name of the field.
        fieldType (str)
            The Metadata field type. Options are: "default", "date",
            "numeric", or "file". The "default" type is "Text".
        value (str)
            The value accompanying the fieldName entry.
        date (str)
            The date accompanying the fieldName entry. Must be
            in the format of "YYYY-MM-DD HH:MM".
        number (float)
            The numeric value.
        unit (str)
            The unit accompanying the number entry.
        filepath (str)
            Local path to the file to upload for type 'file'

        Returns
        -------
        :class:`~labstep.entities.metadata.model.Metadata`
            An object representing the new Labstep Metadata.

        Example
        -------
        ::

            resource = user.getResource(17000)
            metadata = resource.addMetadata("Refractive Index",
                                               value="1.73")
        """
        import labstep.entities.metadata.repository as metadataRepository

        return metadataRepository.addMetadataTo(
            self,
            fieldName=fieldName,
            fieldType=fieldType,
            value=value,
            date=date,
            number=number,
            unit=unit,
            filepath=filepath,
            extraParams=extraParams,
        )

    def getMetadata(self):
        """
        Retrieve the Metadata of a Labstep Entity.

        Returns
        -------
        :class:`~labstep.entities.metadata.model.Metadata`
            An array of Metadata objects for the Entity.

        Example
        -------
        ::

            my_resource = user.getResource(17000)
            metadatas = my_resource.getMetadata()
        """
        import labstep.entities.metadata.repository as metadataRepository

        return metadataRepository.getMetadata(self)


import numpy as np
from gensim import matutils

from Semantic_Search.utils.const import *
from Semantic_Search.utils.tools import split_phase
from config import *

'''
# The following codes refer to InferSent model
'''

def infersent_sentence2vec(sentence, model, method=INFERSENT_NAMES_METHOD, tokenize=True):
    assert model is not None

    splits = split_phase(sentence)

    if len(splits) == 0:
        logging.info('no word after split_phase in sentence: {} in model: {}!'.format(sentence, methods[method]))
        return None

    sent = ' '.join(splits)
    vec = model.encode([sent], tokenize)
    vec = matutils.unitvec(vec[0])

    return vec

'''
# The following codes refer to Google USE model
'''

def use_sentence2vec(sentence, model, method=USE_NAMES_METHOD):
    assert model is not None

    splits = split_phase(sentence)

    if len(splits) == 0:
        logging.info('no word after split_phase in sentence: {} in model: {}!'.format(sentence, methods[method]))
        return None

    sent = ' '.join(splits)

    # by USEEncoder
    vec = model([sent]).astype(np.float64)

    # by USEPredictor
    # vec = model.encode([sent])

    vec = matutils.unitvec(vec[0])

    return vec


__author__ = 'Rhys'

from app import app
from flask import jsonify
from flask.ext.login import LoginManager, AnonymousUser
from oauth import SynapseProvider
from shared.objects import SessionRU
from db.dbclasses import User

provider = SynapseProvider(app)

#Import API Handlers so that their decorators are processed by flask
from api import core

lm = LoginManager()
lm.init_app(app)

alm = LoginManager()

class Anonymous(AnonymousUser):
	name = u"Anonymous"
	stafflevel = 0
	def is_authenticated(self):
		return False

class WebUser(object):
	id = -1

	def is_authenticated(self):
		'''
		The is_authenticated method has a misleading name.
		In general this method should just return True unless the object represents a user that should not be allowed
		to authenticate for some reason.
		'''
		return True

	def is_active(self):
		'''
		The is_active method should return True for users unless they are inactive, for example because they have
		been banned.
		'''
		return True

	def is_anonymous(self):
		'''
		The is_anonymous method should return True only for fake users that are not supposed to log in to the system.
		'''
		return False

	def get_id(self):
		'''
		Finally, the get_id method should return a unique identifier for the user, in unicode format.
		We use the unique id generated by the dataBase layer for this.
		'''
		return unicode(self.id)

	def __init__(self, id):
		self.id = id

lm.anonymous_user = Anonymous

@lm.user_loader
def load_user(userId):
	db_session = SessionRU()
	user = db_session.query(User).filter(User.id == userId).first()
	if user is not None:
		webuser = WebUser(user.id)
		db_session.close()
		return webuser
	db_session.close()
	return None


class Solution:
    def solve(self, n):
        sol = []
        def check_three(i):
            s = str(i);
            for c in s:
                if(c=='3' or c=='6' or c=='9'):
                    return True
            return False
        for i in range(1,n+1):
            if(i%3==0 or check_three(i)==True):
                sol.append('clap')
            else:
                sol.append(str(i))

        return sol


# -*- coding: utf-8 -*-
# Copyright (C) 2020-2023 by SCICO Developers
# All rights reserved. BSD 3-clause License.
# This file is part of the SCICO package. Details of the copyright and
# user license can be found in the 'LICENSE' file distributed with the
# package.

"""Radon transform LinearOperator wrapping the ASTRA toolbox.

Radon transform :class:`.LinearOperator` wrapping the parallel beam
projections in the
`ASTRA toolbox <https://github.com/astra-toolbox/astra-toolbox>`_.
This package provides both C and CUDA implementations of core
functionality, but note that use of the CUDA/GPU implementation is
expected to result in GPU-host-GPU memory copies when transferring
JAX arrays. Other JAX features such as automatic differentiation are
not available.
"""

from typing import List, Optional, Tuple, Union

import numpy as np

import jax
import jax.experimental.host_callback as hcb

try:
    import astra
except ModuleNotFoundError as e:
    if e.name == "astra":
        new_e = ModuleNotFoundError("Could not import astra; please install the ASTRA toolbox.")
        new_e.name = "astra"
        raise new_e from e
    else:
        raise e

from scico.typing import Shape

from ._linop import LinearOperator

class TomographicProjector(LinearOperator):
    r"""Parallel beam Radon transform based on the ASTRA toolbox.

    Perform tomographic projection (also called X-ray projection) of an
    image or volume at specified angles, using the
    `ASTRA toolbox <https://github.com/astra-toolbox/astra-toolbox>`_.
    """

    def __init__(
        self,
        input_shape: Shape,
        detector_spacing: Union[float, Tuple[float, float]],
        det_count: Union[int, Tuple[int, int]],
        angles: np.ndarray,
        volume_geometry: Optional[List[float]] = None,
        device: str = "auto",
    ):
        """
        Args:
            input_shape: Shape of the input array. Determines whether 2D
               or 3D algorithm is used.
            detector_spacing: Spacing between detector elements. See
               https://www.astra-toolbox.com/docs/geom2d.html#projection-geometries
               or
               https://www.astra-toolbox.com/docs/geom3d.html#projection-geometries
               for more information.
            det_count: Number of detector elements. See
               https://www.astra-toolbox.com/docs/geom2d.html#projection-geometries
               or
               https://www.astra-toolbox.com/docs/geom3d.html#projection-geometries
               for more information.
            angles: Array of projection angles in radians.
            volume_geometry: Specification of the shape of the
               discretized reconstruction volume. Must either ``None``,
               in which case it is inferred from `input_shape`, or
               follow the astra syntax described in
               https://www.astra-toolbox.com/docs/geom2d.html#volume-geometries
               or
               https://www.astra-toolbox.com/docs/geom3d.html#d-geometries.
            device: Specifies device for projection operation.
               One of ["auto", "gpu", "cpu"]. If "auto", a GPU is used if
               available, otherwise, the CPU is used.
        """

        self.num_dims = len(input_shape)
        if self.num_dims not in [2, 3]:
            raise ValueError(
                f"Only 2D and 3D projections are supported, but `input_shape` is {input_shape}."
            )

        output_shape: Shape
        if self.num_dims == 2:
            output_shape = (len(angles), det_count)
        elif self.num_dims == 3:
            assert isinstance(det_count, (list, tuple))
            if len(det_count) != 2:
                raise ValueError("Expected `det_count` to have 2 elements")
            output_shape = (det_count[0], len(angles), det_count[1])

        # Set up all the ASTRA config
        self.detector_spacing = detector_spacing
        self.det_count = det_count
        self.angles: np.ndarray = np.array(angles)

        if self.num_dims == 2:
            self.proj_geom: dict = astra.create_proj_geom(
                "parallel", detector_spacing, det_count, self.angles
            )
        elif self.num_dims == 3:
            assert isinstance(detector_spacing, (list, tuple))
            assert isinstance(det_count, (list, tuple))
            if len(detector_spacing) != 2:
                raise ValueError("Expected `detector_spacing` to have 2 elements")
            self.proj_geom = astra.create_proj_geom(
                "parallel3d",
                detector_spacing[0],
                detector_spacing[1],
                det_count[0],
                det_count[1],
                self.angles,
            )

        self.proj_id: Optional[int]
        self.input_shape: tuple = input_shape

        if volume_geometry is not None:
            if (self.num_dims == 2 and len(volume_geometry) == 4) or (
                self.num_dims == 3 and len(volume_geometry) == 6
            ):
                self.vol_geom: dict = astra.create_vol_geom(*input_shape, *volume_geometry)
            else:
                raise ValueError(
                    "`volume_geometry` must be a tuple of len 4 (2D) or 6 (3D)."
                    "Please see the astra documentation for details."
                )
        else:
            if self.num_dims == 2:
                self.vol_geom = astra.create_vol_geom(*input_shape)
            elif self.num_dims == 3:
                self.vol_geom = astra.create_vol_geom(
                    input_shape[1], input_shape[2], input_shape[0]
                )

        dev0 = jax.devices()[0]
        if dev0.platform == "cpu" or device == "cpu":
            self.device = "cpu"
        elif dev0.platform == "gpu" and device in ["gpu", "auto"]:
            self.device = "gpu"
        else:
            raise ValueError(f"Invalid device specified; got {device}.")

        if self.num_dims == 3 and self.device == "cpu":
            raise ValueError("No CPU algorithm exists for 3D tomography.")

        if self.num_dims == 3:
            # not needed for astra's 3D algorithm
            self.proj_id = None
        elif self.num_dims == 2:
            if self.device == "cpu":
                self.proj_id = astra.create_projector("line", self.proj_geom, self.vol_geom)
            elif self.device == "gpu":
                self.proj_id = astra.create_projector("cuda", self.proj_geom, self.vol_geom)

        # Wrap our non-jax function to indicate we will supply fwd/rev mode functions
        self._eval = jax.custom_vjp(self._proj)
        self._eval.defvjp(lambda x: (self._proj(x), None), lambda _, y: (self._bproj(y),))  # type: ignore
        self._adj = jax.custom_vjp(self._bproj)
        self._adj.defvjp(lambda y: (self._bproj(y), None), lambda _, x: (self._proj(x),))  # type: ignore

        super().__init__(
            input_shape=self.input_shape,
            output_shape=output_shape,
            input_dtype=np.float32,
            output_dtype=np.float32,
            adj_fn=self._adj,
            jit=False,
        )

    def _proj(self, x: jax.Array) -> jax.Array:
        # Applies the forward projector and generates a sinogram

        def f(x):
            if x.flags.writeable == False:
                x.flags.writeable = True
            if self.num_dims == 2:
                proj_id, result = astra.create_sino(x, self.proj_id)
                astra.data2d.delete(proj_id)
            elif self.num_dims == 3:
                proj_id, result = astra.create_sino3d_gpu(x, self.proj_geom, self.vol_geom)
                astra.data3d.delete(proj_id)
            return result

        return hcb.call(
            f, x, result_shape=jax.ShapeDtypeStruct(self.output_shape, self.output_dtype)
        )

    def _bproj(self, y: jax.Array) -> jax.Array:
        # applies backprojector
        def f(y):
            if y.flags.writeable == False:
                y.flags.writeable = True
            if self.num_dims == 2:
                proj_id, result = astra.create_backprojection(y, self.proj_id)
                astra.data2d.delete(proj_id)
            elif self.num_dims == 3:
                proj_id, result = astra.create_backprojection3d_gpu(
                    y, self.proj_geom, self.vol_geom
                )
                astra.data3d.delete(proj_id)
            return result

        return hcb.call(f, y, result_shape=jax.ShapeDtypeStruct(self.input_shape, self.input_dtype))

    def fbp(self, sino: jax.Array, filter_type: str = "Ram-Lak") -> jax.Array:
        """Filtered back projection (FBP) reconstruction.

        Perform tomographic reconstruction using the filtered back
        projection (FBP) algorithm.

        Args:
            sino: Sinogram to reconstruct.
            filter_type: Select the filter to use. For a list of options
               see `cfg.FilterType` in the `ASTRA documentation
               <https://www.astra-toolbox.com/docs/algs/FBP_CUDA.html>`__.
        """

        if self.num_dims == 3:
            raise NotImplementedError("3D FBP is not implemented")

        # Just use the CPU FBP alg for now; hitting memory issues with GPU one.
        def f(sino):
            if sino.flags.writeable == False:
                sino.flags.writeable = True
            sino_id = astra.data2d.create("-sino", self.proj_geom, sino)

            # create memory for result
            rec_id = astra.data2d.create("-vol", self.vol_geom)

            # start to populate config
            cfg = astra.astra_dict("FBP")
            cfg["ReconstructionDataId"] = rec_id
            cfg["ProjectorId"] = self.proj_id
            cfg["ProjectionDataId"] = sino_id
            cfg["option"] = {"FilterType": filter_type}

            # initialize algorithm; run
            alg_id = astra.algorithm.create(cfg)
            astra.algorithm.run(alg_id)

            # get the result
            out = astra.data2d.get(rec_id)

            # cleanup FBP-specific arra
            astra.algorithm.delete(alg_id)
            astra.data2d.delete(rec_id)
            astra.data2d.delete(sino_id)
            return out

        return hcb.call(
            f, sino, result_shape=jax.ShapeDtypeStruct(self.input_shape, self.input_dtype)
        )


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

#这是服务器的首页，即为生成服务web.app的地方

import logging;logging.basicConfig(level=logging.INFO)
import asyncio,os,time,json
import orm
from handler import COOKIE_NAME,cookie2user
from models import User
from jinja2 import Environment,FileSystemLoader
from aiohttp import web
from coroweb import get,add_routes,add_static
from config import configs

#初始化jinja2模板
def init_jinja2(app,**kw):
	logging.info('init jinja2...')
	options = dict(
		    autoescape = kw.get('autoescape',True),
		    block_start_string = kw.get('block_start_string','{%'),
		    block_end_string = kw.get('block_end_string','%}'),
		    variable_start_string = kw.get('variable_start_string','{{'),
		    variable_end_string = kw.get('variable_end_string','}}'),
		    auto_reload = kw.get('auto_reload',True)
		)
	path = kw.get('path',None)
	if path is None:
		path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'templates')
	logging.info('set jinja2 template path: %s' %str(path))
	env = Environment(loader=FileSystemLoader(path),**options)
	filters = kw.get('filters',None)
	if filters is not None:
		for name, f in filters.items():
			env.filters[name] = f
	#给app增添'__templating__'属性，值为jinja2的env，可以通过调用env.get_template来获取模板
	app['__templating__'] = env

#middlewares拦截器
async def logger_factory(app,handler):
	async def logger(request):
		logging.info('Request: %s %s' %(request.method,request.path))
		return (await handler(request))
	return logger

#解析cookie将登陆用户绑定到request对象的拦截器
async def auth_factory(app,handler):
	async def auth(request):
		logging.info('check user: %s %s' %(request.method,request.path))
		#设置新的属性__user__
		request.__user__ = None
		#已经import handler，同样的COOKIE_NAME就可以拿到
		cookie_str = request.cookies.get(COOKIE_NAME)
		if cookie_str:
			#从cookie_str中拿到用户名
			user = await cookie2user(cookie_str)
			if user:
				logging.info('set current user: %s' %user.email)
				request.__user__ = user
		return (await handler(request))
	return auth

#这里解析的是request里的数据
async def data_factory(app,handler):
	async def parse_data(request):
		if request.method == 'POST':
			if request.content_type.startswith('application/json'):
				request.__data__ = await request.json()
				logging.info('request json: %s' %str(request.__data__))
			elif request.content_type.startswith('application/x-www-form-urlencoded'):
				request.__data__ = await request.post()
				logging.info('request form: %s ' %str(request.__data__))
		return (await handler(request))
	return parse_data

#对handler的返回结果进行处理，使其符合aiohttp的response格式
async def response_factory(app,handler):
	async def response(request):
		logging.info('Response handler...')
		r = await handler(request)
		if isinstance(r,web.StreamResponse):
			#StreamResponse是aiohttp的标准返回对象，不需要处理
			return r
		if isinstance(r,bytes):
			resp = web.Response(body = r)
			resp.content_type = 'application/octer-stream'
			return resp
		if isinstance(r,str):
			if r.startswith('redirect:'):
				return web.HTTPFound(r[9:])
			resp = web.Response(body = r.encode('utf-8'))
			resp.content_type='text/html;charset=utf-8'
			return resp
		if isinstance(r,dict):
			#在handler里用'__template__'属性来作为键指向返回对象（html模板
			template = r.get('__template__')
			if template is None:
				resp = web.Response(body = json.dumps(r,ensure_ascii = False,default = lambda o:o.__dict__).encode('utf-8'))
				resp.content_type = 'application/json;charset=utf-8'
				return resp
			else:
				resp = web.Response(body = app['__templating__'].get_template(template).render(**r).encode('utf-8'))
				resp.content_type = 'text/html;charset=utf-8'
				return resp
		if isinstance(r,int) and r >= 100 and r<600:
			return web.Response(r)
		if isinstance(r,tuple) and len(r) == 2:
			t,m = r
			if isinstance(t,int) and t>=100 and t<600:
				return web.Response(t,str(m))
		#default
		resp = web.Response(body = str(r).encode('utf-8'))
		resp.conent_type= 'text/plain;charset=utf-8'
		return resp
	return response

def datetime_filter(t):
	delta = int(time.time() - t)
	if delta <60:
		return u'1分钟前'
	if delta <3600:
		return u'%s分钟前' %(delta //60)
	if delta <86400:
		return u'%s小时前' %(delta//3600)
	if delta <604800:
		return u'%s天前' %(delta//86400)
	dt = datetime.formtimestamp(t)
	return u'%s年%s月%s日' %(dt.year,dt.month,dt.day)

async def init(loop):
	await orm.create_pool(loop = loop,**configs.db)
	app = web.Application(loop = loop,middlewares=[logger_factory,auth_factory,response_factory])
	init_jinja2(app,filters=dict(datetime = datetime_filter))
	add_routes(app,'handler')
	add_static(app)
	srv = await loop.create_server(app.make_handler(),'127.0.0.1',9000)
	logging.info('server started at http://127.0.0.1:9000...')
	return srv

loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()


'''
旋转图像

给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
'''

class Solution:
	def rotate(self, matrix):
		"""
		:type matrix: List[List[int]]
		:rtype: void Do not return anything, modify matrix in-place instead.
		"""
		#zip()函数
		matrix[:] = map(list,zip(*matrix[::-1]))

matrix = [
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
]

Solution().rotate(matrix)

print(matrix)


import asyncio, time

def timeit(func):
    """ Timing decorator for coroutines """
    async def process(func, *args, **params):
        if asyncio.iscoroutinefunction(func):
            print('this function is a coroutine: {}'.format(func.__name__))
            return await func(*args, **params)
        else:
            print('this is not a coroutine')
            return func(*args, **params)

    async def helper(*args, **params):
        print('{}.time'.format(func.__name__))
        start = time.time()
        result = await process(func, *args, **params)

        # Test normal function route...
        # result = await process(lambda *a, **p: print(*a, **p), *args, **params)

        print('>>>', time.time() - start)
        return result

    return helper


from datetime import datetime
from os.path import dirname, join

import pytest
from city_scrapers_core.constants import BOARD, PASSED, TENTATIVE
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from scrapy.settings import Settings

from city_scrapers.spiders.det_police_fire_retirement import (
    DetPoliceFireRetirementSpider,
)

test_response = file_response(
    join(dirname(__file__), "files", "det_police_fire_retirement.html"),
    url="http://www.rscd.org/member_resources/board_of_trustees/upcoming_meetings.php",
)
test_past_response = file_response(
    join(dirname(__file__), "files", "det_police_fire_retirement_past.html"),
    url="http://www.rscd.org/member_resources_/board_of_trustees/past_meeting_agendas___minutes.php",  # noqa
)

spider = DetPoliceFireRetirementSpider()
spider.settings = Settings(values={"CITY_SCRAPERS_ARCHIVE": False})

freezer = freeze_time("2019-04-05")
freezer.start()
spider._parse_past_documents(test_past_response)
parsed_items = [item for item in spider._parse_meetings(test_response)]
freezer.stop()

def test_total():
    assert len(parsed_items) == 38

def test_title():
    assert parsed_items[0]["title"] == "Board of Trustees"

def test_description():
    assert parsed_items[0]["description"] == ""

def test_start():
    assert parsed_items[0]["start"] == datetime(2019, 1, 10, 9, 0)
    assert parsed_items[-1]["start"].year < 2019

def test_end():
    assert parsed_items[0]["end"] is None

def test_id():
    assert (
        parsed_items[0]["id"]
        == "det_police_fire_retirement/201901100900/x/board_of_trustees"
    )

def test_status():
    assert parsed_items[0]["status"] == PASSED
    assert parsed_items[8]["status"] == TENTATIVE

def test_location():
    assert parsed_items[0]["location"] == {
        "name": "Retirement Systems Conference Room",
        "address": "500 Woodward Ave. Suite 300 Detroit, MI 48226",
    }
    assert parsed_items[-1]["location"] == {
        "name": "Retirement Systems",
        "address": "500 Woodward Ave. Suite 300 Detroit, MI 48226",
    }

def test_source():
    assert (
        parsed_items[0]["source"]
        == "http://www.rscd.org/member_resources/board_of_trustees/upcoming_meetings.php"  # noqa
    )

def test_links():
    assert parsed_items[0]["links"] == [
        {"href": "http://www.rscd.org/PFRS_3229A_01102019.pdf", "title": "Agenda"},
        {"href": "http://www.rscd.org/PFM_3229_011019.pdf", "title": "Minutes"},
    ]
    assert parsed_items[8]["links"] == []

def test_classification():
    assert parsed_items[0]["classification"] == BOARD

@pytest.mark.parametrize("item", parsed_items)
def test_all_day(item):
    assert item["all_day"] is False


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@__Create Time__ = 2018/2/1 下午5:48
@__Description__ = " "
"""

from django.views.generic.list import ListView
from django.views.generic.edit import CreateView,BaseDeleteView,UpdateView,BaseUpdateView
from perm.mixins import PermissionRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from ..models.group import AssetGroup
from ..models.asset import Asset
from ..forms.group import CreateAssetGroupForm,EditAssetGroupForm
from django.contrib import messages
from django.urls import reverse_lazy,reverse
from django.http import HttpResponseRedirect

class AssetGroupListView(LoginRequiredMixin,ListView):
    model = AssetGroup
    template_name = 'asset-group/list.html'

class CreateAssetGroupView(PermissionRequiredMixin,LoginRequiredMixin,CreateView):
    model = AssetGroup
    template_name = 'asset-group/create.html'
    form_class = CreateAssetGroupForm
    success_url = reverse_lazy('asset_group_list')
    permission_required = 'create_asset_group'

    def form_invalid(self, form):
        messages.error(self.request,form.errors.as_text())
        return super().form_invalid(form)

    def form_valid(self, form):
        asset_group_object = form.save(commit=False)
        asset_group_object.created_by = self.request.user.name
        return super().form_valid(form)

class DeleteAssetGroupView(PermissionRequiredMixin,LoginRequiredMixin,BaseDeleteView):
    model = AssetGroup
    success_url = reverse_lazy('asset_group_list')
    permission_required = 'delete_asset_group'

class EditAssetGroupView(PermissionRequiredMixin,LoginRequiredMixin,UpdateView):
    model = AssetGroup
    form_class = EditAssetGroupForm
    template_name = 'asset-group/create.html'
    success_url = reverse_lazy('asset_group_list')
    permission_required = 'edit_asset_group'


# IGNACIO A VARAS C.
# Ingeniero en Bioinformatica
# CBIB 2014
# ignaciovarasc@gmail.com

import sys

name = sys.argv[1]
f = open(name,"r")
name2 = "%s_codesgi" % (name)
f2 = open(name2,"w")
while True:
    linea = f.readline()
    if not linea: break
    linea = linea.split()
    gi = linea[2].split('|')

    line = "%s\t%s\n" % (linea[0],gi[1])
    f2.write(line)
f.close()
f2.close()