import time
import configs
import dialogs
import pyqtgraph as pg
import numpy as np
from PyQt4 import QtGui

DEFAULT_VIEW_RANGE = 60#S
DEFAULT_TIME_FORMAT = "%m/%d/%Y %H:%M:%S"
LOAD_EVERY_RESET = 1

#TODO
#Add grid config to graph

class ModAxisItem(pg.AxisItem):
        def __init__(self, *args, **kwargs):
            super(ModAxisItem, self).__init__(*args, **kwargs)
            self.plotDate = 0
        def tickStrings(self, values, scale, spacing):
            if not self.plotDate:
                places = max(0, np.ceil(-np.log10(spacing*scale)))
                strings = []
                for v in values:
                    vs = v * scale
                    if abs(vs) < .001 or abs(vs) >= 10000:
                        vstr = "%g" % vs
                    else:
                        vstr = ("%%0.%df" % places) % vs
                    strings.append(vstr)
                return strings
            else:
                return [time.ctime(value) for value in values if value > 0]

class singleAxesGraph(pg.PlotWidget):
    def __init__(self, name, plotLabels):
        self.modAxis = ModAxisItem(orientation='bottom')
        super(singleAxesGraph, self).__init__(axisItems={'bottom' : self.modAxis})
        self.name = name
        self.plotLabels = plotLabels
        self.pause = False
        self.plotItem.setTitle(name)

        self.config = configs.GraphConfig(self.name, self.plotLabels)
        self.modAxis.plotDate = self.config.configDict[self.config.PlotDate]
        self.viewRange = self.config.configDict[self.config.ViewRange]

        if self.modAxis.plotDate:
            now = time.time()
            self.setXRange(now - self.viewRange, now, 0)
        else:
            self.setXRange(-self.viewRange, 0, 0)

        self.primaryPlots = [self.plot(name=item, pen=self.makePen(item)) for item in plotLabels]
        self.setLabel('bottom', 'Time', units='s')
        legend = self.addLegend()
        for plot in self.primaryPlots:
            legend.addItem(plot, plotLabels[self.primaryPlots.index(plot)])

        self.menu = self.getPlotItem().getViewBox().menu
        self.configure = QtGui.QAction("Configure..", self.menu)
        self.configure.triggered.connect(self.open_config)
        self.menu.addAction(self.configure)

        self.pauseAction = QtGui.QAction("Pause", self.menu)
        self.pauseAction.triggered.connect(self.toggle_pause)
        self.pauseAction.setCheckable(True)
        self.menu.addAction(self.pauseAction)

    def makePen(self, label):
        color = QtGui.QColor(self.config.configDict[self.config.PlotDataItemColor % label])
        width = self.config.configDict[self.config.PlotDataItemWidth % label]
        style = self.config.configDict[self.config.PlotDataItemPattern % label]
        return pg.mkPen(color=color, width=width, style=style)

    def setAxisNames(self, name, units):
        self.setLabel('left', name, units=units)

    def update_data(self, dataList):
        if self.isVisible() and not self.pause:
            if LOAD_EVERY_RESET:
                self.config.load_configs()
                self.load_config()
            for i in range(len(self.primaryPlots)):
                now = time.time()
                if not self.modAxis.plotDate:
                    xdata = dataList[i][1] - now
                    self.setXRange(-self.viewRange, 0, 0)
                else:
                    xdata = dataList[i][1]
                    self.setXRange(now - self.viewRange, now, 0)
                ydata = dataList[i][0]
                self.primaryPlots[i].setData(x=xdata, y=ydata)

    def open_config(self):
        dialogs.GraphConfigDialog(self.config)
        self.load_config()

    def load_config(self):
        self.modAxis.plotDate = self.config.configDict[self.config.PlotDate]
        self.viewRange = self.config.configDict[self.config.ViewRange]
        pens = [self.makePen(label) for label in self.plotLabels]
        for plot in self.primaryPlots:
            i = self.primaryPlots.index(plot)
            plot.setPen(pens[i])

    def toggle_pause(self):
        if self.pause:
            self.pause = False
            self.pauseAction.setChecked(False)
        else:
            self.pause = True
            self.pauseAction.setChecked(True)

class doubleAxesGraph(pg.PlotWidget):
    def __init__(self, name, plotLabelsLeft, plotLabelsRight):
        self.modAxis = ModAxisItem(orientation='bottom')
        super(doubleAxesGraph, self).__init__(axisItems={'bottom' : self.modAxis})
        self.name = name
        self.plotLabelsLeft = plotLabelsLeft
        self.plotLabelsRight = plotLabelsRight
        self.pause = False

        self.config = configs.GraphConfig(self.name, self.plotLabelsLeft, self.plotLabelsRight)
        self.modAxis.plotDate = self.config.configDict[self.config.PlotDate]
        self.viewRange = self.config.configDict[self.config.ViewRange]

        if self.modAxis.plotDate:
            now = time.time()
            self.setXRange(now - self.viewRange, now, 0)
        else:
            self.setXRange(-self.viewRange, 0, 0)

        self.leftAxis = self.plotItem
        self.leftAxis.setTitle(name)
        self.leftAxis.getAxis('bottom').setLabel('Time', units='s')
        legend = self.leftAxis.addLegend()

        self.rightAxis = pg.ViewBox()
        #legend1 = self.rightAxis.addLegend()
        self.leftAxis.showAxis('right')
        self.leftAxis.scene().addItem(self.rightAxis)
        self.leftAxis.getAxis('right').linkToView(self.rightAxis)
        self.rightAxis.setXLink(self.leftAxis)

        self.leftAxis.vb.sigResized.connect(self.updateViews)

        self.leftAxisPlots = [self.leftAxis.plot([], [], name=plot, pen=self.makePen(plot)) for plot in plotLabelsLeft]
        for plot in plotLabelsRight:
            self.rightAxis.addItem(pg.PlotCurveItem([], [], name=plot, pen=self.makePen(plot)))
        self.rightAxisPlots = [self.rightAxis.allChildren()[1]]
        for plot in self.rightAxisPlots:
            legend.addItem(plot, plotLabelsRight[self.rightAxisPlots.index(plot)])

        self.menu = self.getPlotItem().getViewBox().menu
        self.configure = QtGui.QAction("Configure..", self.menu)
        self.configure.triggered.connect(self.open_config)
        self.menu.addAction(self.configure)

        self.pauseAction = QtGui.QAction("Pause", self.menu)
        self.pauseAction.triggered.connect(self.toggle_pause)
        self.pauseAction.setCheckable(True)
        self.menu.addAction(self.pauseAction)

    def makePen(self, label):
        color = QtGui.QColor(self.config.configDict[self.config.PlotDataItemColor % label])
        width = self.config.configDict[self.config.PlotDataItemWidth % label]
        style = self.config.configDict[self.config.PlotDataItemPattern % label]
        return pg.mkPen(color=color, width=width, style=style)

    def setAxisNames(self, nameLeft, unitsLeft, nameRight, unitsRight):
        self.leftAxis.getAxis('left').setLabel(nameLeft, units=unitsLeft)
        self.leftAxis.getAxis('right').setLabel(nameRight, units=unitsRight)

    def updateViews(self):
        self.rightAxis.setGeometry(self.leftAxis.vb.sceneBoundingRect())

    def open_config(self):
        dialogs.GraphConfigDialog(self.config)
        self.load_config()

    def load_config(self):
        self.modAxis.plotDate = self.config.configDict[self.config.PlotDate]
        self.viewRange = self.config.configDict[self.config.ViewRange]
        pens = [self.makePen(label) for label in self.plotLabelsLeft]
        for plot in self.plotLabelsRight:
            pens.append(self.makePen(plot))
        for plot in self.leftAxisPlots:
            i = self.leftAxisPlots.index(plot)
            plot.setPen(pens[i])
        for plot in self.rightAxisPlots:
            i = len(self.leftAxisPlots) + self.rightAxisPlots.index(plot)
            plot.setPen(pens[i])

    def toggle_pause(self):
        if self.pause:
            self.pause = False
            self.pauseAction.setChecked(False)
        else:
            self.pause = True
            self.pauseAction.setChecked(True)

    def update_data(self, dataListLeft, dataListRight): #data1 = [self.voltage.value]
        if self.isVisible() and not self.pause:
            if LOAD_EVERY_RESET:
                self.config.load_configs()
                self.load_config()
            for i in range(len(self.leftAxisPlots)):
                now = time.time()
                if not self.modAxis.plotDate:
                    xdata = dataListLeft[i][1] - now
                    self.setXRange(-self.viewRange, 0, 0)
                else:
                    xdata = dataListLeft[i][1]
                    self.setXRange(now - self.viewRange, now, 0)
                ydata = dataListLeft[i][0]

                self.leftAxisPlots[i].setData(x=xdata, y=ydata)

            for i in range(len(self.rightAxisPlots)):
                now = time.time()
                if not self.modAxis.plotDate:
                    xdata = dataListRight[i][1] - now
                else:
                    xdata = dataListRight[i][1]
                ydata = dataListRight[i][0]

                self.rightAxisPlots[i].setData(x=xdata, y=ydata)


"""
zip() - Cria um iteável (Zip Object) que agrega cada elemento
de cada um dos iteráveis passados como entrada em pares.
"""
# Exemplos

lista1 = [1, 2, 3]
lista2 = [4, 5, 6]

zip1 = zip(lista1, lista2)

print(zip1)

print(list(zip1))

texto = 'abcdefg', 'absdw'
numeros = 123456, 12323

zip2 = zip(texto, numeros)

print(list(zip2))

tupla = 1, 2, 3
lista = [4, 5, 6]
dicionario = {"a": 7, "b": 8, "c": 9}
zt = zip(tupla, lista, dicionario.values())
print(list(zt))

# Exemplos mais complexos

prova1 = [80, 91, 78]
prova2 = [98, 89, 53]
alunos = ['maria', 'pedro', 'carla']

final = {dado[0]: max(dado[1], dado[2]) for dado in zip(alunos, prova1, prova2)}
print(final)

final = zip(alunos, map(lambda nota: max(nota), zip(prova1, prova2)))
print(dict(final))


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

# # Data Science Academy - Python Fundamentos - Capítulo 2
#
# ## Download: http://github.com/dsacademybr

# In[1]:

# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', python_version())

# ## Números e Operações Matemáticas

# # Pressione as teclas shift e enter para executar o código em uma célula ou pressione o botão Play no menu superior

# In[2]:

# Soma
4 + 4

# In[3]:

# Subtração
4 - 3

# In[4]:

# Multiplicação
3 * 3

# In[5]:

# Divisão
3 / 2

# In[6]:

# Potência
4 ** 2

# In[7]:

# Módulo
10 % 3

# ### Função Type

# In[8]:

type(5)

# In[9]:

type(5.0)

# In[10]:

a = 'Eu sou uma string'
type(a)

# ### Operações com números float

# In[11]:

3.1 + 6.4

# In[12]:

4 + 4.0

# In[13]:

4 + 4

# In[14]:

# Resultado é um número float
4 / 2

# In[15]:

# Resultado é um número inteiro
4 // 2

# In[16]:

4 / 3.0

# In[17]:

4 // 3.0

# ### Conversão

# In[18]:

float(9)

# In[19]:

int(6.0)

# In[20]:

int(6.5)

# ### Hexadecimal e Binário

# In[21]:

hex(394)

# In[22]:

hex(217)

# In[23]:

bin(286)

# In[24]:

bin(390)

# ### Funções abs, round e pow

# In[25]:

# Retorna o valor absoluto
abs(-8)

# In[26]:

# Retorna o valor absoluto
abs(8)

# In[27]:

# Retorna o valor com arredondamento
round(3.14151922,2)

# In[28]:

# Potência
pow(4,2)

# In[29]:

# Potência
pow(5,3)

# # Fim

# ### Obrigado - Data Science Academy - facebook.com/dsacademybr


import yaml
import os.path
import os
import jinja2
import sys
sys.path = [os.path.join(os.path.dirname(__file__), '..')] + sys.path
import bindings.get_info
from bindings.maybe_write import maybe_write
import re

if len(sys.argv) != 2:
    print("Invalid usage: do not have destination")
    sys.exit(1)

print("Generating", sys.argv[1])

directory = os.path.split(os.path.abspath(__file__))[0]
all_info = bindings.get_info.get_all_info()
metadata =all_info['metadata']
#we change {{ and }} to <% and %> to avoid ambiguity when building arrays.
environment = jinja2.Environment(
variable_start_string = '<%', variable_end_string = '%>',
loader = jinja2.FileSystemLoader(directory),
undefined = jinja2.StrictUndefined,
extensions = ['jinja2.ext.loopcontrols'])

#we have to do some sanitizing for the template.
#the map we have here is actually very verbose, and can be flattened into something easily iterable.
#we can then take advantage of either std::pair or std::tuple as the keys.
joined_properties = []
for nodekey, nodeinfo in [(i, metadata['nodes'].get(i, dict())) for i in all_info['constants'].keys() if re.match("Lav_OBJTYPE(\w+_*)+_NODE", i)]:
    #add everything from the object itself.
    for propkey, propinfo in nodeinfo.get('properties', dict()).items():
        joined_properties.append((nodekey, propkey, propinfo))
    #if we're not suppressing inheritence, we follow this up with everything from lav_OBJTYPE_GENERIC.
    if not nodeinfo.get('suppress_implied_inherit', False):
        for propkey, propinfo in metadata['nodes']['Lav_OBJTYPE_GENERIC_NODE']['properties'].items():
            joined_properties.append((nodekey, propkey, propinfo))

#this is the same logic, but for events.
joined_events = []
for nodekey, nodeinfo in [(i, metadata['nodes'].get(i, dict())) for i in all_info['constants'].keys() if re.match("Lav_OBJTYPE_(\w+_*)+_NODE", i)]:
    #add everything from the object itself.
    for eventkey, eventinfo in nodeinfo.get('events', dict()).items():
        joined_events.append((nodekey, eventkey, eventinfo))
    #if we're not suppressing inheritence, we follow this up with everything from lav_OBJTYPE_GENERIC.
    if not nodeinfo.get('suppress_implied_inherit', False):
        for eventkey, eventinfo in metadata['nodes']['Lav_OBJTYPE_GENERIC_NODE'].get('events', dict()).items():
            joined_events.append((nodekey, eventkey, eventinfo))

#the template will convert the types into enums via judicious use of if statements-we use it like augmented c, and prefer to do refactoring only there when possible.
#each property will be crammed into a property descriptor, but some of the ranges here are currently potentially unfriendly, most notably float3 and float6.
#we are going to convert all numbers into strings, and make them valid c identifiers.  Skip anything that is already a string.
def string_from_number(val, type):
    if type in {'float', 'float3', 'float6', 'float_array'}:
        return str(float(val))+'f'
    elif type == 'double':
        return str(float(val))
    elif type in {'int', 'int_array', 'boolean'}:
        return str(int(val))
    else:
        print("Warning: Unrecognized type or value with type", type, "and value", val)
        print("Returning val unchanged.")
        return val

#note that there is a very interesting little hack heere.
#Since the second key of every tuple is a dict, it's possible that we're marking up a property we've already marked up.
#Problem: if we just do dict(foo), and later nest dicts, we'll have hard-to-find problems.
#solution: mark the properties as we normalize them.
for propkey, propid, propinfo in joined_properties:
    if propinfo.get('normalized', False):
        continue
    if propinfo['type'] == 'boolean':
        propinfo['range'] = [0, 1]
    if propinfo['type'] == 'int' and propinfo.get('read_only', False):
        propinfo['range'] = [0, 0]
    if propinfo['type'] == 'float' and propinfo.get('read_only', False):
        propinfo['range'] = [0.0, 0.0]
    if propinfo['type'] == 'double' and propinfo.get('read_only', False):
        propinfo['range'] = [0.0, 0.0]
    #Some int arrays are arrays of enums, i.e. FDN filter types.
    if propinfo['type'] in {'int', 'int_array'} and not propinfo.get('read_only', False) and 'value_enum' in propinfo:
        e = all_info['constants_by_enum'][propinfo['value_enum']]
        r1 = min(e.values())
        r2 = max(e.values())
        propinfo['range'] = [r1, r2]
    if propinfo['type'] == 'int' and propinfo.get('default', None) in all_info['constants']:
        propinfo['default'] = all_info['constants'][propinfo['default']]
    if propinfo.get('range', None) =='dynamic':
        propinfo['range'] = [0, 0]
        propinfo['is_dynamic'] = True
    for i, j in enumerate(list(propinfo.get('range', []))): #if we don't have a range, this will do nothing.
        if isinstance(j, str):
            continue #it's either MIN_INT, MAX_INT, INFINITY, -INFINITY, or another special identifier.  Pass through unchanged.
        #we're not worried about float3 or float6 logic, because those aren't allowed to have traditional ranges at the moment-so this is it:
        propinfo['range'][i] = string_from_number(j, propinfo['type'])
    #Some array properties (see the feedback delay network) are controlled completely by their constructor.
    #If this is the case, we need to give it some defaults so that the generated cpp file doesn't explode.
    #The constructor later updates this information.
    if propinfo['type'] in {'int_array', 'float_array'} and propinfo.get('dynamic_array', False):
        propinfo['min_length'] = propinfo.get('min_length', 1)
        propinfo['max_length'] = propinfo.get('max_length', 1)
        #This string is handled later; we need to be careful about the type here.
        #No need to duplicate code we have to do in a minute anyway.
        propinfo['default'] = propinfo.get('default', 'zeros')
        propinfo['range'] = propinfo.get('range', ['MIN_INT', 'MAX_INT'] if propinfo['type'] == 'int_array' else ['-INFINITY', 'INFINITY'])
    #Default handling logic.  If we don't have one and are int, float, or double we make it 0.
    if propinfo['type'] in {'int', 'float', 'double'}:
        propinfo['default'] = string_from_number(propinfo.get('default', 0), propinfo['type'])
    #otherwise, if we're one of the array types, we do a loop for the same behavior.
    elif propinfo['type'] in {'float3', 'float6'}:
        for i, j in enumerate(list(propinfo.get('default', [0, 0, 0] if propinfo['type'] == 'float3' else [0, 0, 0, 0, 0, 0]))):
            propinfo['default'][i] = string_from_number(j, propinfo['type'])
    elif propinfo['type'] in {'int_array', 'float_array'}:
        #As a special case, we allow the default heere to be the string "zeros".
        if propinfo.get('default', None) == "zeros":
            length = int(propinfo['min_length'])
            propinfo['default'] = [0.0]*length
            if propinfo['type'] == 'float_array':
                propinfo['default'] = [int(i) for i in propinfo['default']]
        for i, j in enumerate(list(propinfo.get('default', []))):
            propinfo['default'][i] = string_from_number(j, propinfo['type'])
    propinfo['normalized'] = True

#Sorting these makes sure maybe-write always gets the same thing.
joined_properties.sort()
joined_events.sort()

#do the render, and write to the file specified on the command line.
context = {
'joined_properties': joined_properties,
'joined_events': joined_events,
}
context.update(all_info)

template = environment.get_template('metadata.t')
result = template.render(context)

if not os.path.exists(os.path.split(os.path.abspath(sys.argv[1]))[0]):
    os.makedirs(os.path.split(os.path.abspath(sys.argv[1]))[0])

maybe_write(sys.argv[1], result)


import requests
from player import Player

headers = {
    'Authorization': 'Token 8462b8d16624f572bdc0d8402680ae5245449f4d',
    'Content-Type': 'application/json',
}

data = '{"direction":"n"}'

newMap = {}

response = requests.post('https://lambda-treasure-hunt.herokuapp.com/api/adv/move/', headers=headers, data=data)

print(response.text)

# algorithm

oppositeDirection = {'n': 's', 's': 'n', 'e': 'w', 'w': 'e'}
traversalPath = []
reversalPath = [None]
rooms = {}
roomsDictionary = {}
roomGraph = {}

#maze algorithm

#initialize first room by appending each exit
rooms[0] = player.currentRoom.getExits()
roomsDictionary[0] = player.currentRoom.getExits()

while len(rooms) < len(roomGraph)-1:
    if player.currentRoom.id not in rooms:
        rooms[player.currentRoom.id] = player.currentRoom.getExits()
        roomsDictionary[player.currentRoom.id] = player.currentRoom.getExits()
        lastDirection = reversalPath[-1]
        roomsDictionary[player.currentRoom.id].remove(lastDirection)
    while len(roomsDictionary[player.currentRoom.id]) < 1:
        reverse = reversalPath.pop()
        traversalPath.append(reverse)
        player.travel(reverse)
    exit_dir = roomsDictionary[player.currentRoom.id].pop(0)
    traversalPath.append(exit_dir)
    reversalPath.append(oppositeDirection[exit_dir])
    player.travel(exit_dir)
    if len(roomGraph) - len(rooms) ==1:
        rooms[player.currentRoom.id] = player.currentRoom.getExits()


import webbrowser
import os
from bs4 import BeautifulSoup
import requests
import matplotlib.pyplot as plt

def urlify(s):

     # Remove all non-word characters (everything except numbers and letters)
     #s = re.sub(r"[^\w\s]", '', s)

     # Replace all runs of whitespace with a single dash
     s = re.sub(r"\s+", '-', s)

     return s

count =0
a=[]
b=[]
next_lines = []

directory ='/root/Downloads/facebook-namanarora921/ads'
for filename in os.listdir(directory):
    if filename.endswith('interests.html'):
        fname = os.path.join(directory,filename)
        with open(fname, 'r') as f:
            soup = BeautifulSoup(f.read(),'html.parser')
            x = soup.find_all("div",class_= "_2lek")
            for e in x:
                a=e.text
                b.append(a)

text = ''.join([str(v) for v in b])
trr = "+".join(text.split())
print("\n")
print("INPUT IS GIVEN IN THE FOLLOWING FORMAT")
print("\n")
print(trr)
print("\n")
print("\n")
classifier = 'genderanalyzer_v5'
readkey = 'aweO454Kgswc'

url = 'https://api.uclassify.com/v1/uClassify/'+classifier+'/classify/?readKey='+readkey+'&text=This+is+the+text+to+classify'

test = requests.get(url)

#webbrowser.open(url_2, new=2)

output = test.text

male = output[26:34]
female = output[10:18]
print(output)
print("Percentage of male =",float(male)*100,"%")
print("Percentage of female =",float(female)*100,"%")

male_p = float(male)*100
female_p = float(female)*100

left = [1, 2]

height = [male_p, female_p]

tick_label = ['male', 'female']

# plotting a bar chart
plt.bar(left, height, tick_label = tick_label,
        width = 0.8, color = ['red', 'green'])

# naming the x-axis
plt.xlabel('x - axis')
# naming the y-axis
plt.ylabel('y - axis')
# plot title
plt.title('My bar chart!')

# function to show the plot
plt.show()


# N-Queen

def check(si, sj):
    # 위쪽 방향
    for i in range(si - 1, -1, -1):
        if v[i][sj]:
            return 0
    # 좌상단
    i, j = si - 1, sj - 1
    while i >= 0 and j >= 0:
        if v[i][j]:
            return 0
        i, j = i - 1, j - 1
    # 우상단
    i, j = si - 1, sj + 1
    while i >= 0 and j < N:
        if v[i][j]:
            return 0
        i, j = i - 1, j + 1
    # 3방향 모두 퀸이 없다면 성공
    return 1

def DFS(n):
    global sol
    if n == N:
        sol += 1
        return
    for j in range(N):
        if check(n, j):
            v[n][j] = 1
            DFS(n + 1)
            v[n][j] = 0

for t in range(1, int(input()) + 1):
    N = int(input())
    v = [[0] * N for _ in range(N)]
    sol = 0
    DFS(0)
    print(f'#{t} {sol}')


import re

import re
f = open("document.xml", 'r')
pattern = re.compile('o:gfxdata="(.+?)"')
results = ()
for l in f:
   results = pattern.findall(l)

strings = []
if results:
    for item in results:
        strings.append(''.join(item.split('
')))

for i in strings:
    print(i)

f = open("zips.txt", 'r')
stringLine = []
for l in f:
    tmp = l.split('
')
    tmp = ''.join(tmp).strip()
    stringLine.append(tmp)

for i in stringLine:
    print(i)


import random

class ControlStructuresEngine:
    # THESE ARE METHODS DEFINED AT THE CLASS LEVEL
    def demonstrateBasicFunctions(self):
        ran_list = [round(random.uniform(10, 100)) for x in range(10)]
        print(ran_list)
        print('The Total of Numbers in ran_list: ' + str(sum(ran_list)))

        #[S1, S2, S3..... S10]
        names = ["S" + str(x) for x in range(1, 11)]
        print(names)

        marks = zip(names,ran_list)
        print(list(marks))

    def demonstrateIfElifElse(self):
        #Generate two random numbers
        x = random.normalvariate(50,2)
        y = random.uniform(10,100)

        if(x > y):
            print('X is greater than Y')
        elif(x == y):
            print('X is Y')
        else:
            print('Y is greater than X')

        if (x > y): print('X is greater than Y')

        print('X is greater than Y') if (x > y) else print('X is NOT greater than Y')

    def demonstrateForLoop(self):
        ran_nums = [round(random.uniform(10, 100)) for x in range(10)]

        for x in ran_nums:
            if(x > 50): print(x)

        ran_nums_gt_50 = [x for x in ran_nums if x>50 ]
        print(ran_nums_gt_50)

        str1 = "Pablo Riuz"
        for x in str1:
            if(str.isupper(x)): print(x)

        str_UC = [x for x in str1 if str.isupper(x)]
        print(str_UC)

        str1_iter = iter(str1)
        print(next(str1_iter))
        print(next(str1_iter))
        print(next(str1_iter))
        print(next(str1_iter))

        list1 = [1,3,5,7,9]
        for x in list1:
            print(x)
            if x == 5: continue
            print(x)

        for x in list1:
            print(x)
            if x == 5: break
            print(x)

        list2 = list(range(5, 50, 5))
        print(list2)
        print(range(5, 50, 5))

        for x in range(5, 50, 5):
            print(x)
            if x == 25: continue
            print(x)

        print('####')
        for x in range(5, 75, 5):
            print(x/2)
        else:
            print('The for loop ended')
            print('Was it ended by the break?')

    def get_the_two_max_numbers(self,numbers):
        numbers.sort(reverse=True)
        return(numbers[:2])

    def get_the_two_max_numbers2(self,numbers):
        num1 = 0
        num2 = 0
        for x in numbers:
            if(x > num1): num1 = x
            elif (x > num2): num2 = x
        return([num1, num2])

    def generateMultiTable(self, number):
        return([number*x for x in range(11) ])
        """
        for i in range(1, 11):
            table = number * i
            print(table) """

    def doEx1(self):
        print("#Q1#")
        numbers = [round(random.uniform(10, 100)) for x in range(10)]
        print(self.get_the_two_max_numbers(numbers))
        print(self.get_the_two_max_numbers2(numbers))

        print("")
        print("#Q2#")
        random_numbers = [round(random.uniform(1, 100)) for x in range(20)]

        sum_even = 0
        sum_odd = 0

        for x in random_numbers:
            if x % 2 == 0:
                sum_even += x
            else:
                sum_odd += x

        print("Random Numbers:", random_numbers)
        print("Sum of Even Numbers:", sum_even)
        print("Sum of Odd Numbers:", sum_odd)

        sum_even = sum([x for x in random_numbers if x % 2 == 0])
        sum_odd = sum([x for x in random_numbers if x % 2 != 0])

        print("Sum of Even Numbers:", sum_even)
        print("Sum of Odd Numbers:", sum_odd)

        print()
        print("#C#")
        student = [
            {"id": 2, "first_name": "John", "last_name": "Quick", "subjects": ["English", "Python"], "score": [87, 93]},
            {"id": 3, "first_name": "Paul", "last_name": "Kenedy", "subjects": ["English", "C++", "Math"],
             "score": [85, 76, 90]},
            {"id": 4, "first_name": "Ricki", "last_name": "Morty", "subjects": ["C++", "Math"], "score": [67, 74]}]

        sumMath = 0
        countStudent = 0

        for i in student:
            if 'Math' in i["subjects"]:
                sumMath += i["score"][i["subjects"].index('Math')]
                countStudent += 1

        print(sumMath / countStudent)

        print()
        print("#D#")
        print(self.generateMultiTable(3))

        print("#E#")

        i = 1
        user_nums = []
        while(i <=5):
            num = int(input())
            user_nums.append(num)
            i += 1

        print(user_nums)

#THIS IS A FUNCTION DEFINED AT THE MODULE LEVEL
def mySampleFunction(a, b):
    return(a * b / 9000)

cs_engine = ControlStructuresEngine()

#cs_engine.demonstrateBasicFunctions()
#cs_engine.demonstrateIfElifElse()
#cs_engine.demonstrateForLoop()
cs_engine.doEx1()
#mySampleFunction(6,8)


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

from django.db import models, migrations

class Migration(migrations.Migration):

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

    operations = [
        migrations.AddField(
            model_name='alumno',
            name='imagen',
            field=models.ImageField(verbose_name='Imagen alumno', null=True, blank=True, upload_to='Proyecto/images/'),
        ),
    ]


import math
N = int(input())

ans = None
for i in range(1, 50001):
    v = math.floor(i * 1.08)
    if v == N:
        ans = i
if ans is not None:
    print(ans)
else:
    print(":(")


"""
Credits:
* https://code.google.com/p/webscraping/source/browse/webkit.py
* https://github.com/jeanphix/Ghost.py/blob/master/ghost/ghost.py
"""
#import time
#import sys
from PyQt4.QtCore import QEventLoop, QUrl, QEventLoop, QTimer, QByteArray, QSize
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebView, QWebPage
from PyQt4.QtNetwork import (QNetworkAccessManager, QNetworkRequest,
                             QNetworkCookieJar, QNetworkCookie)
from lxml.html import fromstring
from grab.selector import Selector
from grab.response import Response
import logging
try:
    from urlparse import urlsplit
except ImportError:
    from urllib.parse import urlsplit

from grab.kit.network_access_manager import KitNetworkAccessManager
from grab.kit.network_reply import KitNetworkReply
from grab.kit.error import KitError
from grab.tools.encoding import decode_dict

from grab.util.py3k_support import *

logger = logging.getLogger('grab.kit')

class Resource(object):
    def __init__(self, reply):
        self.reply = reply
        self.url = str(reply.url().toString())

        self.status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
        if not isinstance(self.status_code, int):
            self.status_code = self.status_code.toInt()[0]
        self.headers = {}
        for header in reply.rawHeaderList():
            self.headers[header.data()] = reply.rawHeader(header).data()

class KitWebView(QWebView):
    def setApplication(self, app):
        self.app = app

    def closeEvent(self, event):
        self.app.quit()

    def sizeHint(self):
        viewport_size = (800, 600)
        return QSize(*viewport_size)

class KitPage(QWebPage):
    def __init__(self, *args, **kwargs):
        QWebPage.__init__(self)
        self.user_agent = 'QtWebKitWrapper'

    def userAgentForUrl(self, url):
        if self.user_agent is None:
            return super(KitPage, self).userAgentForUrl(url)
        else:
            return self.user_agent

    def shouldInterruptJavaScript(self):
        return True

    def javaScriptAlert(self, frame, msg):
        logger.error(u'JavaScript Alert: %s' % unicode(msg))

    def javaScriptConfirm(self, frame, msg):
        logger.error(u'JavaScript Confirm: %s' % unicode(msg))

    def javaScriptPrompt(self, frame, msg, default):
        logger.error(u'JavaScript Prompt: %s' % unicode(msg))

    def javaScriptConsoleMessage(self, msg, line_number, src_id):
        logger.error(u'JavaScript Console Message: %s' % unicode(msg))

class Kit(object):
    _app = None

    def __init__(self, gui=False):
        if not Kit._app:
            Kit._app = QApplication([])

        manager = KitNetworkAccessManager()
        manager.finished.connect(self.network_reply_handler)

        self.cookie_jar = QNetworkCookieJar()
        manager.setCookieJar(self.cookie_jar)

        self.page = KitPage()
        self.page.setNetworkAccessManager(manager)

        self.view = KitWebView()
        self.view.setPage(self.page)
        self.view.setApplication(Kit._app)

        if gui:
            self.view.show()

    def get_cookies(self):
        cookies = {}
        for cookie in self.cookie_jar.allCookies():
            cookies[cookie.name().data()] = cookie.value().data()
        return cookies

    def request(self, url, user_agent='Mozilla', cookies={}, timeout=15,
                method='get', data=None, headers={}):
        url_info = urlsplit(url)

        self.resource_list = []
        loop = QEventLoop()
        self.view.loadFinished.connect(loop.quit)

        # Timeout
        timer = QTimer()
        timer.setSingleShot(True)
        timer.timeout.connect(loop.quit)
        timer.start(timeout * 1000)

        # User-Agent
        self.page.user_agent = user_agent

        # Cookies
        cookie_obj_list = []
        for name, value in cookies.items():
            domain = ('.' + url_info.netloc).split(':')[0]
            #print 'CREATE COOKIE %s=%s' % (name, value)
            #print 'DOMAIN = %s' % domain
            cookie_obj = QNetworkCookie(name, value)
            cookie_obj.setDomain(domain)
            cookie_obj_list.append(cookie_obj)
        self.cookie_jar.setAllCookies(cookie_obj_list)

        # Method
        method_obj = getattr(QNetworkAccessManager, '%sOperation' % method.capitalize())

        # Ensure that Content-Type is correct if method is post
        if method == 'post':
            headers['Content-Type'] = 'application/x-www-form-urlencoded'

        # Post data
        if data is None:
            data = QByteArray()

        # Request object
        request_obj = QNetworkRequest(QUrl(url))

        # Headers
        for name, value in headers.items():
            request_obj.setRawHeader(name, value)

        # Make a request
        self.view.load(request_obj, method_obj, data)

        loop.exec_()

        if timer.isActive():
            request_resource = None
            url = str(self.page.mainFrame().url().toString()).rstrip('/')
            for res in self.resource_list:
                if url == res.url or url == res.url.rstrip('/'):
                    request_resource = res
                    break
            if request_resource:
                return self.build_response(request_resource)
            else:
                raise KitError('Request was successfull but it is not possible '\
                               'to associate the request to one of received responses')
        else:
            raise KitError('Timeout while loading %s' % url)

    def build_response(self, resource):
        response = Response()
        response.head = ''
        response.code = resource.status_code

        runtime_body = self.page.mainFrame().toHtml()
        body = resource.reply.data
        url = resource.reply.url().toString()
        headers = resource.headers
        cookies = self.get_cookies()

        # py3 hack
        if PY3K:
            if isinstance(body, QByteArray):
                body = body.data()
            headers = decode_dict(headers)
            cookies = decode_dict(cookies)
        else:
            runtime_body = unicode(runtime_body)
            body = str(body)
            url = str(url)

        response.runtime_body = runtime_body.encode('utf-8')
        response.body = body
        response.url = url
        response.parse(charset='utf-8')
        response.headers = headers
        response.cookies = cookies

        return response

    def __del__(self):
        self.view.setPage(None)

    def network_reply_handler(self, reply):
        status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
        if status_code:
            if not isinstance(status_code, int):
                status_code = status_code.toInt()[0]
            logger.debug('Resource loaded: %s [%d]' % (reply.url().toString(),
                                                       status_code))
            self.resource_list.append(Resource(reply))

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)

    br = Kit(gui=False)
    #resp = br.request('http://httpbin.org/post', method='post', cookies={'foo': 'bar'},
                      #data='foo=bar')
    #print(resp.body)
    resp = br.request('http://ya.ru/')
    print(unicode(br.page.mainFrame().documentElement().findFirst('title').toPlainText()))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov  6 11:57:02 2020
@author: noahlefrancois
"""

import numpy as np
from fast_histogram import histogram2d
from scipy.fft import rfftn, irfftn

class NBody_solver:
    def __init__(self,size,particles,dt,soft=0.1,G=1,boundaryCondition='Periodic', cosmology_mass=False):
        """
        The NBody class that specifies the simulation.
        Input(s):
            - N (x,y): size of the grid. NOTE: Only accepts square grids currently
            - particles (system_init object): List of velocity&position for all particles
            - dt (float): step size for time-stepping
            - soft (float): softening parameter for green function
            - G (float): Gravitational constant (default 1.0)
            - boundary type: Either set to Periodic or Non-Periodic
        """

        self.BC = boundaryCondition
        #For non-periodic conditions, the grid is padded to double the actual size
        #with empty space to avoid wrap-around effects.
        if self.BC == 'Non-Periodic':
            self.size = (2*size[0],2*size[1],2*size[2])
            #self.size = size
        else:
            self.size = size
        self.cosmology_mass = cosmology_mass
        self.soft = soft
        self.G = G
        self.dt = dt
        self.x = particles.x
        self.v = particles.v
        self.m = particles.m
        x, y, z = np.linspace(0, self.size[0]-1, self.size[0]), np.linspace(0, self.size[1]-1, self.size[1]), np.linspace(0, self.size[2]-1, self.size[2])
        self.mesh = np.array(np.meshgrid(x,y,z))
        self.get_NGPdensity()
        self.get_greensFunc()

    def get_NGPdensity(self):
        """
        Get the density function rho on the grid using the Nearest Grid Points method, which approximates
        the density by lumping each particle's mass into the nearest grid point.
        """
        #Get nearest gridpoint index
        self.x_ind = np.rint(self.x).astype('int') % self.size[0]
        #Store the grid of particle indices to access later
        self.x_indexList = tuple(self.x_ind[:, i] for i in range(3))
        #Add up the contributions of all particles to get the total density at each grid point
        x_gridpoints = np.linspace(0, self.size[0]-1, self.size[0]+1)
        bin_coords = np.repeat([x_gridpoints], 3, axis=0)

        GP_densities = np.histogramdd(self.x_ind, bins = bin_coords, weights = self.m.flatten())
        self.rho = GP_densities[0]

    def get_greensFunc(self):
        """
        Get the Green's function of the particles on the grid
        """
        r = np.sum(self.mesh**2,axis=0)
        r[r<self.soft**2] = self.soft**2
        r += self.soft**2
        r = np.sqrt(r)

        g = 1/(4*np.pi*r)

        if self.BC == 'Periodic':
            #Handle the corner periodic behaviour
            h_x,h_y,h_z = self.size[0]//2, self.size[1]//2, self.size[2]//2

            #Not sure how to generalize this to 3D
            try:
                g[h_x:, :h_y, :h_z] = np.flip(g[:h_x,:h_y,:h_z],axis=0)
                g[:,h_y:,h_z:] = np.flip(g[:,:h_y,:],axis=1)
            except:
                g[h_x:, :h_y+1, :h_z+1] = np.flip(g[:h_x,:h_y+1,:h_z+1],axis=0)
                g[:,h_y:,h_z:] = np.flip(g[:,:h_y,:h_z],axis=1)

        self.green = g

    def get_Potential(self):
        """
        Get the potential function by solving the Laplace equation L(Psi) = rho. The simplest way to
        do this is to take the convolution of rho with the Green's function.
        """
        """
        Numpy method
        rho_FFT = np.fft.rfftn(self.rho)
        green_FFT = np.fft.rfftn(self.green)

        psi_FFT = rho_FFT*green_FFT
        psi = np.fft.irfftn(psi_FFT)

        """
        #Scipy method
        #Seems to give identical results to np.fft, but the scipy.fft is a bit faster
        rho_FFT = rfftn(self.rho)
        green_FFT = rfftn(self.green)

        psi_FFT = rho_FFT*green_FFT
        psi = irfftn(psi_FFT)

        #Shift psi back to the centre of the real domain
        for i in range(3):
            psi = 0.5*(np.roll(psi,1,axis=i)+psi)

        #If the boundary conditions is not periodic, set the potential to 0
        #For non-periodic boundary conditions, use Dirichlet BC with Psi|_boundary = 0
        if self.BC == 'Non-Periodic':
            realSize = self.size[0]

            psi[:,0,0] = 0
            psi[:,realSize:,0] = 0
            psi[0,:,0] = 0
            psi[realSize:,:,0] = 0

            psi[:,0,realSize:] = 0
            psi[:,realSize:,realSize:] = 0
            psi[0,:,realSize:] = 0
            psi[realSize:,:,realSize:] = 0

            psi[0,0,:] = 0
            psi[realSize:,0,:] = 0

            psi[0,realSize:,:] = 0
            psi[realSize:,realSize:,:] = 0

        self.psi = psi

    def get_Forces(self):
        """
        The force at each point is defined as the gradient of the potential
        Evaluate the gradient using central differencing (could use a higher-order method if time)
        We then apply the force at each grid point to each particle lumped onto that grid point by the NGP method
        """

        F_gp = np.zeros([3,self.size[0],self.size[1],self.size[2]])
        self.get_Potential()
        #Central differencing to get force field on the grid points
        #Could replace this with a higher order scheme
        #np.roll(x,n,axis=0) shifts the array entries of x by n indices along axis 0

        F_gp[0] = 0.5*(np.roll(self.psi,1,axis=0)-np.roll(self.psi,-1,axis=0))
        F_gp[1] = 0.5*(np.roll(self.psi,1,axis=1)-np.roll(self.psi,-1,axis=1))
        F_gp[2] = 0.5*(np.roll(self.psi,1,axis=2)-np.roll(self.psi,-1,axis=2))

        F_gp = -self.G*self.rho*F_gp
        #Apply the force to each particle
        F_ptcls = np.moveaxis(F_gp,[0,1,2],[-1,-2,-3])
        F = F_ptcls[self.x_indexList]
        self.F = F

    def get_totalEnergy(self):
        """
        Track the total energy of the system as the sum of the kinetic and potential energies
        """
        vTot = np.sqrt(self.v[:,0]**2 + self.v[:,1]**2 + self.v[:,2]**2)
        KE = np.sum(self.m*(vTot**2))
        #Would be nice to take psi & rho as inputs to avoid calculating them redundantly
        psi = self.psi
        rho = self.rho
        PE = -0.5*np.sum(np.sum(psi)*rho)
        TE = KE + PE
        self.E = TE

    def time_stepping_leapfrog(self):
        """
        Evolves the particle's position and momentum using the leap frog method seen in class
        """
        #velocity update step
        if self.cosmology_mass:
            self.v[:,0] = self.v[:,0]+self.F[:,0]*self.dt/self.m[:,0]
            self.v[:,1] = self.v[:,1]+self.F[:,1]*self.dt/self.m[:,0]
            self.v[:,2] = self.v[:,2]+self.F[:,2]*self.dt/self.m[:,0]
        else:
            self.v[:,0] = self.v[:,0]+self.F[:,0]*self.dt/self.m
            self.v[:,1] = self.v[:,1]+self.F[:,1]*self.dt/self.m
            self.v[:,2] = self.v[:,2]+self.F[:,2]*self.dt/self.m
        #position update steps
        self.x = self.x+self.v*self.dt
        self.x = self.x%self.size[0]

    def advance_timeStep(self):
        #file_save=['x_data','E_data',1]
        """
        Take one step forward in time by getting the forces and taking a time step
        Also update the density and Green's function for the new particle distribution
        Output the particle positions and the total energy after the step
        """
        #Get the forces from the current particle distribution (psi is defined during this operation)
        self.get_Forces()
        #Get the total energy for the current particle distribution (needs psi)
        self.get_totalEnergy()
        #Move the particles according to the force field to get the new particle distribution
        #This method will update the positions and velocities of the particles
        self.time_stepping_leapfrog()
        #Update rho and Green's function for the new particle distribution
        self.get_NGPdensity()
        self.get_greensFunc()

        return self.E, self.x


import random

words = ['rainbow', 'computer', 'data', 'science', 'programming',
         'python', 'mathematics', 'player', 'condition',
         'reverse', 'water', 'board', 'keyboard', 'table']

secretWord = random.choice(words)
name = input("What is your name? : ")
print(f"Good Luck, {name}!")
print('\n')
print("Guess the Characters of the Secret Word :\n ")
correctWord = ''
for i in correctWord:
    print(i, end='')
turns = 15
while turns > 0:
    fails = 0
    for k in secretWord:
        if k in correctWord:
            print(k, end='')
        else:
            print('_', end='')
            fails += 1
    if fails == 0:
        print("\nYou Win!")
        print(f"The Word is : {secretWord} ")
        break
    print()
    guess = input("\nGuess a Character : ")
    correctWord += guess
    if guess not in secretWord:
        turns -= 1
        print(f"Wrong! You only have {turns} left")
        if turns == 0:
            print(f"You Lose!! The Word was {secretWord}")


from geosoup import MultiRaster
from geosoup import Raster, Opt, Vector, Handler
import multiprocessing as mp
from sys import argv
from copy import deepcopy
'''

ras = Raster("D:/temp/tree_cover/hansen_tc_mosaic_2010_byte_lzw_250m.tif")
ras.initialize()
print(ras)
mras=MultiRaster(filelist=["D:/temp/tree_cover/hansen_tc_mosaic_2010_byte_lzw_250m.tif",
                           "D:/temp/tree_cover/hansen_tc_mosaic_2010_byte_lzw_250m.tif",
                           "D:/temp/tree_cover/hansen_tc_mosaic_2010_byte_lzw_250m.tif"])

#lmras=mras.layerstack(outfile='D:/temp/tree_cover/hansen_tc_mosaic_2010_byte_lzw_250m_3band.tif')
#outlmras=Raster('D:/temp/tree_cover/hansen_tc_mosaic_2010_byte_lzw_250m_3band.tif')
#outlmras.datasource=lmras
#outlmras.initialize()

#outlmras.write_to_file(compress='lzw')

#res=mras.layerstack(outfile='D:/temp/tree_cover/hansen_tc_mosaic_2010_byte_lzw_250m_3band.tif',
#                    return_vrt=False,
#                    compress='lzw')

ras=Raster('D:/temp/tree_cover/hansen_tc_mosaic_2010_byte_lzw_250m_3band.tif')
ras.initialize()
ras.make_tile_grid(10240, 10240)
for tile in ras.tile_grid:
    print(tile)
ras.make_tiles(10240, 10240, "D:/temp/tree_cover/test_tiles", add_overview=True)
'''

'''
This script extracts sample vectors from raster tiles
in a folder. The name of each file is added to the csv as an attribute.
'''

def find_search_string(year):
    """
    Method to return the appropriate string to search for in the tile name
    based on the year of sample
    :param year: Year of sample
    :return: string or None
    """
    str_dict = {
        '_1992-': (1987, 1997),
        '_2000-': (1998, 2002),
        '_2005-': (2003, 2007),
        '_2010-': (2008, 2012),
        '_2015-': (2013, 2018)
    }

    for k, v in str_dict.items():
        if v[0] <= year <= v[1]:
            return k
    return

def find_intersection(name_tuple):
    """
    Method to identify geometries that intersect with the tile
    :param name_tuple: tuple containing - tile filename, vector filename, bounds wkt string
    :return: list or None
    """
    tile_filename, vector_filename, bounds_wkt = name_tuple

    bounds_geom = Vector.get_osgeo_geom(bound_wkt)

    all_samp_vec = Vector(vector_filename)

    temp_ras = Raster(tile_filename)
    temp_bounds = temp_ras.get_bounds()
    temp_wkt = Vector.wkt_from_coords(temp_bounds, geom_type='polygon')
    temp_geom = Vector.get_osgeo_geom(temp_wkt)
    temp_geom.CloseRings()

    if temp_geom.Intersects(bounds_geom):
        intrsct_list = []

        for samp_indx in range(all_samp_vec.nfeat):

            samp_geom = Vector.get_osgeo_geom(all_samp_vec.wktlist[samp_indx])

            samp_year = all_samp_vec.attributes[samp_indx]['year']
            samp_year_search_str = find_search_string(samp_year)

            if (samp_year_search_str is not None) and \
                    (samp_year_search_str in Handler(tile_filename).basename):
                if temp_geom.Intersects(samp_geom):
                    attr = all_samp_vec.attributes[samp_indx]
                    attr.update({'geom': all_samp_vec.wktlist[samp_indx]})
                    intrsct_list.append(attr)

        if len(intrsct_list) > 0:
            return {tile_filename: intrsct_list}

def tile_process(tile_info):
    """
    Method to provide coordinates of all the levels (max limit: nsamp)
    :param tile_info: Dictionary of the form : {tile_raster_path: [list of sample dicts]}
    :return: dictionary
    """

    tile_filename, geom_list = list(tile_info.items())[0]

    tile_ras = Raster(tile_filename)
    tile_ras.initialize()
    tile_bnames = tile_ras.bnames

    geom_wkt_list = [geom_dict['geom'] for geom_dict in geom_list]

    # dict of extracted values where keys are IDs
    extract_list = tile_ras.extract_geom(geom_wkt_list,
                                         pass_pixel_coords=True)

    print('Extract list is {} long from tile {}'.format(str(len(extract_list)), tile_name))

    out_list = []
    for samp_indx, samp_dict in enumerate(extract_list):
        if len(samp_dict['values']) > 0 and len(samp_dict['values'][0]) > 0:

            temp_dict = deepcopy(geom_list[samp_indx])
            samp_dict_with_bands = dict(zip(tile_bnames, samp_dict['values'][0]))
            temp_dict.update(samp_dict_with_bands)
            temp_dict.update({'filename': Handler(tile_filename).basename})
            out_list.append(temp_dict)

    print('Out list is {} long from tile {}'.format(str(len(out_list)), tile_name))

    if len(out_list) > 0:
        return out_list
    else:
        return

if __name__ == '__main__':

    """
    infile: Input raster tif file
    outfile: Output shapefile
    nsamp: Number of samples per class to be extracted
    start_level and end level: Classification levels from where to extract the samples
    step_level: Increments between start_level and end_level
    nprocs: Number of processes to use for sample extraction

    --------------------------------------------
    examples:
    """
    raster_filefolder = "D:/temp/tree_cover/test_tiles/"
    samp_shpfile = "D:/temp/tree_cover/all_samp_post_v9.shp"
    extract_file = "D:/temp/tree_cover/all_samp_post_v9_out.csv"
    # nprocs = 2

    # replace bound_coords with the following if no boundary needed:
    # bound_coords = None

    # script, raster_filefolder, samp_shpfile, extract_file, nprocs = argv
    # ------------------------------------------------------------------------------------------------------

    bound_coords = [[-165.90800781250002, 67.14281541784403], [-167.31425781250002, 66.93710574593051],
                    [-169.07207031250002, 64.40470750992607], [-167.66582031250002, 62.35795332711261],
                    [-164.32597656250002, 57.33622778331068], [-165.20488281250002, 53.96666515623615],
                    [-158.34941406250002, 53.550992243482334], [-148.85722656250002, 58.731933742605904],
                    [-142.35332031250002, 58.731933742605904], [-136.48051644679492, 56.74119582563745],
                    [-133.91582031250002, 54.48048639601067], [-129.69707031250002, 52.06354722436047],
                    [-124.7751953125, 48.93431376306091], [-116.36726129245775, 48.724285986503354],
                    [-107.9001953125, 48.47027580249403], [-94.5408203125, 47.17206587233248],
                    [-88.03968465179696, 46.4184607772877], [-83.99394531250002, 43.46597166198637],
                    [-82.93925781250002, 40.192611128052754], [-74.32597656250002, 43.33825798989073],
                    [-67.64628906250002, 42.17673121632382], [-58.32988281250001, 44.603271845712804],
                    [-53.23222656250001, 45.59587375476319], [-49.36503906250001, 49.39407810907766],
                    [-52.35332031250001, 54.27572510460249], [-54.63847656250001, 56.76258052056773],
                    [-61.66972656250001, 57.901054192561524], [-65.00957031250002, 57.901054192561524],
                    [-69.22832031250002, 57.24123463705217], [-80.82988281250002, 55.08866006127723],
                    [-88.74003906250002, 58.087383512987316], [-97.1775390625, 59.89795706904842],
                    [-105.7908203125, 62.194403351036605], [-116.5134765625, 65.5204149882913],
                    [-126.5330078125, 68.59904919862765], [-134.44316406250002, 69.54080414556246],
                    [-140.59550781250002, 69.16895364821778], [-144.81425781250002, 68.40579909921763],
                    [-151.66972656250002, 67.81603533682497], [-158.70097656250002, 67.27898929955994],
                    [-164.32597656250002, 67.00586941496265], [-165.90800781250002, 67.14281541784403]]

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

    bound_wkt = Vector.wkt_from_coords(bound_coords, geom_type='polygon')

    tile_list = Handler(raster_filefolder).find_all(pattern='*.tif')

    Opt.cprint('Found {} tiles'.format(str(len(tile_list))))
    Opt.cprint('---------------------------')

    tile_preprocess_list = [(tile_name, samp_shpfile, bound_wkt) for tile_name in tile_list]

    # nprocs = int(nprocs)
    # pool = mp.Pool(nprocs)

    tile_samp_list = []
    for tile_name in tile_preprocess_list:
        print(tile_name)

    for tile_tuple in tile_preprocess_list:
        result = find_intersection(tile_tuple)

        if result is not None:
            print(result)
            tile_name, sample_locs = list(result.items())[0]
            print('Number of samples: {}'.format(str(len(sample_locs))))
            tile_samp_list.append(result)

    Opt.cprint('Number of tiles to extract from: {}'.format(str(len(tile_samp_list))))
    Opt.cprint('---------------------------')

    for tile_samp in tile_samp_list:
        Opt.cprint(tile_samp)
    Opt.cprint('---------------------------')

    # pool = mp.Pool(nprocs)

    Handler(extract_file).file_delete()

    result_dicts = []
    for tile_samp in tile_samp_list:

        results = tile_process(tile_samp)

        print('results is {} long from tile {}'.format(str(len(results)), list(tile_samp.items())[0][0]))

        if results is not None:
            result_dicts += results

            if Handler(extract_file).file_exists():
                Handler.write_to_csv(results, outfile=extract_file, append=True, header=False)
            else:
                Handler.write_to_csv(results, outfile=extract_file, append=False, header=True)

            Opt.cprint('Extracted {} samples'.format(str(len(results))))

    Opt.cprint('---------------------------')
    for result in result_dicts:
        Opt.cprint(result)
    Opt.cprint('---------------------------')
    Opt.cprint('All tiles completed - writing csv')

    extract_file2 = Handler(extract_file).add_to_filename('_2')

    Handler.write_to_csv(result_dicts, outfile=extract_file2)

    Opt.cprint('Written : {}'.format(extract_file))


import tensorflow as tf

with tf.variable_scope("lr_model"):
    def linear_regression():#定义名字
        # 1）准备好数据集：y = 0.8x + 0.7 100个样本
        # 特征值X, 目标值y_true
        with tf.variable_scope("original_data"):#定义名字
            X = tf.random_normal(shape=(100, 1), mean=2, stddev=2, name="original_data_x")
            # y_true [100, 1]
            # 矩阵运算 X（100， 1）* （1, 1）= y_true(100, 1)
            y_true = tf.matmul(X, [[0.8]], name="original_matmul") + 0.7

        # 2）建立线性模型：
        # y = W·X + b，目标：求出权重W和偏置b
        # 3）随机初始化W1和b1

        with tf.variable_scope("linear_model"):#定义名字
            weights = tf.Variable(initial_value=tf.random_normal(shape=(1, 1)), name="weights")
            bias = tf.Variable(initial_value=tf.random_normal(shape=(1, 1)), name="bias")
            y_predict = tf.matmul(X, weights, name="model_matmul") + bias

        # 4）确定损失函数（预测值与真实值之间的误差）-均方误差
        with tf.variable_scope("loss"):#定义名字
            error = tf.reduce_mean(tf.square(y_predict - y_true), name="error_op")

        # 5）梯度下降优化损失：需要指定学习率（超参数）
        # W2 = W1 - 学习率*(方向)
        # b2 = b1 - 学习率*(方向)
        with tf.variable_scope("gd_optimizer"):#定义名字
            optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01, name="optimizer").minimize(error)

        # 2）收集变量
        tf.summary.scalar("error", error)##生成准确率标量图
        tf.summary.histogram("weights", weights)#用来显示直方图信息
        tf.summary.histogram("bias", bias)#用来显示直方图信息

        # 3）合并变量
        merge = tf.summary.merge_all()

        # 添加一个saver保存模型！！！！！！！！！！！！！！
        saver = tf.train.Saver()#实例化

        # 初始化变量
        init = tf.global_variables_initializer()
        # 开启会话进行训练
        with tf.Session() as sess:
            # 运行初始化变量Op
            sess.run(init)
            print("随机初始化的权重为%f， 偏置为%f" % (weights.eval(), bias.eval()))
            # 第2999步的误差为0  .000000，权重为0 .799999， 偏置为0 .700002
            # 1）创建事件文件【重要】
            file_writer = tf.summary.FileWriter(logdir="./summary", graph=sess.graph)

            #加载历史模型
            saver.restore(sess, "./summary/ckpt/linear/linear_regression.ckpt")

            # 训练模型
            for i in range(1000):
                sess.run(optimizer)
                print("第%d步的误差为%f，权重为%f， 偏置为%f" % (i, error.eval(), weights.eval(), bias.eval()))
                # 4）运行合并变量op
                summary = sess.run(merge)
                file_writer.add_summary(summary, i)#i保留每一次的数量
                # 训练过程比较长，保存一下，只会保存最近的五个！！！！！！！！
                saver.save(sess, "./summary/ckpt/linear/linear_regression.ckpt2")

if __name__ == '__main__':
    linear_regression()


from . import resnet
from . import pyramidnet
from . import wide_resnet
from .shakeshake import shake_resnet

def build_model(model_name, num_classes=10):
    if model_name in ['wideresnet-28-10', 'wrn-28-10']:
        model = wide_resnet.WideResNet(28, 10, 0, num_classes)

    elif model_name in ['wideresnet-40-2', 'wrn-40-2']:
        model = wide_resnet.WideResNet(40, 2, 0, num_classes)

    elif model_name in ['shakeshake26_2x32d', 'ss32']:
        model = shake_resnet.ShakeResNet(26, 32, num_classes)

    elif model_name in ['shakeshake26_2x96d', 'ss96']:
        model = shake_resnet.ShakeResNet(26, 96, num_classes)

    elif model_name in ['shakeshake26_2x112d', 'ss112']:
        model = shake_resnet.ShakeResNet(26, 112, num_classes)

    elif model_name == 'pyramidnet':
        model = pyramidnet.PyramidNet('cifar10', depth=272, alpha=200, num_classes=num_classes, bottleneck=True)

    elif model_name == 'resnet200':
        model = resnet.ResNet('imagenet', 200, num_classes, True)

    elif model_name == 'resnet50':
        model = resnet.ResNet('imagenet', 50, num_classes, True)

    return model


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

"""Padding operations for cylindrical data.

@@wrap_pad
@@wrap
"""

from __future__ import division

import tensorflow as tf
from math import floor, ceil

def wrap_pad(tensor, wrap_padding, axis=(1, 2)):
    """Apply cylindrical wrapping to one axis and zero padding to another.

    By default, this wraps horizontally and pads vertically. The axes can be
    set with the `axis` keyword, and the wrapping/padding amount can be set
    with the `wrap_pad` keyword.
    """
    rank = tensor.shape.ndims
    if axis[0] >= rank or axis[1] >= rank:
        raise ValueError(
                "Invalid axis for rank-{} tensor (axis={})".format(rank, axis)
              )

    # handle single-number wrap/pad input
    if isinstance(wrap_padding, list) or isinstance(wrap_padding, tuple):
        wrapping = wrap_padding[1]
        padding = wrap_padding[0]
    elif isinstance(wrap_padding, int):
        wrapping = padding = wrap_padding

    # set padding dimensions
    paddings = [[0, 0]] * rank
    paddings[axis[0]] = [floor(padding/2), ceil(padding/2)]

    return tf.pad(wrap(tensor, wrapping, axis=axis[1]), paddings, 'CONSTANT')

def wrap(tensor, wrapping, axis=2):
    """Wrap cylindrically, appending evenly to both sides.

    For odd wrapping amounts, the extra column is appended to the [-1] side.
    """
    rank = tensor.shape.ndims
    if axis >= rank:
        raise ValueError(
                "Invalid axis for rank-{} tensor (axis={})".format(rank, axis)
              )

    sizes = [-1] * rank

    sizes[axis] = ceil(wrapping/2)
    rstarts = [0]*rank
    rpad = tf.slice(tensor, rstarts, sizes)

    sizes[axis] = floor(wrapping/2)
    lstarts = [0]*rank
    lstarts[axis] = tensor.shape.as_list()[axis] - floor(wrapping/2)
    lpad = tf.slice(tensor, lstarts, sizes)

    return tf.concat([lpad, tensor, rpad], axis=axis)

def unwrap(tensor, wrapping, axis=2):
    """Removes wrapping from an image.

    For odd wrapping amounts, this assumes an extra column on the [-1] side.
    """
    rank = tensor.shape.ndims
    if axis >= rank:
        raise ValueError(
                "Invalid axis for rank-{} tensor (axis={})".format(rank, axis)
              )

    sizes = [-1] * rank
    sizes[axis] = tensor.shape.as_list()[axis] - wrapping

    starts = [0] * rank
    starts[axis] = floor(wrapping/2)

    return tf.slice(tensor, starts, sizes)
    #return tensor[:,:,1:-1,:]


import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from Loss_legacy import DSSIMLoss
import numpy as np
from Blocks import DiscriminatorBlock
from CustomLayers import EqualizedLinear, EqualizedConv2d, View
from Losses import MyLogisticGAN

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

class _RESOBLOCK(nn.Module):
    def __init__(self, in_chan, out_chan):
        super(_RESOBLOCK, self).__init__()
        self.conv0 = nn.Conv2d(in_chan, out_chan, 1)
        self.conv1 = nn.Conv2d(in_chan, out_chan, 3)
        self.conv2 = nn.Conv2d(in_chan, out_chan, 5)
        self.conv3 = nn.Conv2d(in_chan, out_chan, 7)

    def forward(self, x):
        shp = x.shape
        x0 = F.upsample(self.conv0(x), size=shp[2:], mode='bilinear')
        x1 = F.upsample(self.conv1(x), size=shp[2:], mode='bilinear')
        x2 = F.upsample(self.conv2(x), size=shp[2:], mode='bilinear')
        x3 = F.upsample(self.conv3(x), size=shp[2:], mode='bilinear')
        x_comb = (x0+x1+x2+x3)/1.0
        return x_comb

class _ResRESOBLOCK(nn.Module):
    def __init__(self, in_chan, out_chan):
        super(_ResRESOBLOCK, self).__init__()
        self.resoblock0 = _RESOBLOCK(in_chan, out_chan)
        self.resoblock1 = _RESOBLOCK(out_chan, out_chan)
        self.leak0 = nn.LeakyReLU(0.1, inplace=False)
        self.leak2 = nn.LeakyReLU(0.1, inplace=False)
        self.bn = nn.BatchNorm2d(out_chan)
        self.conv = nn.Conv2d(in_chan, out_chan, 1)

    def forward(self, x):
        identity = self.conv(x)
        x = self.resoblock0(x)
        x = self.leak0(x)
        x = self.resoblock1(x)
        x = x+identity
        x = self.leak2(x)
        x = self.bn(x)
        return x

class MyDiscriminator(nn.Module):
    def __init__(self):
        super(MyDiscriminator, self).__init__()
        act, gain = {'relu': (torch.relu, np.sqrt(2)), 'lrelu': (nn.LeakyReLU(negative_slope=0.2), np.sqrt(2))}['lrelu']
        self.DisBlock0 = DiscriminatorBlock(3, 128, gain=gain, use_wscale=True, activation_layer=act, blur_kernel=[1, 2, 1])
        self.DisBlock1 = DiscriminatorBlock(128, 128, gain=gain, use_wscale=True, activation_layer=act, blur_kernel=[1, 2, 1])
        self.DisBlock2 = DiscriminatorBlock(128, 128, gain=gain, use_wscale=True, activation_layer=act, blur_kernel=[1, 2, 1])
        self.DisBlock3 = DiscriminatorBlock(128, 128, gain=gain, use_wscale=True, activation_layer=act, blur_kernel=[1, 2, 1])
        self.DisBlock4 = DiscriminatorBlock(128, 128, gain=gain, use_wscale=True, activation_layer=act, blur_kernel=[1, 2, 1])
        self.DisBlock5 = DiscriminatorBlock(128, 64, gain=gain, use_wscale=True, activation_layer=act, blur_kernel=[1, 2, 1])
        self.view = View(-1)
        self.linear0 = EqualizedLinear(1024, 1024, gain=gain, use_wscale=True)
        self.linear1 = EqualizedLinear(1024, 1024, gain=gain, use_wscale=True)
        self.act = act

    def forward(self, x):
        x = self.DisBlock0(x)
        x = self.DisBlock1(x)
        x = self.DisBlock2(x)
        x = self.DisBlock3(x)
        x = self.DisBlock4(x)
        x = self.DisBlock5(x)
        x = self.view(x)
        x = self.act(self.linear0(x))
        x = self.act(self.linear1(x))
        return x

class RESOAUGNET(nn.Module):
    def __init__(self):
        super(RESOAUGNET, self).__init__()
        self.resreso0 = _ResRESOBLOCK(3, 128)
        self.activ = nn.Sigmoid()
        self.dssim = DSSIMLoss()
        self.mse = nn.MSELoss()
        self.l1 = nn.L1Loss()
        self.conv = nn.Conv2d(128, 3, 1)
        self.noise = torch.randn([1, 3, 256, 256]).float().to(device)
        self.noise = self.noise*0.2
        self.noise.requires_grad = True

    def forward(self, x):
        x = x+self.noise
        x = self.resreso0(x)
        x = self.conv(x)
        x = self.activ(x)
        return x

    def gram_matrix(self, y):
        (b, ch, h, w) = y.size()
        features = y.reshape([b, ch, w * h])
        # features = y.view(b, ch, w * h)
        features_t = features.transpose(1, 2)
        gram = features.bmm(features_t) / (ch * h * w)
        return gram

    def loss(self, x, y):
        loss_d = self.dssim(x, y)
        loss_m = self.l1(x, y)
        g_x = self.gram_matrix(x)
        g_y = self.gram_matrix(y)
        loss_g = self.mse(g_x, g_y)
        loss = (loss_d+loss_m)/2.0+loss_g*100.0/2.0
        return loss

def load(path):
    model = RESOAUGNET().to(device)
    model.load_state_dict(torch.load(path, map_location=device))
    model.eval()
    return model

def predict_one(img, model):
    img = img/255.0
    img = np.array([img], dtype=np.float32)
    img = img.transpose(0, 3, 1, 2)
    img = torch.from_numpy(img).float().to(device)
    pred = model(img)[0].permute(1,2,0).cpu().detach().numpy()*255.0
    pred = pred.astype(np.uint8)
    return pred

if __name__=='__main__':
    '''
    cfg.model.g_optim.learning_rate = 0.003
    cfg.model.g_optim.beta_1 = 0
    cfg.model.g_optim.beta_2 = 0.99
    cfg.model.g_optim.eps = 1e-8
    '''
    x = torch.randint(0, 255, (5,3,256,256)).float()/255
    x = x.to(device)
    dis = MyDiscriminator()
    gen = RESOAUGNET()
    GanLoss = MyLogisticGAN(dis)
    pred = gen(x)
    gen_loss = GanLoss.gen_loss(x, pred)
    pred = pred.detach()
    dis_loss = GanLoss.dis_loss(x, pred)
    print(gen_loss, dis_loss)


import os

import pytest

from stable_baselines import PPO2

@pytest.mark.parametrize("cliprange", [0.2, lambda x: 0.1 * x])
@pytest.mark.parametrize("cliprange_vf", [None, 0.2, lambda x: 0.3 * x, -1.0])
def test_clipping(cliprange, cliprange_vf):
    """Test the different clipping (policy and vf)"""
    model = PPO2('MlpPolicy', 'CartPole-v1',
                 cliprange=cliprange, cliprange_vf=cliprange_vf).learn(1000)
    model.save('./ppo2_clip.zip')
    env = model.get_env()
    model = PPO2.load('./ppo2_clip.zip', env=env)
    model.learn(1000)

    if os.path.exists('./ppo2_clip.zip'):
        os.remove('./ppo2_clip.zip')


import RPi.GPIO as GPIO
import time

# 13, 16, 18, 37
WE = 38
OE = 35

A = [22, 3, 5, 7, 29, 31, 26, 24, 21, 19, 40, 15]
D = [23, 32, 33, 8, 10, 36, 11, 12]

chip = 0
writeZeros = False
doFullClear = False
verifyOnly = False
changeMode = True
dataFile = "out.txt"

def setAddress(addr):
    for i in range(len(A)):
        bit = addr & 1
        if(bit):
            GPIO.output(A[i], GPIO.HIGH)
        else:
            GPIO.output(A[i], GPIO.LOW)

        addr = addr >> 1

def readByte(addr):
    setAddress(addr)
    byte = 0
    for i in range(len(D)):
        byte += GPIO.input(D[i]) << len(D)
        byte = byte >> 1
    return byte

def writeByte(addr, byte):
    setAddress(addr)

    for i in range(len(D)):
        bit = byte & 1
        if(bit):
            GPIO.output(D[i], GPIO.HIGH)
        else:
            GPIO.output(D[i], GPIO.LOW)

        byte = byte >> 1
    time.sleep(0.001)
    GPIO.output(WE, GPIO.LOW)
    time.sleep(0.01)
    GPIO.output(WE, GPIO.HIGH)
    time.sleep(0.005)

def setupRead():
    for i in range(len(D)):
        GPIO.setup(D[i], GPIO.IN)
    GPIO.output(OE, GPIO.LOW)
    time.sleep(0.0005)

def setupWrite():
    for i in range(len(D)):
        GPIO.setup(D[i], GPIO.OUT)
    GPIO.output(OE, GPIO.HIGH)
    time.sleep(0.0005)

def clear():
    print("Clearing entire chip...")
    for i in range(4096):
        writeByte(i, 0)

displayCount = 0

def display(byte):
    global displayCount
    displayCount += 1

    if displayCount % 16 == 1:
        print(hex(displayCount-1)+": "),

    hexstring = hex(byte)[2:]
    if byte < 16:
        hexstring = "0" + hexstring
    print(hexstring),

    if displayCount % 4 == 0:
        print(" "),
    if displayCount % 16 == 0:
        print("")

GPIO.setmode(GPIO.BOARD)
GPIO.setup(WE, GPIO.OUT)
GPIO.setup(OE, GPIO.OUT)

for i in range(len(A)):
    GPIO.setup(A[i], GPIO.OUT)

GPIO.output(WE, GPIO.HIGH)
GPIO.output(OE, GPIO.HIGH)

f = open(dataFile, "r")
f.readline()

setupWrite()
if doFullClear:
    clear()

line = f.readline()[:-1]
bytes = []
addr = 0
if changeMode:
    setupRead()

while line:
    byte = (int(line, 16)>>8*chip) % 256
    display(byte)
    bytes.append(byte)
    if(byte != 0 or writeZeros or changeMode):
        if not verifyOnly:
            if changeMode:
                if(not readByte(addr) == byte):
                    setupWrite()
                    writeByte(addr, byte)
                    setupRead()
            else:
                writeByte(addr, byte)
    addr += 1
    line = f.readline()[:-1]

print("")
print("Verifying...")

setupRead()
foundError = False
for i in range(addr):
    if(readByte(i) != bytes[i]):
        print("I/O error: Byte "+str(i)+" invalid! expceted " + hex(bytes[i]) + ", read "+hex(readByte(i)))
        foundError = True

if not foundError:
    print("Success!")

GPIO.cleanup()


import os
from collections import deque
from copy import deepcopy
from math import inf
from random import choice
from timeit import default_timer

# Goal state.
goal = [['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '10', '11', '12'], ['13', '14', '15', '0']]

# Load a puzzle state from a specified text file.
def load(puzzle):
    with open(puzzle, "r") as f:
        lines = f.readlines()[:4]
        puzzle = [line.strip().split(" ") for line in lines]

    return puzzle

# Get the coordinates of a number tile in the puzzle.
def find(puzzle, num):
    for row in puzzle:
        if num in row:
            return [puzzle.index(row), row.index(num)]

# Check whether the puzzle is solvable.
# Implementation inspired by: https://www.geeksforgeeks.org/check-instance-15-puzzle-solvable/
def solvable(puzzle):
    # Transform the puzzle to a list.
    puzzle_as_list = []
    for row in puzzle:
        for num in row:
            if int(num) != 0:
                puzzle_as_list.append(int(num))

    # Calculate inversions
    inversions = 0
    for i, n in [(i, n) for i, n in enumerate(puzzle_as_list)]:
        j = i + 1
        while j < len(puzzle_as_list):
            if puzzle_as_list[j] < n:
                inversions += 1
            j += 1

    # Puzzle is solvable iff
    # blank is in even row and number of inversions is odd or
    # blank is in odd row and number of inversions is even.
    blank_row = find(puzzle[::-1], "0")[0]+1
    if (blank_row % 2 == 0) == (inversions % 2 != 0):
        return True
    else:
        return False

# Append a puzzle to a text file.
def save_puzzle(puzzle, file):
    with open(file, "a") as f:
        if file == "puzzle_solution.txt":
            for row in puzzle:
                new_row = []
                for num in row:
                    if int(num) == 0:
                        new_row.append("   ")
                    elif int(num) < 10:
                        new_row.append(" " + str(num) + " ")
                    else:
                        new_row.append(str(num) + " ")
                f.write("".join(new_row) + "\n")
            f.write("\n\n")
        else:
            for row in puzzle:
                f.write(" ".join(row) + "\n")

# Get possible moves of the blank tile.
def get_moves(puzzle):
    # List potential moves in order: Up, Right, Down, Left.
    potential_moves = [[-1, 0], [0, 1], [1, 0], [0, -1]]

    # Check which of the potential moves are possible (in bounds).
    possible_moves = []
    for pm in potential_moves:
        y, x = find(puzzle, "0")
        y += pm[0]
        x += pm[1]
        if 0 <= y < 4:
            if 0 <= x < 4:
                possible_moves += [[pm[0], pm[1]]]

    return possible_moves

# Move the blank tile in the puzzle.
def move(puzzle, direction):
    # Deepcopy in order not to modify the original.
    new_puzzle = deepcopy(puzzle)
    y, x = find(new_puzzle, "0")
    # Position blank tile will move to.
    y_new, x_new = y + direction[0], x + direction[1]
    # Swap blank tile with tile in direction.
    new_puzzle[y][x], new_puzzle[y_new][x_new] = new_puzzle[y_new][x_new], new_puzzle[y][x]

    return new_puzzle

# Shuffle the goal state by a specified number of moves.
def shuffle(goal, number):
    # Deepcopy in order not to modify the original.
    puzzle = deepcopy(goal)
    # File name based on number of moves, remove file if already existing.
    file = "puzzle_start"+str(number)+".txt"
    if os.path.exists(file):
        os.remove(file)
    # Make number of moves in goal puzzle..
    for i in range(number-1):
        moves = get_moves(puzzle)
        puzzle = move(puzzle, choice(moves))

    save_puzzle(puzzle, file)

# Manhattan distance as sum of all distances between the tile start and goal position
# + 2* the number of linear conflicts, where two tiles are in the same row/col,
# their goal position is in the same row/col and one tile is in the way of the other tile's goal position.
# Implementation inspired by:
# https://algorithmsinsight.wordpress.com/graph-theory-2/a-star-in-general/implementing-a-star-to-solve-n-puzzle/
def heuristic_mh_lc(puzzle):
    distance = 0
    for i in range(1, 15):
        x1 = find(puzzle, str(i))[1]
        y1 = find(puzzle, str(i))[0]
        x2 = find(goal, str(i))[1]
        y2 = find(goal, str(i))[0]
        distance += abs(x2 - x1) + abs(y2 - y1)

    conflicts = 0
    # Linear conflicts in rows.
    for y in range(3):
        row = puzzle[y]
        for i, n in enumerate(row):
            if i < len(row)-1:
                next = row[i+1]
                if n != "0":
                    goal_row_num = find(goal, str(n))[0]
                    goal_row_next = find(goal, str(next))[0]
                    if goal_row_num == goal_row_next and int(n) > int(next):
                        conflicts += 1

    # Linear conflicts in columns.
    for x in range(3):
        col = [puzzle[0][x], puzzle[1][x], puzzle[2][x], puzzle[3][x]]
        for i, n in enumerate(col):
            if i < len(col)-1:
                next = col[i+1]
                if n != "0":
                    goal_col_num = find(goal, str(n))[1]
                    goal_col_next = find(goal, str(next))[1]
                    if goal_col_num == goal_col_next and int(n) > int(next):
                        conflicts += 1

    return distance + 2 * conflicts

# Create dicts from databases
db1 = {}
with open("database1.txt", "r") as f:
    for line in f.readlines():
        db1[line[2:12]] = int(line[15:].strip().replace("]", ""))
db2 = {}
with open("database2.txt", "r") as f:
    for line in f.readlines():
        db2[line[2:12]] = int(line[15:].strip().replace("]", ""))
db3 = {}
with open("database3.txt", "r") as f:
    for line in f.readlines():
        db3[line[2:12]] = int(line[15:].strip().replace("]", ""))

# Implementation inspired by:
# https://algorithmsinsight.wordpress.com/graph-theory-2/implementing-bfs-for-pattern-database/
def heuristic_pd(puzzle):
    distance = 0

    # Add cost of each pattern to distance
    pos1 = ""
    for t in ["1", "2", "3", "4", "7"]:
        pos1 += str(find(puzzle, t)[0]) + str(find(puzzle, t)[1])
    distance += db1[pos1]

    pos2 = ""
    for t in ["5", "6", "9", "10", "13"]:
        pos2 += str(find(puzzle, t)[0]) + str(find(puzzle, t)[1])
    distance += db2[pos2]

    pos3 = ""
    for t in ["8", "11", "12", "14", "15"]:
        pos3 += str(find(puzzle, t)[0]) + str(find(puzzle, t)[1])
    distance += db3[pos3]

    return distance

# Solve the puzzle using the IDA* algorithm.
# Adapted pseudo code from https://en.wikipedia.org/wiki/Iterative_deepening_A*.
def ida_star(puzzle):
    begin = default_timer()

    # Delete previous solution.
    if os.path.exists("puzzle_solution.txt"):
        os.remove("puzzle_solution.txt")

    # Initialize starting state, bound and queue.
    puzzle = load(puzzle)
    bound = heuristic_pd(puzzle)
    path = deque([puzzle])

    # If puzzle is not solvable, throw error.
    if not solvable(puzzle):
        return "Puzzle is not solvable!"

    # Start main part of the search
    print("Searching for solution...")
    while True:
        # Call search function
        t = search(path, 0, bound)

        # If found, save the path to the text file and print amount of moves,
        # time taken and path as moves of the blank tile.
        if t == "FOUND":
            for s in path:
                save_puzzle(s, "puzzle_solution.txt")

            # Get the moves of the blank tile as Up, Right, Down, Left.
            directions = []
            for i, m in enumerate(path):
                if i < len(path)-1:
                    next = path[i+1]
                    direction = [find(next, "0")[0] - find(m, "0")[0], find(next, "0")[1] - find(m, "0")[1]]
                    if direction == [-1, 0]:
                        directions.append("Up")
                    elif direction == [0, 1]:
                        directions.append("Right")
                    elif direction == [1, 0]:
                        directions.append("Down")
                    elif direction == [0, -1]:
                        directions.append("Left")

            # End timer and print the results.
            end = default_timer()
            return "Found solution with " + str(len(path) - 1) + " moves in " \
                   + str(round(end - begin, 2)) + " seconds." + "\n" + \
                   "Moves: " + ", ".join(directions) + "\n"

        if t == inf:
            return "NOT_FOUND"

        bound = t

# Search function to use in IDA*
def search(path, g, bound):
    # Get state f-value.
    state = path[-1]
    f = g + heuristic_pd(state)

    # If f-value exceeds threshold, return f for new threshold.
    if f > bound:
        return f
    # If state is goal state, return to main function.
    elif state == goal:
        return "FOUND"
    # Else, set minimum to infinite, generate next states
    # and recursively call function itself, updating minimum.
    else:
        min = inf
        next_states = [move(state, m) for m in get_moves(state)]
        for s in next_states:
            if s not in path:
                path.append(s)
                t = search(path, g+1, bound)
                if t == "FOUND":
                    return "FOUND"
                if t < min:
                    min = t
                path.pop()

    return min

# Starting puzzles.
# shuffle(goal, 25)
# shuffle(goal, 50)
# shuffle(goal, 100)
# shuffle(goal, 500)
# shuffle(goal, 1000)
puzzle25 = "puzzle_start25.txt"
puzzle50 = "puzzle_start50.txt"
puzzle100 = "puzzle_start100.txt"
puzzle500 = "puzzle_start500.txt"
puzzle1000 = "puzzle_start1000.txt"
puzzleT = "puzzle_startT.txt"

# TODO: Pick a starting puzzle
print(ida_star(puzzle1000))


from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys

class MainDemo(QMainWindow):
    my_signal = pyqtSignal(str)
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置窗口标题
        self.setWindowTitle('vilogy')
        label = QLabel('Here is vilogy!')
        label.setAlignment(Qt.AlignCenter)
        self.setCentralWidget(label)

        # Add toolbox widget
        tb = QToolBar('Tools')
        tb.setIconSize(QSize(16, 16))
        self.addToolBar(tb)

        # Bool button action
        button_action = QAction(QIcon('keda_16.png'), 'Menu Button', self)
        button_action.setStatusTip('This is menu button')
        button_action.triggered.connect(self.onButtonClick)
        button_action.setCheckable(True)
        tb.addAction(button_action)
        self.setStatusBar(QStatusBar(self))

        # Add new menu
        button_action2 = QAction('PyQt5', self)
        button_action3 = QAction('Torch', self)
        button_action2.setCheckable(True)
        button_action3.setCheckable(True)
        button_action2.triggered.connect(self.onButtonClick)
        button_action3.triggered.connect(self.onButtonClick)

        # Menu & action
        mb = self.menuBar()
        mb.setNativeMenuBar(False)
        file_menu = mb.addMenu('&File')
        file_menu.addAction(button_action)

        # Add seperator
        file_menu.addSeparator()
        # Add secondary menu
        python_menu = file_menu.addMenu('Python')
        python_menu.addAction(button_action2)
        python_menu.addSeparator()
        python_menu.addAction(button_action3)

    def onButtonClick(self, s):
        print(s)

# 创建应用实例
# 通过sys.argv传入命令行参数
App = QApplication(sys.argv)
# 创建窗口实例
Demo = MainDemo()
# 显示窗口
Demo.show()
# 执行应用
# 进入事件循环
App.exec_()


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
from bs4 import BeautifulSoup
import time
import keyboard
import os
from termcolor import cprint
#def start(url):

def fun(urls,dir_name,keywords_of_ss):
    k=1
    for elem in keywords_of_ss:
        for element in urls:
            if(elem in element):
                name_of_ss=k  ############################### COMPLETE THIS
                driver=webdriver.Chrome(executable_path=r"D:\Dhanbad\chromedriver.exe")
                time.sleep(2)
                #if(keyboard.is_pressed('q')):
                #   break
                try:
                    driver.get(element)
                    driver.maximize_window()
                    #print(os.getcwd(),"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
                    driver.save_screenshot(os.getcwd() + "\\Screen-Shots\\" + str(name_of_ss) + "_ss.png")
                    driver.close()
                except:
                    driver.close()
                k+=1

def get(url,lst,depth,tag,attribute,c,name_file,k,l,keywords_of_ss):
    print(c)
    strngs=[]
    if( (lst==[] or lst == None) and k==1):
        f=open(f"./{name_file}/{name_file}_{k}.txt","w")
        driver=webdriver.Chrome(executable_path=r"D:\Dhanbad\chromedriver.exe")
        driver.get(url)
        elem = driver.find_elements_by_tag_name(tag)
        for lnk in elem:
            if(lnk.get_attribute(attribute) != None and lnk.get_attribute(attribute)  != ""):
                if(lnk.get_attribute(attribute) not in lst):
                        if(l):
                            f.write(lnk.get_attribute(attribute)+"\n")
                        lst.append(lnk.get_attribute(attribute))
        f.close()
        driver.close()
        if(tag=="a" and keywords_of_ss  != None and keywords_of_ss != ""):
            fun(lst,c,keywords_of_ss)
        return(lst)
    elif(k<=depth):
        k+=1
        for element in lst:
            f=open(f"./{file_name}/{file_name}_{k}.txt","w")
            driver=webdriver.Chrome(executable_path=r"D:\Dhanbad\chromedriver.exe")
            driver.get(element)
            elem = driver.find_elements_by_tag_name(tag)
            for lnk in elem:
                if(lnk.get_attribut(attribute) not in lst):
                    if(l):
                        f.write(lnk.get_attribute(attribute)+"\n")
                    lst.append(lnk.get_attribute(attribute))
            driver.close()
        if(tag=="a" and keywords_of_ss  != None and keywords_of_ss != ""):
            fun(lst,c,keywords_of_ss)
            f.close()
            return(lst)


# -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 00:18:47 2018

@author: Sergey
"""
import numpy as NP
from BadaryRAO import BadaryRAO

class srhArray():
    def __init__(self, fromFits = None):
        self.RAO = BadaryRAO()
        self.sizeOfUv = 256
        self.uvLcp = NP.zeros((self.sizeOfUv,self.sizeOfUv),dtype=complex);
        self.uvRcp = NP.zeros((self.sizeOfUv,self.sizeOfUv),dtype=complex);
        if fromFits is None:
            self.uvPlane = NP.zeros((self.uvSize, self.uvSize))


"""
"""
from __future__ import division, print_function
from extractwords import ExtractWords, getPaths
from emaildata import EmailData
from random import shuffle, random
from sklearn.svm import SVC
from id3 import Id3
from math import sqrt
import time

class SerialPredict:

    def __init__(self, spampaths, hampaths, findmsgfts=False, msgfts="message.fts"):
        self.spampaths = spampaths
        self.hampaths = hampaths
        self.msgfts = ExtractWords.getMessageFeatures(msgfts)
        self.vector = self.getFeatureVector()
        self.inputs, self.outputs = self.getIO()
        if findmsgfts:
            self.ew = ExtractWords(self.spampaths, self.hampaths, nummsgfeatures=200)
            self.ew.countWords(self.ew.spampaths, self.ew.hampaths)
            self.msgfts = self.ew.msgfeatures

    def getFeatureVector(self):
        vector = []
        vector += self.msgfts
        return vector

    def generateMessageVector(self, emo):
        msgvector = []
        msg = emo.message
        msglist = msg.split()
        for word in self.msgfts:
            if word in msglist:
                msgvector.append(1)
            else:
                msgvector.append(0)
        return msgvector

    def generateFeatureVector(self, emailpath):
        vector = []
        emo = EmailData(emailpath)
        vector += self.generateMessageVector(emo)
        return vector

    def getIO(self):
        vector = []
        for i, spam in enumerate(self.spampaths):
            if i % 100 == 0:
                print("Generating vector for spam number {}.".format(i))
            svec = self.generateFeatureVector(spam) + [1]
            vector.append(svec)
        for i, ham in enumerate(self.hampaths):
            if i % 100 == 0:
                print("Generating vector for ham number {}.".format(i))
            hvec = self.generateFeatureVector(ham) + [0]
            vector.append(hvec)
        shuffle(vector)
        invec = [x[:-1] for x in vector]
        outvec = [x[-1] for x in vector]
        return invec, outvec

def svmTest():
    """
    Decision based on python sklearn-SVM
    """
    h, s = getPaths("spam", "ham")
    sp = SerialPredict(s[:3000], h[:3000])
    # print(sp.inputs)
    # print(sp.outputs)
    trainsize = 5000
    clf = SVC(kernel="linear")
    clf.fit(sp.inputs[:trainsize], sp.outputs[:trainsize])
    testCorrect(trainsize, clf, sp.inputs, sp.outputs)

def id3test():
    """
    Prediction based on a single decision tree
    About 5% less accurate than linear svm.  Maybe will do better in parallel,
        as a decision forest?
    """
    h, s = getPaths("spam", "ham")
    sp = SerialPredict(s[:6500], h[:6500])
    vectors = [x + [sp.outputs[i]] for i, x in enumerate(sp.inputs)]
    dec = Id3(vectors[:10000], header=False, test_set=vectors[10000:])
    dec.learnModel()
    right = dec.testExamples(dec.test_set)
    print(right)

def forestTest():
    """
    """
    forest = []
    h, s = getPaths("spam", "ham")
    exnum = 10000
    testnum = 3000
    sp = SerialPredict(s[:exnum//2], h[:exnum//2])
    sptest = SerialPredict(s[exnum//2: exnum//2 + testnum//2], h[exnum//2: exnum//2 + testnum//2])
    vectors = [x + [sp.outputs[i]] for i, x in enumerate(sp.inputs)]
    testvectors = [x + [sptest.outputs[i]] for i, x in enumerate(sptest.inputs)]
    numtrees = 25
    for i in range(numtrees):
        print("Learning tree {}.".format(i+1))
        splitnum1 = int((i/numtrees) * exnum)
        splitnum2 = int(((i+1)/numtrees) * exnum)
        dec = Id3(vectors[splitnum1:splitnum2], header=False)
        dec.titles = sp.vector
        dec.learnModel()
        dec.writeModel("forest/tree{}.txt".format(i))
        forest.append(dec)
    right = 0
    for i, example in enumerate(testvectors):
        if i % 100 == 0:
            print("Testing example {}.".format(i))
        answers = [0, 0]
        for tree in forest:
            a = tree.classify(example[:-1])
            if a == 0:
                answers[0] += 1
            else:
                answers[1] += 1
        if answers[0] > answers[1]:
            a = 0
        else:
            a = 1
        if a == example[-1]:
            right += 1
    print("Decision forest of {} trees got {} right.".format(numtrees, right/len(testvectors)))

def randomForest():
    """
    not working
    """
    forest = []
    h, s = getPaths("spam", "ham")
    exnum = 10000
    testnum = 3000
    sp = SerialPredict(s[:exnum//2], h[:exnum//2])
    sptest = SerialPredict(s[exnum//2: exnum//2 + testnum//2], h[exnum//2: exnum//2 + testnum//2])
    vectors = [x + [sp.outputs[i]] for i, x in enumerate(sp.inputs)]
    testvectors = [x + [sptest.outputs[i]] for i, x in enumerate(sptest.inputs)]
    numtrees = 25
    treefeatures = []
    for i in range(numtrees):
        print("Learning tree {}.".format(i+1))
        featurechoices = []  # indeces of sqrt(len(example)) features
        baggedvector = []
        for j in range(int(.7 * len(sp.vector))):
            ind = int(random() * len(sp.vector))  # note that the same number could be generated. This is ok.
            featurechoices.append(ind)
        treefeatures.append(featurechoices)
        for k in range(len(vectors)):
            baggedvector.append([vectors[k][j] for j in featurechoices] + [vectors[k][-1]])
        # print("featurechoices: {}".format(featurechoices))
        # print("baggedvector: {}".format(len(baggedvector)))
        # print("baggedvector[0]: {}".format(len(baggedvector[0])))
        # print(len(baggedvector))
        # print(len(baggedvector[0]))
        dec = Id3(baggedvector, header=False)
        dec.titles = [sp.vector[x] for x in featurechoices]
        dec.learnModel()
        dec.writeModel("forest/tree{}.txt".format(i))
        forest.append(dec)
    right = 0
    for i, example in enumerate(testvectors):
        if i % 100 == 0:
            print("Testing example {}.".format(i))
        answers = [0, 0]
        for k, tree in enumerate(forest):
            # print(treefeatures[k])
            # print(len(example))
            examplemod = [example[j] for j in treefeatures[k]] + [example[-1]]
            a = tree.classify(examplemod[:-1])
            if a == 0:
                answers[0] += 1
            else:
                answers[1] += 1
        if answers[0] > answers[1]:
            a = 0
        else:
            a = 1
        if a == examplemod[-1]:
            right += 1
    print("Decision forest of {} trees got {} right.".format(numtrees, right/len(testvectors)))

if __name__ == '__main__':
    start = time.time()
    # svmTest()
    id3test()
    # forestTest()
    # randomForest()
    end = time.time()
    print("Total Serial Time: {} seconds.".format(end-start))