#!/usr/bin/env python3

import subprocess
import requests

def location() -> (float, float):
    try:
        process = subprocess.run(
            ['CoreLocationCLI', '-once', 'YES',
             '-format', '%latitude\n%longitude'],
            stdout=subprocess.PIPE,
            encoding='utf8',
            timeout=2,
        )
    except FileNotFoundError:
        print("CoreLocationCLI not installed")
        return (None, None)
    lines = str(process.stdout).splitlines()
    if len(lines) < 2:
        return (None, None)
    latitude = lines[0]
    longitude = lines[1]
    return (latitude, longitude)

def first_value(d: dict):
    return d['values'][0]['value']

def weather(latitude: float, longitude: float) -> dict:
    response = requests.get(
        'https://api.weather.gov/points/{lat},{lon}'
        .format(lat=latitude, lon=longitude),
        timeout=5,
    )
    forecast_url = response.json()['properties']['forecastGridData']
    response = requests.get(forecast_url, timeout=5)
    json = response.json()
    actual_lat, actual_lon = json['geometry']['coordinates'][0][0]
    props = json['properties']
    return {
        'code': 0,
        'coordinates': {
            'latitude': actual_lat,
            'longitude': actual_lon,
        },
        'humidity': first_value(props['relativeHumidity']) / 100.0,
        'apparentTemperature': first_value(props['apparentTemperature']),
        'temperature': first_value(props['temperature']),
        'wind': {
            'chill': first_value(props['windChill']),
            'direction': first_value(props['windDirection']),
            'speed': first_value(props['windSpeed']),
        },
        'units': {
            'temperature': 'C',
            'apparentTemperature': 'C',
        },
    }

last_location = (None, None)

def raw_weather_info():
    global last_location
    latitude, longitude = location()
    error = None
    if latitude is None or longitude is None:
        error = 'Error getting current location.'
        if last_location[0] is None or last_location[1] is None:
            return {'error': error}
        latitude = last_location[0]
        longitude = last_location[1]
    else:
        last_location = (latitude, longitude)
    try:
        info = weather(latitude, longitude)
        if error is not None:
            info['error'] = error
        return info
    except Exception as e:
        return {'error': 'Error parsing weather information: ' + str(e)}

if __name__ == '__main__':
    print(raw_weather_info())


from flask import Flask, render_template, request, jsonify
from faker import Faker
import random
import urllib2
import simplejson

fake = Faker()

app = Flask(__name__)

class Programmer(object):

    def __init__(self, name):
        self.name=name
        self.rsvp=self.answer()
        self.image=self.img()
        #self.image="http://"
        self.arrived=False

    def answer(self):
        a = ["yes", "no", "maybe"]
        return random.choice(a)

    def img(self):
        fetcher = urllib2.build_opener()
        searchTerm = self.name
        startIndex = "0"
        searchUrl1 = "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + searchTerm + "&start=" + startIndex
        searchUrl = searchUrl1.replace(' ', '%20')
        f = fetcher.open(searchUrl)
        deserialized_output = simplejson.load(f)
        imageUrl = deserialized_output['responseData']['results'][0]['unescapedUrl']
        return imageUrl

    #def imggoo(self):
    #    options = images.ImageOptions()
    #    options.image_type = images.ImageType.FACE
    #    results = google.search_images(self.name, options)
    #    return results
    # INSANELY ugly thing to use

visitors = []

for x in xrange(15):
    programmer = Programmer(fake.name())
    visitors.append(programmer)

vis = []

for v in visitors:
    vis.append({"name" : v.name, "rsvp" : v.rsvp, "image" : v.image, "arrived" : v.arrived});

#ipdb.set_trace()

@app.route('/programmers')
def programmers():
    return(jsonify(results=vis))

@app.route('/')
def index():
    return render_template('index.html')

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


# Read a file

with open('bupa.data', 'r') as f:
 lines = f.readlines()

lastListEle=[]
matrixEle = []
newMatrixEle = []

for line in lines:
  #print(type(line)) # string
  linecp = line[0:-1] # remove '\n'
  rowdata = linecp.split(',')
  #print(rowdata)
  #newRowdata = list(map(lambda x :float(x),rowdata[0:-1]))
  newRowdata = rowdata[0:-1]
  #print(newRowdata)
  #print(type(rowdata)) # list type
  matrixEle.append(rowdata)
  newMatrixEle.append(newRowdata)
  lastListEle.append(rowdata[-1]) # last element into lastListEle

#print(newMatrixEle)
#print(lastListEle)

outa = open('a.data','w')
for itema in newMatrixEle:
  outa.write(','.join(itema)+'\n')
outb = open('b.data','w')
for itemb in lastListEle:
  print >> outb, itemb
outa.close()
outb.close()


from collections import OrderedDict
import numpy as np
import cv2
import dlib
import imutils
from matplotlib import pyplot as plt

CHEEK_IDXS = OrderedDict([("left_cheek", (1,2,3,4,5,48,49,31)),
                        ("right_cheek", (11,12,13,14,15,35,53,54))
                         ])

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

img = cv2.imread('img1.jpg')
img = imutils.resize(img, width=600)

overlay = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

detections = detector(gray, 0)
for k,d in enumerate(detections):
    shape = predictor(gray, d)
    for (_, name) in enumerate(CHEEK_IDXS.keys()):
        pts = np.zeros((len(CHEEK_IDXS[name]), 2), np.int32)
        for i,j in enumerate(CHEEK_IDXS[name]):
            pts[i] = [shape.part(j).x, shape.part(j).y]

        pts = pts.reshape((-1,1,2))
        cv2.polylines(overlay,[pts],True,(0,255,0),thickness = 2)

    cv2.imshow("Image", overlay)
    cv2.waitKey(0)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()


from src.DataSetReader import DataSetReader
import pandas as pd
#date,county,state,fips,cases,deaths

class StateDataSetReader(DataSetReader):

    def __init__(self):
        self.df = pd.read_csv("../data/us-states.csv")
        self.df = self.df.drop("fips",axis=1)

    def display(self):
        print(self.df)

if __name__ == '__main__':
    StateDataSetReader().display()


class Node():
    def __init__(self, elem):
        self.elem = elem
        self.next = None

class SingleLink():
    def __init__(self, node=None):
        self.__head = node
        if node is not None:
            node.next = node

    def is_empty(self):
        """
        判断链表是否为空
        :return:
        """
        return self.__head == None

    def get_length(self):
        """
        得到链表的长度
        :return:
        """
        cursor = self.__head
        if self.__head is None:
            return 0
        count = 1
        while (cursor.next != self.__head):
            count += 1
            cursor = cursor.next
        return count

    def travel(self):
        """
        遍历链表
        :return:
        """
        link = "head->"
        cursor = self.__head
        if cursor is None:
            link = "空链表"
            print(link)
            return
        link += str(cursor.elem)
        cursor = cursor.next
        while (cursor != self.__head):
            link += "->" + str(cursor.elem)
            cursor = cursor.next
        link += "->head"
        print(link)
        return

    def add(self, elem):
        """
        头插
        :param Node:
        :return:
        """
        # 空
        tmp_node = Node(elem)
        if self.__head is None:
            self.__head = tmp_node
            tmp_node.next = tmp_node
        last_node = self.__head
        while (last_node.next != self.__head):
            last_node = last_node.next
        tmp_node.next = self.__head
        self.__head =tmp_node
        last_node.next = tmp_node
        return

    def append(self, elem):
        """
        尾插
        :param Node:
        :return:
        """
        tmp_node = Node(elem)
        cursor = self.__head
        if cursor is None:
            self.__head = tmp_node
            tmp_node.next =tmp_node
            return
        while (cursor.next != self.__head):
            cursor = cursor.next
        cursor.next = tmp_node
        tmp_node.next = self.__head
        return

    def insert(self, pos, elem):
        """
        指定位置插入 从1开始，指定你想插入元素的位置
        :param pos:
        :param node:
        :return:
        """
        cursor = self.__head
        tmp_node = Node(elem)
        count = 1
        if pos < 1 or pos > self.get_length() + 1:
            print("输入错误，请重试")
            return
        elif pos == 1:
            # 头插
            self.add(elem)
            return
        elif pos == self.get_length()+1:
            self.append(elem)
            return
        else:
            while (cursor is not None):
                if count == pos - 1:
                    tmp_cursor = cursor.next
                    cursor.next = tmp_node
                    tmp_node.next = tmp_cursor
                    break
                cursor = cursor.next
                count += 1
            return

    def remove_node(self, elem):
        """
        删除节点
        :param node:
        :return:
        """
        cursor_pre = None
        cursor = self.__head
        if self.__head == None:
            print("空链表 删除失败")
            return False
        if self.get_length() == 1:
            self.__head = None
            print("删除成功")
            return True
        last_node = self.__head
        while (last_node.next != self.__head):
            last_node =last_node.next
        while (cursor.next != self.__head):
            if cursor.elem == elem:
                if cursor == self.__head:
                    self.__head = cursor.next
                    last_node.next = self.__head
                else:
                    cursor_pre.next = cursor.next
                print("删除成功")
                return True
            cursor_pre = cursor
            cursor = cursor.next
        if cursor.elem == elem:
            cursor_pre.next = cursor.next
            print("删除成功")
            return True
        print("未发现相关元素，删除失败")
        return False

    def search(self, elem):
        """
        判断节点是否存在
        :param node:
        :return:
        """
        cursor = self.__head
        while (cursor.next != self.__head):
            if cursor.elem == elem:
                return True
            cursor = cursor.next
        if cursor.elem == elem :
            return True
        return False

if __name__ == '__main__':
    single_link = SingleLink()
    single_link.add(0)
    #print(single_link.get_length())
    single_link.travel()
    single_link.add(1)
    single_link.travel()
    single_link.add(2)
    single_link.travel()
    single_link.add(3)
    single_link.travel()
    print("链表长度"+str(single_link.get_length()))
    single_link.insert(2,4)
    single_link.travel()
    print(single_link.remove_node(0))
    single_link.travel()
    print(single_link.remove_node(1))
    single_link.travel()
    print(single_link.remove_node(3))
    single_link.travel()


#CREATED BY: Aaryn Coutanche -> aaryncoutanche@gmail.com
import socket, threading, time, sys, api

HOST, PORT = '127.0.0.1', int(sys.argv[1])

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(1)

print('Open HTTP server on port %s ...' % PORT)

serverRunning = True
def filterRequest(data, depth):
    data = data.replace('\r', '')
    data = data.split('\n')
    request = []
    for x in range(depth):
        request.append(data[x])
    return request
def main():
    global sock, serverRunning
    try:
        conn, addr = sock.accept()
    except:
        return
    request = conn.recv(1024)
    uri = filterRequest(request, 1)[0].split(' ')[1]
    uri = uri.split('/')
    uri.pop(0)
    conn.sendall(api.proc(uri))
    conn.close()

def keyListener():
    global serverRunning
    while serverRunning:
        data = raw_input('>>> ')
        if data == 'close':
            serverRunning = False
    sock.shutdown(socket.SHUT_RDWR)
threading.Thread(target=keyListener).start()
while serverRunning:
    main()

sock.close()
print('Closed HTTP server on port %s ...' % PORT)


"""
scrapple.selectors.selector
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Defines Scrapple selectors
"""

from __future__ import print_function
import requests
from lxml import etree

class Selector(object):
	"""
	Selector defines the basic selector object.
	"""

	def __init__(self, url):
		try:
			self.content = requests.get(url).content
			self.tree = etree.HTML(self.content)
		except requests.exceptions.MissingSchema:
			raise Exception('URL should be of the form "http://<page_link>')
		except requests.exceptions.InvalidURL:
			raise Exception('The URL provided is invalid')
		except requests.exceptions.ConnectionError:
			raise Exception('Ensure that you are connected to the Internet and that the page exists')

	def extract_content(self, selector, attr, default):
		"""
		Method for performing the content extraction for the particular selector type.
		"""
		raise NotImplementedError

	def extract_links(self):
		"""
		Method for performing the link extraction for the crawler.
		"""
		raise NotImplementedError

	def extract_tabular(self):
		"""
		Method for performing the content extraction from tabular organized data.
		"""
		raise NotImplementedError


import constants
import pygame as game
import os
import math
import random
import Utility_Functions as util
from point import point

class shotgun_shot:
    def __init__(s, pos = [0, 0], speed = 50, direction = "right"):
        s.pos = [int(pos[0]), int(pos[1])]
        s.speed = int(constants.FPS / speed)
        s.clock = 1
        s.direction = direction

        s.animation_clips = [game.image.load(os.getcwd() + '\\images\\Shooting_anim\\shotgun\\' + s.direction + "\\img_" + str(x) + ".png") for x in range(len(os.listdir(os.getcwd() + '\\images\\Shooting_anim\\shotgun\\' + s.direction)))]
        s.animation_index = 0
        s.animation_index_max = len(s.animation_clips) - 1

        s.rect = s.animation_clips[0].get_rect()
        s.middle = [s.pos[0] + s.rect[2] / 2, s.pos[1] + s.rect[3] / 2]
        if s.direction == "down":
            for x in range(1, s.rect[3] + 1):
                s.weapon_hitbox = [int(s.pos[0]), int(s.pos[1]), int(s.pos[0] + s.rect[2]), int(s.pos[1] + s.rect[3] + x)]
                pixel = constants.screen.get_at([s.weapon_hitbox[2], s.weapon_hitbox[1]])[0:3]
                if pixel[0] == 33 and pixel[1] == 33 and pixel[2] == 255:
                    break
            if x != s.rect[3]:
                print(s.animation_index_max - 1)
                print(math.floor(x / 2))
        elif s.direction == "right":
            for x in range(s.rect[2] + 1):
                s.weapon_hitbox = [int(s.middle[0] + x), int(s.middle[1])]
                pixel = constants.screen.get_at([s.weapon_hitbox[0], s.weapon_hitbox[1]])#[0:3]
                if pixel[2] == 255:
                    break
            if x != s.rect[3]:
                s.animation_index_max = math.floor(x / s.rect[2] * s.animation_index_max)
        elif s.direction == "left":
            for x in range(s.rect[2] + 1):
                s.weapon_hitbox = [int(s.middle[0] - x), int(s.middle[1])]
                pixel = constants.screen.get_at([s.weapon_hitbox[0], s.weapon_hitbox[1]])#[0:3]
                if pixel[2] == 255:
                    break
            if x != s.rect[3]:
                s.animation_index_max = math.floor(x / s.rect[2] * s.animation_index_max)
        elif s.direction == "up":
            for x in range(s.rect[3] + 1):
                s.weapon_hitbox = [int(s.middle[0]), int(s.middle[1] - x)]
                pixel = constants.screen.get_at([s.weapon_hitbox[0], s.weapon_hitbox[1]])#[0:3]
                if pixel[2] == 255:
                    break
            if x != s.rect[3]:
                s.animation_index_max = math.floor(x / s.rect[2] * s.animation_index_max)
    def update(s):
        if(s.clock % s.speed == 0):
            if(s.animation_index != s.animation_index_max):
                s.animation_index += 1
            else:
                constants.deleteMe.append(s)
        s.clock += 1
    def DrawMe(s):
        game.draw.rect(constants.screen, (255, 0, 102), (s.pos[0], s.pos[1], s.rect[0], s.rect[1]))
    def draw(s):
        constants.screen.blit(s.animation_clips[s.animation_index], (s.pos[0], s.pos[1], s.rect[0], s.rect[1]))


#!/usr/bin/python3

import discord
from discord.ext import commands
import asyncio

import math

class Pages:
    def __init__(self,
                 ctx,
                 current_page=1,
                 msg=None,
                 item_list=[],
                 title='Paginator',
                 display_option=(1, 0),
                 editable_content=True):
        """Creates a paginator.

        Parameters
        -----------
        ctx: discord.ext.commands.Context
            The current context (guild, channel, etc for bot to send messages).
        current_page: int
            Specify which page to display.
        msg: discord.Message
            This is helpful for delete function. Specify which message the bot needs to update if an element in the original message is modified.
        item_list: list or dictionary
            List of items to paginate. Using a dictionary is only useful for embeds option where there is a need for field names and values.
        title: str
            Summary of content of the items.
        display_option: tuple
            The first record of the tuple may have these values:
                0   : Messages will be in code blocks, the number of entries for each page is
                    defined by user (autosize = False), and item_list will be a list of strings
                    corresponding to the pages.
                1   : Code blocks, autosize = True, item_list is a list of strings.
                2   : Embed, autosize = False, item_list is a dictionary with two keys: names & values
                    the values of which will be a list. (item_list = {'names': [], 'values': []})
                3   : Embed, autosize = False, item_list is a list of strings.
                4   : Embed, autosize = True, item_list is a dictionary.
                5   : Embed, autosize = True, item_list is a list of strings.
            The second record is the user defined size of each page. For autosize = True, this value
            is ignored.
        editable_content: bool
            True if the items can be updated by the users (this is like an MVC).
            False otherwise.
        """
        self.bot = ctx.bot
        self.guild = ctx.guild
        self.channel = ctx.channel
        self.user = ctx.author
        self.message = msg
        self.itemList = item_list
        self.title = title
        self.displayOption = display_option
        self._organize()
        self.actions = [
            ('⏪', self._first_page),
            ('◀', self._prev_page),
            ('▶', self._next_page),
            ('⏩', self._last_page),
            ('⏹', self._halt),
        ]
        if editable_content:
            self.actions.append(('🚮', self._del))
        self.currentPage = current_page
        self.delete = False

    def _organize(self):
        organize_helper_map = {
            0: self._organize_code_blocks,
            1: self._organize_code_blocks_autosize,
            2: self._organize_embeds_dict,
            3: self._organize_embeds_list,
            4: self._organize_embeds_autosize_dict,
            5: self._organize_embeds_autosize_list,
        }
        pages_to_send = ['empty page']
        self.organize_helper = organize_helper_map[self.displayOption[0]]
        self.pagesToSend, self.lastPage = self.organize_helper(pages_to_send)

    def _organize_code_blocks(self, pages_to_send):
        item_per_page = self.displayOption[1]
        page_counter = math.ceil(len(self.itemList) / item_per_page)
        for i in range(page_counter):
            index_start = item_per_page * i
            index_end = item_per_page * (i + 1)
            content = '\n'.join(self.itemList[index_start:index_end]).replace(
                '```', '')
            pages_to_send.append('```markdown\n' + content +
                                 '\n\n~ Page {:02d} of {:02d} ~'.format(
                                     i + 1, page_counter) + '```')
        return pages_to_send, page_counter

    def _organize_code_blocks_autosize(self, pages_to_send):
        page_counter = length = cache = 0
        for i in range(len(self.itemList)):
            # truncate quotes that are too long
            if len(self.itemList[i]) > 1200:
                self.itemList[i] = self.itemList[i][:1200] + '...'
            length += len(self.itemList[i])
            if length > 1894:
                pages_to_send.append(
                    '```markdown\n' + self.title + ':\n\n' +
                    '\n'.join(self.itemList[cache:i]).replace('```', ''))
                cache = i
                length = len(self.itemList[i])
                page_counter += 1
            elif i == len(self.itemList) - 1:    # edge case
                pages_to_send.append(
                    '```markdown\n' + self.title + ':\n\n' +
                    '\n'.join(self.itemList[cache:i + 1]).replace('```', ''))
                page_counter += 1
        for i in range(len(pages_to_send)):
            pages_to_send[i] += '\n\n~ Page {:02d} of {:02d} ~'.format(
                i, page_counter) + '```'
        return pages_to_send, page_counter

    def _organize_embeds_dict(self, pages_to_send):
        item_per_page = self.displayOption[1]
        page_counter = math.ceil(len(self.itemList['names']) / item_per_page)
        em = discord.Embed(title=self.title, colour=0xDA291C)
        for i in range(page_counter):
            em.set_footer(
                text='Page {:02d} of {:02d}'.format(i + 1, page_counter))
            index_start = item_per_page * i
            index_end = item_per_page * (i + 1)
            for name, val in zip(
                    self.itemList['names'][index_start:index_end],
                    self.itemList['values'][index_start:index_end]):
                em.add_field(name=name, value=val)
            pages_to_send.append(em)
            em = discord.Embed(title=self.title, colour=0xDA291C)
        return pages_to_send, page_counter

    def _organize_embeds_list(self, pages_to_send):
        item_per_page = self.displayOption[1]
        page_counter = math.ceil(len(self.itemList) / item_per_page)
        em = discord.Embed(title=self.title, colour=0xDA291C)
        for i in range(page_counter):
            em.set_footer(
                text='Page {:02d} of {:02d}'.format(i + 1, page_counter))
            index_start = item_per_page * i
            index_end = item_per_page * (i + 1)
            em.description = ''.join(self.itemList[index_start:index_end])
            if len(em.description) > 1200:
                em.description = em.description[:1200] + '...'
            pages_to_send.append(em)
            em = discord.Embed(title=self.title, colour=0xDA291C)
        return pages_to_send, page_counter

    def _organize_embeds_autosize_dict(self, pages_to_send):
        # TODO: implement real autosize™
        # this method should not be called at the moment
        # itemPerPage = 10
        pass

    def _organize_embeds_autosize_list(self, pages_to_send):
        pass

    async def _show_page(self, page):
        self.currentPage = max(0, min(page, self.lastPage))
        if self.message:
            if self.currentPage == 0:
                try:
                    await self.message.delete()
                    self.message = None
                    return
                except:
                    pass
            else:
                if self.displayOption[0] < 2:    # code blocks
                    await self.message.edit(
                        content=self.pagesToSend[self.currentPage])
                else:    # embeds
                    await self.message.edit(
                        embed=self.pagesToSend[self.currentPage])
                return
        else:
            if self.displayOption[0] < 2:
                self.message = await self.channel.send(
                    content=self.pagesToSend[self.currentPage],
                    delete_after=300)
            else:
                self.message = await self.channel.send(
                    embed=self.pagesToSend[self.currentPage], delete_after=300)
            for (emoji, _) in self.actions:
                await self.message.add_reaction(emoji)
            return

    async def _first_page(self):
        await self._show_page(1)

    async def _prev_page(self):
        await self._show_page(max(1, self.currentPage - 1))

    async def _next_page(self):
        await self._show_page(min(self.lastPage, self.currentPage + 1))

    async def _last_page(self):
        await self._show_page(self.lastPage)

    async def _halt(self):
        await self._show_page(0)

    async def _del(self):
        self.delete = True
        await self._show_page(self.currentPage)

    def _react_check(self, reaction, user):
        if user == self.bot.user:
            return False
        if reaction.message.id != self.message.id:
            return False
        for (emoji, action) in self.actions:
            if reaction.emoji != emoji:
                continue
            self.user = user
            self._turn_page = action
            return True
        return False

    async def paginate(self):
        if self.delete:
            self.delete = False
            self._organize()
        await self._show_page(self.currentPage)
        while not self.delete and self.message:
            try:
                reaction, user = await self.bot.wait_for(
                    'reaction_add', check=self._react_check)
            except:
                try:
                    await self.message.delete()
                except:
                    pass
                finally:
                    break
            await self._turn_page()
            try:
                await self.message.remove_reaction(reaction, user)
            except:
                pass


from .dojo_test_case import DojoVCRTestCase
from .dojo_test_case import DojoTestCase
import logging
from vcr import VCR
from django.urls import reverse

logger = logging.getLogger(__name__)

class GoogleSheetsConfigTestApi(DojoVCRTestCase):
    fixtures = ['dojo_testdata.json']

    def __init__(self, *args, **kwargs):
        DojoTestCase.__init__(self, *args, **kwargs)

    def assert_cassette_played(self):
        if True:  # set to True when committing. set to False when recording new test cassettes
            self.assertTrue(self.cassette.all_played)

    def _get_vcr(self, **kwargs):
        my_vcr = super(GoogleSheetsConfigTestApi, self)._get_vcr(**kwargs)
        my_vcr.record_mode = 'once'
        my_vcr.path_transformer = VCR.ensure_suffix('.yaml')
        my_vcr.cassette_library_dir = 'dojo/unittests/vcr/google_sheets/'
        return my_vcr

    def setUp(self):
        super().setUp()
        self.client.force_login(self.get_test_admin())

    def test_config_google_sheets(self):
        # To regenerate the cassette, use an actual credentials json file
        with open('tests/test-dojo-sheets-NONEXISTING.json', 'rb') as f:
            data = {}
            # fail on purpose to get all the fields dynamically
            response = self.client.post(reverse('configure_google_sheets'), data, follow=True)
            form = response.context['form']
            self.assertEqual(form.is_valid(), False)

            for field in form:
                # do not consider the "protect" checkbox, leave them as is
                if 'Protect' in field.html_name:
                    continue
                # Select Hide (0) by default
                data.update({field.html_name: 0})

            data.update({
                # To regenerate the cassette, use non-revoked credentials
                # The json file is a real json file, but the account is disabled and the key deleted
                # The VCR does not recognize the stream otherwise, and will not match causing tests to fail :sob: :shrug:
                # due to the bearer token having to remain in the vcr yaml
                'email_address': 'test-dojo-sheets@test-dojo-sheets.iam.gserviceaccount.com',
                # needs to match ID in the cassette
                'drive_folder_ID': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
                'enable_service': 'on',
                'cred_file': f
            })
            # force use of specific submit button
            data.update({
                'update': 'Submit'
            })

            response = self.client.post(reverse('configure_google_sheets'), data, follow=True)
            self.assertContains(response, "successfully")
            self.assert_cassette_played()


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

import tornado.gen
import handlers.base_handler
from django import forms

class PersonRoleForm(forms.Form):

    role = forms.CharField(required=True)
    description = forms.CharField(required=False)

class CreatePersonRoleHandler(
    handlers.base_handler.BaseHandler):

    @property
    def access(self):
        return [
            "OWNER",
            "ADMIN"
        ]

    @tornado.gen.coroutine
    def post(self):
        customer_id = self.get_argument("customer_id", None)
        customer_id = int(customer_id) if isinstance(customer_id, int) else None

        if customer_id is not None:
            cursor = yield self.db.execute(
                "select * from customer.customer where id=%s limit 1",
                (customer_id,))

            if cursor.rowcount > 0:
                person_role_form = PersonRoleForm({
                    "rple": self.get_argument("role", None),
                    "description": self.get_argument("description", None),
                })

                if person_role_form.is_valid():
                    data = person_role_form.date
                    data.update({
                        "customer_id": customer_id,
                    })

                    cursor = yield self.db.execute(
                        """insert into customer.persone_role(
                            customer_id, role, description)
                        values(%(customer_id)s, %(role)s, %(description)s)
                        returning id""",
                        data)

                    result = cursor.fetchone()

                    self.finish({
                        "status": True,
                        "role_id": result[0],
                    })

                else:
                    self.finish({
                        "status": False,
                        "errors": person_role_form.errors,
                    })

            else:
                self.finish({
                    "status": False,
                    "errors": {"customer_id": ["Invalid customen Id"]}
                })

        else:
            self.finish({
                "status": False,
                "errors": {"customer_id": ["Customer Id is required"]}
            })


#!/usr/bin/python3
#
# Copyright 2015 MarkLogic Corporation
#
# This script takes a JSON object that enumerates a set of artifacts and
# removes those artifacts from the server.
#
# See put-config.py
#
# For example:
#
# python3 delete-config --json /tmp/config.json
#
# TODO
#

__author__ = 'pmb'

import argparse
import logging
import json
import os
import base64
import logging
from requests.auth import HTTPDigestAuth
from marklogic.connection import Connection
from marklogic.models.database import Database
from marklogic.models.forest import Forest
from marklogic.models.permission import Permission
from marklogic.models.privilege import Privilege
from marklogic.models.role import Role
from marklogic.models.server import Server
from marklogic.models.user import User

#logging.basicConfig(level=logging.INFO)

parser = argparse.ArgumentParser()
parser.add_argument("--host", action='store', default="localhost",
                    help="Management API host")
parser.add_argument("--username", action='store', default="admin",
                    help="User name")
parser.add_argument("--password", action='store', default="admin",
                    help="Password")
parser.add_argument("--json", action="store",
                    help="Name of the file containing JSON config")
parser.add_argument('--debug', action='store_true',
                    help='Enable debug logging')
args = parser.parse_args()

if args.debug:
    logging.basicConfig(level=logging.WARNING)
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("marklogic").setLevel(logging.DEBUG)

with open(args.json) as data_file:
    data = json.load(data_file)

conn = Connection(args.host, HTTPDigestAuth(args.username, args.password))

# Delete users
for config in data['users']:
    name = config['user-name']
    user = User.lookup(conn, name)
    if user is not None:
        verb = "Deleting"
        user = User.unmarshal(config)
        print("{0} user: {1}".format(verb, name))
        user.delete(conn)

# Delete privileges
for config in data['privileges']:
    name = config['privilege-name']
    kind = config['kind']
    priv = Privilege.lookup(conn, name, kind)
    if priv is not None:
        verb = "Deleting"
        priv = Privilege.unmarshal(config)
        print("{0} {1} privilege: {2}".format(verb, kind, name))
        priv.delete(conn)

# Delete roles
for config in data['roles']:
    name = config['role-name']
    role = Role.lookup(conn, name)
    if role is not None:
        print("Deleting role: {0}".format(name))
        role = Role(name)
        role.delete(conn)

# Delete servers
for config in data['servers']:
    name = config['server-name']
    group = config['group-name']
    server = Server.lookup(conn, name, group)
    if server is not None:
        verb = "Deleting"
        server = Server.unmarshal(config)
        kind = server.server_type()
        print("{0} {1} server: {2}".format(verb, kind, name))
        server.delete(conn)

# Delete databases
for config in data['databases']:
    name = config['database-name']
    db = Database.lookup(conn, name)
    if db is not None:
        print("Deleting database: {0}".format(name))
        db.delete(connection=conn)

# Delete forests
for config in data['forests']:
    name = config['forest-name']
    f = Forest.lookup(conn, name)
    if f is not None:
        print("Deleting forest: {0}".format(name))
        f.delete(connection=conn)


#!/usr/bin/env python2

# Copyright (C) 2014 Hiroki Horiuchi <x19290@gmail.com>
#
# [GNU all-permissive license]
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.
# This file is offered as-is, without any warranty.

from unittest import TestCase, TestProgram

import pythonpath
pythonpath
from py import md_or_dos

class T0grub_msdos(TestCase):
    def test(self):
        expected = '(md/3)', '(md/10)', '(hd1,msdos3)'
        got = md_or_dos('/dev/md3'), md_or_dos('/dev/md/10'), md_or_dos('b3')
        self.assertEqual(expected, got)

if __name__ == '__main__':
    TestProgram()


def main():
    # Основная функция.
    print("""
    МЕНЮ:
    1 - Записать данные в файл.
    2 - Прочитать данные из файла.
    """)
    choice = int(input('Ваш выбор - '))
    if choice == 1:
        write_golf()
    elif choice == 2:
        read_golf()
    else:
        print('Нет такого пункта в меню.')

def write_golf():
    # Записывает достижения игрока в файл golf.txt.

    # Открываю файл golf.txt в режим записи.
    golf = open('golf.txt', 'w')

    more = 'y'

    while more != 'n':
        name = input('Имя игрока: ')
        points = int(input('Заработал очков: '))
        # Записываю эти данные в файл.
        golf.write(name + "\n")
        golf.write(str(points) + "\n")

        # Предлагаю записать еще 1 игрока.
        more = input("'n' - чтобы завешить запись. ")

    # Закрываю файл.
    golf.close()

def read_golf():
    # Считывает информацию с файла golf.txt.

    # Открываю файл golf.txt в режиме чтения.
    golf = open('golf.txt', 'r')

    # Читаю первую строку в файле.
    name = golf.readline()

    while name != '':
        # Читаю счёт
        points = float(golf.readline())

        # Удаляю \n из имени.
        name = name.rstrip('\n')

        print('Игрок: ', name, '.', sep='')
        print('Заработал(а) -', points, 'балов.')

        # Читаю еще одно имя.
        name = golf.readline()

    # Закрываю файл.
    golf.close()

main()


from django.core import serializers
from django.db.models import Q
from django.shortcuts import get_object_or_404, get_list_or_404
from django.http import HttpResponse
from .models import *
import json

def index(request):
    return HttpResponse("Hello, world. You're at the radio index.")

def station(request, station_id):
    """
    Haal informatie op voor een enkel radiostation.
    """
    station = get_object_or_404(Station, id=station_id)

    serialized_station = serializers.serialize('json', [station])

    return HttpResponse(json.dumps(json.loads(serialized_station)[0]))

def stations(request):
    """
    Haal lijst op van alle radiostations.
    """
    stations = Station.objects.all()

    serialized_stations = serializers.serialize('json', stations)

    return HttpResponse(serialized_stations)

def station_played_tracks(request, station_id, limit=50):
    """
    Haal de laatst afgespeelde tracks op voor een radiostation.
    """
    played_tracks = get_list_or_404(
        PlayedTrack.objects.order_by('-pk'),
        station=station_id
    )[:limit]

    serialized_played_tracks = serializers.serialize(
        'json',
        played_tracks,
        use_natural_foreign_keys=True,
        use_natural_primary_keys=True
    )
    return HttpResponse(serialized_played_tracks)

def track(request, track_id):
    """
    Haal de informatie op voor een enkele track.
    """
    track = get_object_or_404(Track, id=track_id)

    serialized_track = serializers.serialize('json', [track])

    return HttpResponse(json.dumps(json.loads(serialized_track)[0]))

def tracks(request, track_ids):
    """
    Haal de informatie op voor meerdere tracks.
    """
    track_ids = track_ids.split(',')

    # Query opbouwen; vergelijkbaar met WHERE IN (1...n)
    q = Q()
    for ti in track_ids:
        q = q | Q(id=ti)

    tracks = get_list_or_404(Track, q)

    serialized_tracks = serializers.serialize('json', tracks)

    return HttpResponse(serialized_tracks)


import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
import random as random

"""
training model - only PM2.5
"""

csvfile = open('train.csv', encoding='Big5')

x = [] #record x

for row in csvfile:
    r = row.split('\n')
    d = r[0].split(',')
    x.append(d)

x.pop(0) #skip first row

#extract PM2.5
f = []
for row in x:
    if(row[2] == 'PM2.5'):
        row.pop(0)
        row.pop(0)
        row.pop(0)
        f.append(row)

for row in range(len(f)):
    for col in range(len(f[row])):
        f[row][col] = float(f[row][col])

X = [] #input
Y = [] #ground truth
days = 10 #all = len(f)
for n in range(5,15):
    for i in range(0, len(f[n]) - 10):
        X.append(f[n][i:i+9])
        Y.append(f[n][i + 9])

#y' = b + w1*x1 + w2*x2 + w3*x3 + w4*x4 + w5*x5 + w6*x6 + w7*x7 + w8*x8 + w9*x9
#y' = b + w[1:9] * x[1:9]'

b = 2.5 #initial b
w = np.ones(len(X[0])) #initial w (w1,w2...,w9)
for i in range(len(w)):
    w[i] = 0.5
lr = 100 #initial learning rate
iteration = 50000

b_lr = 0.0
w_lr = 0.0

#Store_initial values for plotting
b_history = [b]
w_history = [w]

#regularization
l = 0.1

#Iteration
for i in range(iteration):

    b_grad = 0.0
    w_grad = np.zeros(len(w))
    for n in range(len(X)):
        wX = np.dot(w, X[n])
        #print("wX: " + str(wX))
        b_grad = b_grad - 2.0*(float(Y[n]) - b - wX)*1.0
        for j in range(len(w_grad)):
            w_grad[j] = w_grad[j] - 2.0*(float(Y[n]) - b - wX)*X[n][j] - (l * 2 * w[j])

    #print("bg: " + str(b_grad))
    #print("wg: " + str(w_grad[0]))

    b_lr = b_lr + b_grad**2
    w_lr = w_lr + w_grad**2

    # Update parameters
    b = b - lr/np.sqrt(b_lr) * b_grad
    w = w - lr/np.sqrt(w_lr) * w_grad

    # Store parameters for plotting
    b_history.append(b)
    w_history.append(w)

    error = 0
    for n in range(len(X)):
        wX = np.dot(w, X[n])
        error += (Y[n] - (b + wX))**2 + l * np.dot(w, w)
    error = np.sqrt(error / len(X))
    if(i % 100 == 0):
        print("i: " + str(i) + "error: " + str(error))

outfile = open('weightone1.txt','w')
outfile.write(str(b) + '\n')
outfile.write(str(w))
outfile.close()

print("b: " + str(b))
print(w)


from django.shortcuts import redirect, render
from django.utils.lru_cache import lru_cache
from django.utils.translation import ugettext_lazy
from wagtail.wagtailadmin import messages
from wagtail.wagtailadmin.edit_handlers import ObjectList, TabbedInterface
from wagtail.wagtailcore.models import Site

from .models import SiteMetadataPreferences

@lru_cache()
def get_edit_handler(cls):
    if hasattr(cls, 'edit_handler'):
        return cls.edit_handler.bind_to_model(cls)

    tabs = []

    tabs.append(ObjectList(cls.general_panels, heading=ugettext_lazy('General')))
    tabs.append(ObjectList(cls.twitter_panels, heading=ugettext_lazy('Twitter'), classname="settings"))

    EditHandler = TabbedInterface(tabs)
    return EditHandler.bind_to_model(cls)

def index(request):
    site = Site.find_for_request(request)
    instance = SiteMetadataPreferences.objects.filter(site=site).first()
    if instance is None:
        instance = SiteMetadataPreferences(site=site)
    EditHandler = get_edit_handler(SiteMetadataPreferences)
    SiteMetadataPreferencesForm = EditHandler.get_form_class(SiteMetadataPreferences)

    if request.method == "POST":
        form = SiteMetadataPreferencesForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            messages.success(request, 'The form has been successfully saved.')
            return redirect('wagtailmetadata')
        else:
            messages.error(request, 'The form could not be saved due to validation errors')
    else:
        form = SiteMetadataPreferencesForm(instance=instance)

    edit_handler = EditHandler(instance=instance, form=form)

    return render(request, 'wagtailmetadata/index.html', {
        'form': form,
        'edit_handler': edit_handler,
    })


#2.	Заполните массив случайными числами в диапазоне 0..4 и выведите на экран номера всех элементов, значение которых равно X.
# ( Х вводится с клавиатуры)

from random import randint

print("Введите число элементов в массиве")
d = int(input())
print("Введите число для сравнения")
x = int(input())
Spisok = [randint(0 , 4) for i in range (d)]
print(Spisok)

for c in range (d):
    l = Spisok[c]
    if l == x:
        print (c)


# Fix code format and add proxy system
# - Zenqi

import requests
import Prawler
import random
import string
import time

def main():
    try:
        num_proxy = int(input("Enter number of proxy to use (Default: 50) > "))
    except:
        num_proxy = 50
    try:
        amount    = int(input("Enter the amount of nitro to generate (Default: 1000) > "))
    except:
        amount = 1000
    value = 1

    print("generating proxy")
    # generate proxy

    proxy_list = Prawler.get_proxy_list(num_proxy, 'http', 'elite', 'US')

    while value <= amount:

        _proxy = random.choice(proxy_list)
        proxies = {
            "http": f"http://{_proxy}"
        }

        nitro = ''.join([random.choice(string.ascii_letters + string.digits) for i in range(16)])
        print(f"waiting 120s before making request, to avoid ratelimit \n")
        time.sleep(120)
        print(f"trying -> {nitro} with proxy -> {_proxy}\n")
        r = requests.get(f'https://discordapp.com/api/v6/entitlements/gift-codes/{nitro}', proxies=proxies, timeout=3)

        if r.status_code == 200:
            print(f"wow, -> {nitro} is accepted.")
            with open('Codes.txt', 'w+') as f:
                f.write(f"\ndiscord.gift/{nitro}")
                f.close()

        elif r.status_code == 404:
            print(f"invalid code -> {nitro}")

        elif r.status_code == 429:
            print('too many request. proxy -> rate limit?\n')

        value += 1

if __name__ == "__main__":
    main()


# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\routing\portals\portal_data_posture.py
# Compiled at: 2020-09-25 01:58:52
# Size of source mod 2**32: 17769 bytes
from _math import Vector3
from animation.animation_utils import StubActor
from animation.arb import Arb
from buffs.buff import Buff
from interactions.constraints import get_global_stub_actor, GLOBAL_STUB_CONTAINER
from postures.base_postures import MobilePosture
from postures.posture_specs import get_origin_spec_carry, get_origin_spec
from routing import Location
from routing.portals import portal_location
from routing.portals.portal_data_base import _PortalTypeDataBase
from routing.portals.portal_enums import PathSplitType
from routing.portals.portal_location import TunableRoutingSurfaceVariant, _PortalLocation
from routing.portals.portal_tuning import PortalType
from sims.outfits.outfit_change import TunableOutfitChange
from sims.sim_info_types import SpeciesExtended
from sims4.tuning.tunable import OptionalTunable, TunableVariant, HasTunableSingletonFactory, AutoFactoryInit, TunableEnumSet, Tunable, TunableMapping, TunableTuple
import postures, sims4.log, terrain
logger = sims4.log.Logger('Portal', default_owner='rmccord')

class _PortalLocationsFromPosture(HasTunableSingletonFactory, AutoFactoryInit):
    FACTORY_TUNABLES = {'bidirectional': Tunable(description='\n            If checked, a "there" and "back" portal will be created. If\n            unchecked, only a "there" portal is created.\n            ',
                        tunable_type=bool,
                        default=True)}

    def __call__(self, obj, posture, routing_surface_start, routing_surface_end, species_overrides):
        species_portals = []

        def get_outer_portal_goal(slot_constraint, stub_actor, entry, routing_surface):
            handles = slot_constraint.get_connectivity_handles(stub_actor, entry=entry, routing_surface_override=routing_surface)
            if not handles:
                slot_constraint.get_connectivity_handles(stub_actor, entry=entry, routing_surface_override=routing_surface,
                  log_none_slots_to_params_as_error=True)
                logger.error('PosturePortal: Species {} has no entry boundary conditions for portal posture', species)
                return
            species_param = SpeciesExtended.get_animation_species_param(stub_actor.species)
            for handle in handles:
                handle_species_param = handle.locked_params.get(('species', 'x'))
                if handle_species_param is None:
                    break
                if handle_species_param == species_param:
                    break
            else:
                return

            return next(iter(handle.get_goals()), None)

        posture_species = posture.get_animation_species()
        for species in species_overrides:
            if species == SpeciesExtended.INVALID:
                continue
            if SpeciesExtended.get_species(species) not in posture_species:
                continue
            stub_actor = get_global_stub_actor(species)
            portal_posture = postures.create_posture(posture, stub_actor, obj, is_throwaway=True)
            slot_constraint = portal_posture.slot_constraint
            containment_constraint = next(iter(slot_constraint))
            there_start = get_outer_portal_goal(slot_constraint, stub_actor, entry=True,
              routing_surface=routing_surface_start)
            if there_start is None:
                continue
            there_end = containment_constraint.containment_transform
            there_entry = Location((there_start.position), orientation=(there_start.orientation), routing_surface=routing_surface_start)
            there_exit = Location((there_end.translation), orientation=(there_end.orientation), routing_surface=routing_surface_end)
            back_entry = None
            back_exit = None
            if self.bidirectional:
                back_start = containment_constraint.containment_transform_exit
                back_end = get_outer_portal_goal(slot_constraint, stub_actor, entry=False,
                  routing_surface=routing_surface_start)
                if back_end is None:
                    continue
                back_entry = Location((back_start.translation), orientation=(back_start.orientation), routing_surface=routing_surface_end)
                back_exit = Location((back_end.position), orientation=(back_end.orientation), routing_surface=routing_surface_start)
            species_portals.append((there_entry, there_exit, back_entry, back_exit, SpeciesExtended.get_portal_flag(species)))

        return species_portals

class _PortalLocationsFromTuning(HasTunableSingletonFactory, AutoFactoryInit):
    FACTORY_TUNABLES = {'location_entry':_PortalLocation.TunableFactory(description='\n            The there entry portal location.\n            ',
       locked_args={'routing_surface':portal_location.ROUTING_SURFACE_TERRAIN,
      'orientation':None}),
     'location_exit':_PortalLocation.TunableFactory(description='\n            The there exit portal location.\n            ',
       locked_args={'routing_surface':portal_location.ROUTING_SURFACE_TERRAIN,
      'orientation':None}),
     'bidirectional':Tunable(description='\n            If checked, the portal will generate a there and back. If unchecked,\n            only a there portal will be created.\n            ',
       tunable_type=bool,
       default=True)}

    def __call__(self, obj, posture, routing_surface_start, routing_surface_end, species_overrides):
        species_portals = []
        posture_species = posture.get_animation_species()
        for species in species_overrides:
            if species == SpeciesExtended.INVALID:
                continue
            else:
                if SpeciesExtended.get_species(species) not in posture_species:
                    continue
                location_entry = self.location_entry(obj).position
                location_exit = self.location_exit(obj).position
                back_entry = None
                back_exit = None
                if self.bidirectional:
                    exit_x_offset = Vector3(location_entry.x - location_exit.x, 0, 0)
                    location_exit = location_exit + exit_x_offset
                    there_angle = sims4.math.vector3_angle(location_exit - location_entry)
                    there_orientation = sims4.math.angle_to_yaw_quaternion(there_angle)
                    there_entry = Location(location_entry, orientation=there_orientation, routing_surface=routing_surface_start)
                    there_exit = Location(location_exit, orientation=there_orientation, routing_surface=routing_surface_end)
                    back_angle = sims4.math.vector3_angle(location_entry - location_exit)
                    back_orientation = sims4.math.angle_to_yaw_quaternion(back_angle)
                    back_entry_position = location_exit + back_orientation.transform_vector(exit_x_offset)
                    back_entry = Location(back_entry_position, orientation=back_orientation, routing_surface=routing_surface_end)
                    back_exit_position = location_entry + back_orientation.transform_vector(exit_x_offset)
                    back_exit = Location(back_exit_position, orientation=back_orientation, routing_surface=routing_surface_start)
                else:
                    there_angle = sims4.math.vector3_angle(location_exit - location_entry)
                there_orientation = sims4.math.angle_to_yaw_quaternion(there_angle)
                there_entry = Location(location_entry, orientation=there_orientation, routing_surface=routing_surface_start)
                there_exit = Location(location_exit, orientation=there_orientation, routing_surface=routing_surface_end)
            species_portals.append((there_entry, there_exit,
             back_entry, back_exit,
             SpeciesExtended.get_portal_flag(species)))

        return species_portals

class _PortalTypeDataPosture(_PortalTypeDataBase):
    FACTORY_TUNABLES = {'posture_start':MobilePosture.TunableReference(description='\n            Define the entry posture as you cross through this portal. e.g. For\n            the pool, the start posture is stand.\n            '),
     'routing_surface_start':TunableRoutingSurfaceVariant(description="\n            The routing surface of the portal's entry position. Sims are on this\n            surface while in the starting posture.\n            "),
     'posture_end':MobilePosture.TunableReference(description='\n            Define the exit posture as you cross through this portal. e.g. For\n            the pool, the end posture is swim.\n            '),
     'routing_surface_end':TunableRoutingSurfaceVariant(description="\n            The routing surface of the portal's exit position. Sims are on this\n            surface when in the ending posture.\n            "),
     '_outfit_change':OptionalTunable(tunable=TunableOutfitChange(description='\n                Define the outfit change that happens when a Sim enters or exits\n                this portal.\n                ')),
     'portal_locations':TunableVariant(description='\n            Define the behavior that determines the entry and exit points.\n            ',
       from_posture=_PortalLocationsFromPosture.TunableFactory(),
       from_tuning=_PortalLocationsFromTuning.TunableFactory(),
       default='from_posture'),
     'species_overrides':OptionalTunable(description='\n            If enabled, we will override the species we generate these portals\n            for. However, the species are still restricted to those that are\n            supported by the posture. If the species cannot enter the posture,\n            then they will not generate portals.\n            ',
       tunable=TunableEnumSet(description='\n                The Species we want this portal to support.\n                ',
       enum_type=SpeciesExtended,
       enum_default=(SpeciesExtended.HUMAN),
       invalid_enums=(SpeciesExtended.INVALID)),
       disabled_value=SpeciesExtended),
     'requires_los_between_entry_and_exit':Tunable(description='\n            If checked, this portal will only be valid if there is LOS between\n            the entry and exit points. If unchecked, LOS is not required.\n            ',
       tunable_type=bool,
       default=True),
     'buff_asm_parameters':TunableMapping(description='\n            A mapping of buffs to parameters to set on the actor in the ASM when \n            traversing this portal.\n            ',
       key_type=Buff.TunableReference(description='\n                If the Sim has this buff, the corresponding ASM parameters will\n                be set on the ASM for this portal.\n                '),
       value_type=TunableTuple(description='\n                The parameter name and value to set on the ASM.\n                ',
       parameter_name=Tunable(description='\n                    The parameter name.\n                    ',
       tunable_type=str,
       default=None),
       parameter_value=Tunable(description='\n                    The value of the parameter if the Sim has the corresponding\n                    buff.\n                    ',
       tunable_type=str,
       default=None))),
     '_lock_portal_on_use':Tunable(description='\n            If checked, only one sim is allowed to use the portal at a time.\n            Otherwise, multiple sims can use the portal at the same time.\n            ',
       tunable_type=bool,
       default=True)}

    @property
    def portal_type(self):
        return PortalType.PortalType_Animate

    @property
    def outfit_change(self):
        return self._outfit_change

    @property
    def requires_los_between_points(self):
        return self.requires_los_between_entry_and_exit

    @property
    def lock_portal_on_use(self):
        return self._lock_portal_on_use

    def get_portal_duration(self, portal_instance, is_mirrored, walkstyle, age, gender, species):
        stub_actor = StubActor(1, species=species)
        arb = Arb()
        portal_posture = postures.create_posture(self.posture_end, stub_actor, GLOBAL_STUB_CONTAINER)
        source_posture = postures.create_posture(self.posture_start, stub_actor, None)
        portal_posture.append_transition_to_arb(arb, source_posture, locked_params={('age', 'x'):age,  'is_mirrored':is_mirrored})
        _, duration, _ = arb.get_timing()
        return duration

    def get_posture_change(self, portal_instance, is_mirrored, initial_posture):
        if initial_posture is not None and initial_posture.carry_target is not None:
            start_posture = get_origin_spec_carry(self.posture_start)
            end_posture = get_origin_spec_carry(self.posture_end)
        else:
            start_posture = get_origin_spec(self.posture_start)
            end_posture = get_origin_spec(self.posture_end)
        if is_mirrored:
            return (
             end_posture, start_posture)
        return (start_posture, end_posture)

    def split_path_on_portal(self):
        return PathSplitType.PathSplitType_Split

    def get_portal_locations(self, obj):
        routing_surface_start = self.routing_surface_start(obj)
        routing_surface_end = self.routing_surface_end(obj)
        portals = self.portal_locations(obj, self.posture_end, routing_surface_start, routing_surface_end, self.species_overrides)
        return portals

    def get_portal_asm_params(self, portal_instance, portal_id, sim):
        if portal_id == portal_instance.back:
            entry_location, exit_location = portal_instance.back_entry, portal_instance.back_exit
        else:
            entry_location, exit_location = portal_instance.there_entry, portal_instance.there_exit
        final_entry_height = terrain.get_terrain_height(entry_location.position.x, entry_location.position.z, entry_location.routing_surface)
        final_entry_position = sims4.math.Vector3(entry_location.position.x, final_entry_height, entry_location.position.z)
        final_exit_height = terrain.get_terrain_height(exit_location.position.x, exit_location.position.z, exit_location.routing_surface)
        final_exit_position = sims4.math.Vector3(exit_location.position.x, final_exit_height, exit_location.position.z)
        params = {('InitialTranslation', 'x'):final_entry_position,
         ('InitialOrientation', 'x'):entry_location.orientation,
         ('TargetTranslation', 'x'):final_exit_position,
         ('TargetOrientation', 'x'):exit_location.orientation}
        if sim is not None:
            if self.buff_asm_parameters:
                for buff, param in self.buff_asm_parameters.items():
                    if sim.has_buff(buff.buff_type):
                        params.update({(param.parameter_name, 'x'): param.parameter_value})

        return params


import unittest
import pandas as pd
import numpy as np

from engine.tolerance import get_time_var_selector, compute_statistics, select_max_diff, compute_max_rel_diff_dataframe
from util.constants import compute_statistics, dataframe_type_dict
from engine.check import check_variable

TEST_VARIABLES = ["v1", "v2"]
TEST_TIMESTEPS = np.arange(3)

def hand_written_dataframes():
    frame = {}
    frame["ref"] = {"max": [10, 4, 2, 47, 23, 24],
                    "min": [3, 9, 1, 23, 32, 53],
                    "mean": [5, 1, 8, 20, 32, 62],
                    "ntime": [1, 2, 3, 1, 2, 3],
                    "time": [1, 2, 3, 1, 2, 3],
                    "name": ["v1", "v1", "v1", "v2", "v2", "v2"]}

    frame["cur"] = {"max": [1, 2, 5, 79, 93, 34],
                    "min": [3, 3, 5, 78, 13, 64],
                    "mean": [1, 10, 5, 55, 32, 27],
                    "ntime": [1, 2, 3, 1, 2, 3],
                    "time": [1, 2, 3, 1, 2, 3],
                    "name": ["v1", "v1", "v1", "v2", "v2", "v2"]}

    frame["tol1"] = {"max": [10, 10, 10, 100, 100, 100],
                     "min": [10, 10, 10, 100, 100, 100],
                     "mean": [10, 10, 10, 100, 100, 100],
                     "ntime": [1, 2, 3, 1, 2, 3],
                     "time": [1, 2, 3, 1, 2, 3],
                     "name": ["v1", "v1", "v1", "v2", "v2", "v2"]}

    frame["tol2"] = {"max": [4, 4, 4, 40, 40, 40],
                     "min": [4, 4, 4, 40, 40, 40],
                     "mean": [4, 4, 4, 40, 40, 40],
                     "ntime": [1, 2, 3, 1, 2, 3],
                     "time": [1, 2, 3, 1, 2, 3],
                     "name": ["v1", "v1", "v1", "v2", "v2", "v2"]}

    return {key: pd.DataFrame(val).sort_values(by=["name", "ntime"]).reset_index(drop=True)
            for key, val in frame.items()}

class TestCheck(unittest.TestCase):

    def setUp(self):
        self.df_dict = hand_written_dataframes()

    def tearDown(self):
        return

    def test_check(self):
        df_ref = self.df_dict["ref"]
        df_cur = self.df_dict["cur"]
        df_tol1 = self.df_dict["tol1"]
        df_tol2 = self.df_dict["tol2"]

        df_diff = compute_max_rel_diff_dataframe(df_ref, df_cur, TEST_VARIABLES)

        out1, err1, tol1 = check_variable(df_diff, df_tol1)
        out2, err2, tol2 = check_variable(df_diff, df_tol2)
        self.assertTrue(out1, "Check with large tolerances did not validate! Here is the DataFrame:\n{}".format(err1))
        self.assertFalse(out2, "Check with small tolerances did validate! Here is the DataFrame:\n{}".format(err2))

        return

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


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv("../data/Position_Salaries.csv");

X = dataset.iloc[:,1:2].values
y = dataset.iloc[:, 2].values

# Feature scaling
#from sklearn.preprocessing import StandardScaler

#sc_X = StandardScaler()
#X = sc_X.fit_transform(X)

# Creating the Model
from sklearn.tree import DecisionTreeRegressor
regressor = DecisionTreeRegressor(random_state=0)

# Fitting the Model

regressor.fit(X, y)

# Predicting the test train result
y_pred = regressor.predict(6.5)

# Griding for higher resolution (replace X in plot with X_grid)
resolution = 1000
X_grid = np.arange(min(X), max(X), (max(X)-min(X))/resolution)
X_grid = X_grid.reshape(len(X_grid), 1)

# Creating the plot
plt.title('Position Vs Salary')
plt.xlabel('Position')
plt.ylabel('Salary')

# Visualizing the regression results
plt.scatter(X, y, color='red')
plt.plot(X_grid, regressor.predict(X_grid), color='blue')

# Show Plot
plt.show()


from tkinter import Scale, HORIZONTAL

from ..utils import load_color

def Slider(root, style = "", horizontal = False, **options):

  props = {
    'troughcolor': load_color(style)['bgColor']
  }

  scale = Scale(
    root
  )

  props.update(**options)

  scale.config(props)

  if horizontal:
    scale.config(orient=HORIZONTAL)

  scale.pack()


from JSpider import JSpider
from scrapy.selector import Selector
from scrapy.http import Request

class HiapkSpider(JSpider):
	name = 'HiapkSpider'
	allowed_domains = ['apk.hiapk.com']

	def __init__(self, mode, dbs, market, *args, **kwargs):
		super(HiapkSpider, self).__init__(mode, dbs, market, *args, **kwargs)

		self.initInitUrl = 'http://apk.hiapk.com/apps'
		self.initCatePath = '//div[@class="cate_list_box"]/ul/li[@class="category_item"]/a/@href'
		self.initUrlPrefix = 'http://apk.hiapk.com'

		self.listItemPrefix = 'http://apk.hiapk.com'

		self.listItemPath = '//span[@class="list_title font14_2"]/a/@href'

		self.metaTitlePath = '//div[@class="left font16"]/span[@class="none"]/text()'
		self.metaDescPath = '//pre[@id="softIntroduce"]/text()'

		self.downUrlPath = '//a[@id="ins91Btn"]/@href'
		self.downUrlPrefix = 'http://apk.hiapk.com'

	def parse_list_next(self, response):
		sel = Selector(response)

		try:
			nextRetUrl = None
			pageUrls = sel.xpath('//div[@class="page"]/a').extract()
			pageUrl = pageUrls[-1]
			if pageUrl.find('href') != -1:
				tmp = pageUrl.split('"')
				nextRetUrl = tmp[1]
			else:
				nextRetUrl = []

			if nextRetUrl != self.listNextNone:
				return Request('http://apk.hiapk.com' + nextRetUrl.replace('amp;', ''), callback = self.parse_list)
			else:
				raise Exception
		except:
			raise


from urlparse import urlparse
from urlparse import parse_qs
import logging
import socket

from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound

from yodl.tasks import transcode
from yodl.models import SongItem
from yodl.models import DBSession
from yodl.celery_utils import celery

log = logging.getLogger(__name__)

def url_validate(url):
    """docstring for url_validate"""
    o = urlparse(url)
    try:
        query = parse_qs(o.query)
        if o.netloc.endswith("youtube.com")\
                and query.keys() == [u'v']:
            return url
    except:
        pass

@view_config(route_name='home', renderer='templates/index.jinja2')
def main_view(request):
    if request.POST:
        url = request.params["url"].strip()
        # check if id and file all ready exists
        if url_validate(url):
            transcode.delay(url)
            request.session["error"] = False

        else:
            request.session["error"] = True

        return HTTPFound(request.route_url('home'))

    i = celery.control.inspect()
    try:
        active = i.active()
        queue = i.scheduled()
    except socket.error:
        log.error("Could not connect to RabbitMQ server.")
        raise

    songs = DBSession.query(SongItem).all()
    return {'songs': songs, 'queue': queue, 'active': active}


import requests
from bs4 import BeautifulSoup
import pandas as pd

def get_gamelogs(player_id, season, playoffs=False):
    """
    :param player_id:
    :param season:
    :param playoffs:
    :return:
    """
    if playoffs:
        selector = 'div_pgl_basic_playoffs'
    else:
        selector = 'div_pgl_basic'

    url = 'https://widgets.sports-reference.com/wg.fcgi?css=1&site=bbr&url=%2Fplayers%2Fa%2F'
    url += f'{player_id}%2Fgamelog%2F{season}%2F&div={selector}'

    # request
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    table = soup.table

    if table:
        return clean_df(pd.read_html(str(table))[0])
    else:
        return pd.DataFrame()

# helper functions
def clean_df(df):
    """
    Cleans input DataFrame:
        * exclude rows with column names
        * rename columns
        * create new feature which tells by how many points game was won/lost
        * new feature, boolean outcome: game won or lost
        * new feature where game was played: home or away
    :param df: pandas DataFrame
    :return: pandas DataFrame
    """
    # remove empty rows
    df = df[df.G != 'G'][df.columns[2:]].reset_index(drop=True)
    # rename columns
    df = df.rename(columns={'Unnamed: 5': 'Side', 'Unnamed: 7': 'Outcome'})
    # calculate result, W for wins, L for lost
    df['Result'] = df['Outcome'].apply(lambda x: x.split('(')[1][:-1])
    # create new feature with game result, + means game was won, - lost by X points
    df['Outcome'] = df['Outcome'].apply(lambda x: x.split('(')[0])
    # create column where the game was played for specific player
    df['Side'] = df['Side'].fillna('Away').replace('@', 'Home')

    return df

# helper functions
def html_2_table_season_stats(table):
    """
    Read HTML code tor return DataFrame
    Input:
        table- bs4 element,
    Output:
        pandas DataFrame
    """
    try:
        col_names = [_.text for _ in table.thead.findAll('th')]
        table_data = [[_.text for _ in row] for row in table.findAll('tr', {'class': 'full_table'})]
    except AttributeError:
        return pd.DataFrame()
    else:
        return pd.DataFrame(table_data, columns=col_names)

def get_season_stats(player_id):
    """
    Returns regular season stats
    :param player_id: string, e.g. mcgeeja01
    :return:
    """
    # generate request url
    url = f'https://www.basketball-reference.com/players/{player_id[0]}/{player_id}.html'

    # request
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')

    # get player stats
    player_info = soup.find('div', {"class": 'players'})

    # get image location
    try:
        player_photo_src = player_info.find('div', {'class': 'media-item'}).img['src']
    except AttributeError:
        player_photo_src = 'assets/face_placeholder.png'

    try:
        player_name = player_info.span.text
    except AttributeError:
        player_name = ''

    # get information about player
    mk_text = ""

    for attr in player_info.findAll('span'):
        try:
            # check if item has item property attribute
            attr_name = attr['itemprop']
            attr_value = attr.text.strip()
            # ignore attributes with no values
            if attr_value != '':
                mk_text += f"* {attr_name}: {attr_value} \n"
        except KeyError:
            pass

    # table with regular season stats
    table_rs = soup.find('table', {'id': 'per_game'})
    df_rs = html_2_table_season_stats(table_rs)

    # table with play-off stats
    table_po = soup.find('table', {'id': 'playoffs_per_game'})
    df_po = html_2_table_season_stats(table_po)

    # generate list for all info about player
    player_info = [player_photo_src, player_name, mk_text]

    return df_rs, df_po, player_info


"""Test PSCUData class from lpdpower.

Tim Nicholls, STFC Application Engineering Group
"""

import sys
if sys.version_info[0] == 3:  # pragma: no cover
    from unittest.mock import Mock, call, patch
else:                         # pragma: no cover
    from mock import Mock, call, patch

from nose.tools import *

sys.modules['smbus'] = Mock()
sys.modules['serial'] = Mock()
sys.modules['Adafruit_BBIO'] = Mock()
sys.modules['Adafruit_BBIO.GPIO'] = Mock()
from odin.adapters.parameter_tree import ParameterAccessor
from lpdpower.pscu_data import PSCUData, PSCUDataError

class TestPscuData():

    @classmethod
    def setup_class(cls):
        cls.pscu = Mock()
        cls.pscu.num_humidities = 2
        cls.pscu.num_temperatures = 11
        cls.pscu.num_quads = 4
        cls.pscu.num_leak_sensors = 1
        cls.pscu.quad = [Mock()] * cls.pscu.num_quads
        for quad in cls.pscu.quad:
            quad.num_channels = 4
        cls.pscu.get_all_latched.return_value = [True]*4
        cls.pscu_data = PSCUData(pscu=cls.pscu)

    @patch('lpdpower.pscu_data.PSCU')
    def test_pscu_data_no_pscu_arg(self, mock_pscu):
        pd = PSCUData()
        assert(pd.pscu is not None)

    def test_get_param(self):

        val = self.pscu_data.get('position')
        self.pscu.get_position.assert_called_with()

    def test_set_param(self):

        enabled = True
        self.pscu_data.param_tree._tree['allEnabled']._type = bool
        self.pscu_data.set('allEnabled', enabled)
        self.pscu.enable_all.assert_called_with(enabled)

    def test_get_missing_param(self):

        missing_param = 'missing_param'
        with assert_raises_regexp(PSCUDataError, 'Invalid path: {}'.format(missing_param)):
            self.pscu_data.get(missing_param)

    def test_set_missing_param(self):

        missing_param = 'missing_param'
        with assert_raises_regexp(PSCUDataError, 'Invalid path: {}'.format(missing_param)):
            self.pscu_data.set(missing_param, 0)

    def test_get_all_latched(self):

        self.pscu_data.get_all_latched()
        self.pscu.get_all_latched.assert_called_with()

    def test_get_quad_traces(self):

        traces = self.pscu_data.get_quad_traces()
        assert_equal(len(traces), self.pscu.num_quads)
        self.pscu.get_quad_trace.assert_has_calls([call(i) for i in range(self.pscu.num_quads)])


from flask import Flask, render_template, request, jsonify
from flask_cors import CORS, cross_origin
import json
import boto3
import time
import os

app = Flask(__name__)
CORS(app)

#Main endpoint for loading the webpage
@app.route('/')
def loadIndex():
    return render_template('index.html')

@app.route('/initServerMC', methods = ['POST'])
def initServerMC():
    inputPass = request.form['pass']
    returnData = {}

    message = "Password Incorrect!"

    if inputPass == os.environ['SERVER_PASSWORD']:
        #Instantiate server here or return ip address if already running
        client = boto3.client(
            'ec2',
            aws_access_key_id=os.environ['ACCESS_KEY'],
            aws_secret_access_key=os.environ['SECRET_KEY'],
            region_name=os.environ['EC2_REGION']
        )
        message = manageServer(client)

    print(message)
    return render_template('index.html', ipMessage=message)

#Gets IP Address for return to webpage otherwise boots server
def manageServer(client):
    returnString = 'ERROR'

    instanceIds = [os.environ['INSTANCE_ID']]
    response = client.describe_instances(InstanceIds = instanceIds)
    reservations = response['Reservations']
    reservation = reservations[0]

    instances = reservation['Instances']

    print("\nSERVER INSTANCES\n")
    print(instances)
    print("\n")
    if len(instances) > 0:
        instance = instances[0]
        state = instance['State']
        stateName = state['Name']

        if (stateName == 'stopped') or (stateName == 'shutting-down'):
            #SETUP MULTIPROCESSING HERE INSTEAD OF REDIS
            returnString = startServer(client)
        elif stateName == 'running':
            returnString = 'IP: ' + instance['PublicIpAddress']
        else:
            returnString = 'ERROR'
    return returnString

#Starts the specified AWS Instance from the configuration
def startServer(client):
    #Gets proper variables to attempt to instantiate EC2 instance and start minecraft server
    returnString = 'ERROR'
    instanceIds = [os.environ['INSTANCE_ID']]
    response = client.start_instances(InstanceIds = instanceIds)

    stateCode = 0

    while not (stateCode == 16):
        time.sleep(3)

        print('\nAWS EC2 START RESPONSE\n')
        print(str(response))
        print('\n')

        response = client.describe_instances(InstanceIds = instanceIds)
        reservations = response['Reservations']
        reservation = reservations[0]

        instances = reservation['Instances']
        instance = instances[0]

        state = instance['State']
        stateCode = state['Code']

        print("\nSERVER INSTANCES\n")
        print(instances)
        print("\n")

    ipAddress = instance['PublicIpAddress']
    returnString = 'Server is starting, this may take a few minutes.\nIP: ' + ipAddress
    return returnString

if __name__ == "__main__":
    app.run()


#calss header
class _AFFORESTATION():
	def __init__(self,):
		self.name = "AFFORESTATION"
		self.definitions = [u'the action of planting trees on an area of land in order to make a forest']

		self.parents = []
		self.childen = []
		self.properties = []
		self.jsondata = {}

		self.specie = 'nouns'

	def run(self, obj1 = [], obj2 = []):
		return self.jsondata


"""
Vinícius Vilar - ADS UNIFIP - Programação 1 - Lista 2 Estrutura de Decisão
Patos - PB | 2020

4. Escreva um programa que leia uma temperatura em graus Fahrenheit,
transforme-a em graus Celsius e exiba o resultado.

"""

fahr = float(input("Grau Fahrenheit: "))

celsius = (fahr - 32) * (5/9)

print("{}ªF para ªC é {:.1f}ªC".format(fahr, celsius))


import json, os, time, random
import numpy as np
import tensorflow as tf

import sys
from datetime import datetime

from pyLogger import pyLogger

import model, sample, encoder

class GPT2():
    """
        GPT-2 class
        ------------------------------------------------------------------------------------------------
        :model_name=117M : String, which model to use

        :seed= -1 : Integer seed for random number generators, fix seed to reproduce
        results. If seed <= -1 (default) then generate a random seed between 0 and 2^32 - 1

        :nsamples=1 : Number of samples to return total

        :batch_size=1 : Number of batches (only affects speed/memory).  Must divide nsamples.

        :length=0 : Number of tokens in generated text, if 0 (default), is
        determined by model hyperparameters

        :temperature=1 : Float value controlling randomness in boltzmann
        distribution. Lower temperature results in less random completions. As the
        temperature approaches zero, the model will become deterministic and
        repetitive. Higher temperature results in more random completions.

        :top_k=0 : Integer value controlling diversity. 1 means only 1 word is
        considered for each step (token), resulting in deterministic completions,
        while 40 means 40 words are considered at each step. 0 (default) is a
        special setting meaning no restrictions. 40 generally is a good value.

        :log_path : Path to log file. If one is not provided the default path will be used (logs/log.txt)

        :debug : Puts GPT-2 into a debugging mode. This allows for more logging and other useful features
        ------------------------------------------------------------------------------------------------
    """

    def __init__(self, model_name='117M', seed=-1, nsamples=1, batch_size=1, length=0, temperature=1, top_k=0, log_path=None, debug=False):
        self.model_name = model_name
        self.seed = seed
        self.nsamples = nsamples
        self.batch_size = batch_size
        self.length = length
        self.temperature = temperature
        self.top_k = top_k
        self.log_path = log_path
        self.debug = debug

        # builds encoder for model.
        self.enc = encoder.get_encoder(self.model_name)

        #builds paramerters to work off of
        self.hparams = model.default_hparams()
        with open(os.path.join('models', self.model_name, 'hparams.json')) as f:
            self.hparams.override_from_dict(json.load(f))

        # if checks pass, start tensorflow
        self.sess = tf.Session()

        self._getReady()

    def _getReady(self):
        """
            Builds the necessary objects for GPT-2 to run properly
        """
        # starts logger
        self.logger = pyLogger(self.log_path)
        self.logger._print("STARTING GPT-2 -- {}\n\n".format(datetime.now().strftime('%Y-%m-%d %H:%M:%S')), None)

        # checks properties before building application
        self._checks()

        # placeholder value, dtype, shape. Shape is batchzise and none
        self.context = tf.placeholder(tf.int32, [self.batch_size, None])
        self.logger._print("Context Pre-Output: {}".format(self.context))

        np.random.seed(self.seed)
        tf.set_random_seed(self.seed)

        # builds the sample for tensorflow
        self.buildSeq()

        saver = tf.train.Saver()
        ckpt = tf.train.latest_checkpoint(os.path.join('models', self.model_name))
        saver.restore(self.sess, ckpt)

        self.logger._print("Started GTP-2 With Params -- Seed: {}; Length: {}; nSamples: {}; Batch-Size: {}; Top-K: {}; Tempurature: {}".format(self.seed, self.length, self.nsamples, self.batch_size, self.top_k, self.temperature))

    def buildSeq(self):
        # generates a sample set sequence of data based on parameters provided
        self.sequence = sample.sample_sequence(
            hparams = self.hparams, length = self.length,
            context = self.context,
            batch_size = self.batch_size,
            temperature = self.temperature, top_k = self.top_k
        )

        # saves that data inside self.sequence
        # self.logger._print("Output: "+str(self.sequence))

    def _checks(self):
        """
            Makes sure all values are appropriate values are inputted and corrects those values
        """

        # checks the current seed and if it is not assigned random seed is generated
        if self.seed < 1 or type(self.seed) is not int:
            self.seed = random.randint(0, 2**32-1)
            self.logger._print("Seed was not defined. Your Seed is: " + str(self.seed), 'W')

        if self.nsamples < 1:
            self.logger._print("nSamples must be an integer greater than 0. nSamples set to 1", 'W')
            self.nsamples = 1

        # makes sure batch size is divisable by samples. prevents errors when building outputs
        if self.nsamples % self.batch_size == 0:
            # set batchsize to a default of 1
            self.logger._print("Batch Size is too large for the amount of samples provided. Batch Size was set to 1.", 'W')
            self.batch_size = 1

        # makes sure the output can calculate the desired length
        if self.length < 1 or self.length > self.hparams.n_ctx:
            # default length = hparmas.n_ctx (max size) / 2
            self.length = self.hparams.n_ctx // 2
            self.logger._print("Length was not defined or too long. Length was set to {}".format(self.length), 'W')

        if self.temperature < 1:
            self.logger._print("Temperature must be 1 or higher. Temperature was set to 1", 'W')
            self.temperature = 1

        if self.top_k < 0:
            self.logger._print("Top_k must be 0 or higher. Top_k was set to 0", 'W')
            self.top_k = 0

        # checks the log path assigned. If path does not exist, use default path
        if self.log_path != None and os.path.exists(self.log_path):
            self.log_path = None
            self.logger.path = self.log_path
            self.logger._print("Path provided for the logs does not exist! Path has been set to log folder", 'W')

    def run(self):
        """
            Runs GPT-2

            Debug allows the user to see more output. Also displays time it took for the program to create and display the output
        """

        self.logger._print("Type ?help for available commands")
        while True:
            self._prompt()

            if self.raw_text == None:
                continue

            # encodes the inputted string into a format that can be inputted into Tensor Flow
            context_tokens = self.enc.encode(self.raw_text)

            if self.debug:
                self.logger._print("Seed: {}; Length: {}; nSamples: {}; Batch-Size: {};".format(self.seed, self.length, self.nsamples, self.batch_size))
                start = time.time()

            for generated in range(self.nsamples // self.batch_size):

                # Returns shape of the output
                # print("Output Tensor: "+str(output))

                # feed dictionary, consiting of the context tokens
                # context tolkens are created by encoding the values provided by the user
                contextDic = {self.context: [context_tokens for placeholder in range(self.batch_size)]}

                # print("Context Dictionary: "+ str(contextDic))

                """
                    TODO figure out how this function works

                    OUT CREATES ALL THE OUTPUTS FOR THE GIVEN PROMPT
                    https://www.tensorflow.org/api_docs/python/tf/Session#run

                    Encoded text and model data is sent into Tensorflow.

                    Tensorflow is then able to create a output based on sample sequence and raw input.
                """
                out = self.sess.run(self.sequence, feed_dict=contextDic)

                # Removes the context tokens (inputted string) from the output.

                # Context tokens are included in the output, this splices them out in order to give only the output and not the original prompt
                out = out[:, len(context_tokens):]

                # print(out)

                """
                    ------------------------------------------------------------------------------------------------

                    There seems to be a graph comparison going on here and returns a list with the indexes to the text.
                    Out is a list of lists. Top list contains the sublists that hold the indices to the dictionary

                    ------------------------------------------------------------------------------------------------

                    What I believe is going on is, samples.py creates a graph that seems to be likely next words. This then gets thrown into the TensorFlow.run() function and is compaired to a dictionary. This then somehow comes up with an appropriate output to generate.

                    ------------------------------------------------------------------------------------------------

                    Because most of this seems to be handled inside of Tensorflow it may be difficult to gain access to the inner workings

                    ------------------------------------------------------------------------------------------------

                    TODO: see if there are other ways to generate Top-K.

                    -- i am unsure if i can get the Top-K. This is because it seems to be stored inside tensorflow and I have not found a way to output it --
                """

                for i in range(self.batch_size):
                    text = self.enc.decode(out[i])
                    self.logger._print("=" * 40 + " SAMPLE " + str(generated+1) + " " + "=" * 40, None)

                    # PRINTS LIST OF INDECIES
                    # print(out[i])
                    self.logger._print(text, "OUTPUT")

            print("=" * 80)
            if self.debug:
                end = time.time()
                self.logger._print("It took "+str(round(end - start)) + " seconds to generate this output")
            self.logger._save()

        # ends program
        self.close()

    # Input for GPT-2 to customize settings
    def _prompt(self):
        "Takes user input and throws appropriate respose to GPT-2"

        self.raw_text = input("Model prompt >>> ")

        # if prompt is empty notify user, and restart loop
        if not self.raw_text:
            print("Prompt should not be empty! Type ?help or ?h for available commands")
            self.raw_text = None

        elif self.raw_text == "?help" or self.raw_text == "?h":
            print("Available Commands:\n\n?help - Displays Commands. Alias: ?h\n#kill - Ends GPT-2 Process\n")
            self.raw_text = None

        # if user types #kill break the loop. Cleaner way to close application
        elif self.raw_text == "#kill":
            check = input("Are you sure you want to end GPT-2? [Y/n] ").lower()
            if check == "n":
                self.raw_text = None
            self.close()

        elif self.raw_text == "#change":
            print("What variable would you like to modify?\n\nnsamples: {} \nbatch_size: {} \nlength: {}".format(self.nsamples, self.batch_size, self.length))

            variable = input("Type the Variable: ").lower()
            try:
                value = int(input("New Value: "))

                if variable == "batch_size":
                    self.batch_size = value
                elif variable == "nsamples":
                    self.nsamples = value
                elif variable == "length":
                    self.length = value
                    self.buildSeq()
            except:
                self.logger._print("Please use an integer!", 'E')

            self.raw_text = None

    def close(self):
        self.logger._print("Ending GPT-2")
        self.logger._print("\n"+"="*80, None)

        self.logger.close()
        self.sess.close()
        sys.exit()


#!/usr/bin/env python
#########################################################################################
#
# Invert the intensity of the image
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2017 Polytechnique Montreal <www.neuro.polymtl.ca>
# Author: Benjamin De Leener, Julien Cohen-Adad
# Modified: 2017-10-17
#
# About the license: see the file LICENSE.TXT
#########################################################################################

from __future__ import division, absolute_import

import sys

from msct_parser import Parser
from spinalcordtoolbox.image import Image
import sct_utils as sct

def get_parser():
    # Initialize the parser
    parser = Parser(__file__)
    parser.usage.set_description('This function inverts the image intensity using the maximum intensity in the image and 0.')
    parser.add_option(name="-i",
                      type_value="file",
                      description="Image to invert.",
                      mandatory=True,
                      example="my_image.nii.gz")

    parser.add_option(name="-o",
                      type_value="file_output",
                      description="output image.",
                      mandatory=False,
                      example="output_image.nii.gz",
                      default_value="inverted_image.nii.gz")

    return parser

def main(args=None):
    parser = get_parser()
    arguments = parser.parse(sys.argv[1:])

    input_filename = arguments["-i"]
    image_input = Image(input_filename)
    image_output = image_input
    image_output.data = image_input.data.max() - image_input.data
    if '-o' in arguments:
        image_output.absolutepath = arguments['-o']
    image_output.save(type='minimize')

if __name__ == "__main__":
    sct.init_sct()
    main()


# lab11.py
# YOUR NAME(S) AND NETID(S) HERE
# DATE COMPLETED HERE
"""Loop functions for lab 11"""

def numberof(seq, v):
    """Returns: number of times v occurs in thelist.

    Parameter seq: list to search
    Precondition: seq is a list of ints

    Parameter v: value to search for
    Precondition: v is an int"""
    assert type(seq) == list and type(v) == int
    count = 0  # Accumulator
    k = 0      # Loop variable

    # IMPLEMENT A WHILE LOOP HERE
    while k < len(seq):
        if seq[k] == v:
            count += 1
        k += 1

    # END WHILE LOOP

    # Return result
    return count

def replace_copy(seq,a,b):
    """Returns: a COPY of thelist but with all occurrences of a replaced by b.

    Example: replace([1,2,3,1], 1, 4) is [4,2,3,4].

    Parameter seq: list to search
    Precondition: seq is a list of ints

    Parameter a: value to search for
    Precondition: a is an int

    Parameter b: value to replace
    Precondition: b is an int"""
    copy = []  # Accumulator
    k = 0      # Loop variable

    # IMPLEMENT A WHILE LOOP HERE
    while k < len(seq):
        if seq[k] == a:
            #print "pass if seq[k] == a:"
            copy.append(b)
        else:
            #print "pass else"
            copy.append(seq[k])
        k += 1

    # END WHILE LOOP

    # Return result
    return copy

def replace(seq,a,b):
    """MODIFY thelist so that all occurrences of a replaced by b.

    This function should have NO RETURN STATEMENT

    Example: if a = [1,2,3,1] then a becomes [4,2,3,4] after the
    function call replace(a,1,4).

    Parameter seq: list to search
    Precondition: seq is a list of ints

    Parameter a: value to search for
    Precondition: a is an int

    Parameter b: value to replace
    Precondition: b is an int"""
    # IMPLEMENT A WHILE LOOP HERE
    index = 0
    while index < len(seq):
        if seq[index] == a:
            seq[index] = b
        index += 1

    # END WHILE LOOP

# OPTIONAL FUNCTION
def exp(x,err=1e-6):
    """Returns: the value of (e ** x) to with the given margin of error.

    Do NOT return (math.E ** x).  This function is more exact that that answer.

    The value (e ** x) is given by the Power Series

        1 + x + (x ** 2)/2 + (x ** 3)/3! + ... + (x ** n)/ n! + ...

    We cannot add up infinite values in a program.  So we APPROXIMATE (e ** x)
    by choosing a value n and stopping at that:

        1 + x + (x ** 2)/2 + (x ** 3)/3! + ... + (x ** n)/ n!

    The error of this approximation is

        abs( (x ** (n+1))/(n+1)!)

    which we want less than err.  So to compute e ** x, we just keep computing
    term = (x ** n)/ n! in a loop until this value is less than our error.  If it
    is not less than the error, we add it to the accumulator, which we return at
    the end.

    Hint: (x**(n+1))/(n+1)!  == (x**n)/n! * x/(n+1)
    Use this fact to simplify your loop.

    Parameter x: the exponent for e ** x
    Precondition: x is a numbers

    Parameter err: The margin of error (OPTIONAL: default is e-6)
    Precondition: err > 0 is a number"""
    approx = 0.0  # Approximation of e ** x
    term   = 1.0  # 1 is the first term in the Power Series
    n = 0         # term 1 corresponds to (x ** 0)/0!
    x = float(x)

    # IMPLEMENT A WHILE LOOP HERE

    while abs(term) >= err:
        approx = approx + term
        #print "approx", approx
        n += 1
        term = term*x/n
    #print "end while loop here"

    # END WHILE LOOP

    # Return result
    return approx

class A(object):
    def __init__(self, hours):
        self._hours = hours

    def getHours(self):
        return self._hours

    def __str__(self):
        return str(self._hours)
    def __repr__(self):
        return str(self.__class__) + str(self)

class B(A):
    def __init__(self, hours, name):
        A.__init__(self, hours)
        self._name = name

    def getName(self):
        return self._name

    def __str__(self):
        return name + ' at ' + A.__str__(self)

def average(grades):
    """Returns: the average of all grades in the dictionary as a float.
    Example: average(example) is 75.8; average({}) is 0.0
    Precondition: grades is a grade dictionary (may be empty)"""
    # Accumulator is a float.  Prevents int division
    avg = 0.0
    for netid in grades:
        grade = grades[netid]
        avg = avg + grade
    if len(grades) == 0:
        return 0.0
    avg = avg/float(len(grades)) # Use of float is not required here
    return avg


#read csv file
import csv
dict_list=[]
with open('C:\\Users\\ssimako\\Documents\\dev\\python\\valtype\\valtype-work.csv', mode='r') as infile:
    reader = csv.DictReader(infile)
    for line in reader:
        dict_list.append(line)
print(dict_list[2])

"""for line in reader:
    dict_list.append(line)
print(dict_list)"""
#    for row in infile:
#        print(row[1])