import numpy as np
import matplotlib.pyplot as plt
import random

class Tuihuo:
    path = []

    def __init__(self, graph, num, value=0):  # 初始化类
        self.num = num
        self.graph = graph
        self.value = 0

    def output_graph(self):  # 输出初始图
        for i in self.graph:
            for j in i:
                print(j, end=',')
            print()

    def distance(self, tuihuocurrent):
        valuenow = 0
        for i in range(self.num - 1):
            valuenow += self.graph[tuihuocurrent[i]][tuihuocurrent[i + 1]]
        valuenow += self.graph[tuihuocurrent[self.num - 1]][0]
        return valuenow

    def threetuihuo(self, tuihuocurrent, x, y, w):
        if x > y:
            x, y = y, x
        if w > y:
            w, y = y, w
        if w > x:
            w, x = x, w
        temp1 = tuihuocurrent[x:y + 1] + tuihuocurrent[w + 1:x]
        tuihuocurrent[w + 1:y + 1] = temp1

        return tuihuocurrent

    def calculate(self):  # 计算近似最短路径并且将路径存储在path中
        result = []  # 用于生成可视化图表
        tuihuosolution = list(range(self.num))
        valuenow = 0
        valuenow = self.distance(tuihuosolution)
        valuebest = valuenow
        tuihuocurrent = tuihuosolution.copy()
        tuihuonow = tuihuosolution.copy()
        t = 100000  # 初始温度
        t1 = 1  # 最后底线温度
        r = 0.99999  # 降温参数

        while t > t1:
            # 使用两路扰乱和三路扰乱两种方式
            p1 = np.random.rand()
            if p1 > 0.5:  # 使用二路扰乱
                while 1:
                    x = random.randrange(1, self.num - 1)
                    y = random.randrange(1, self.num - 1) # 生成交换坐标点
                    if x != y:
                        break
                tuihuocurrent[x], tuihuocurrent[y] = tuihuocurrent[y], tuihuocurrent[x]
            else:  # 使用三路扰乱
                while 1:
                    x = random.randrange(1, self.num - 1)
                    y = random.randrange(1, self.num - 1)
                    w = random.randrange(1, self.num - 1)  # 生成交换坐标点
                    if x != y and x != w and y != w:
                        break
                tuihuocurrent = self.threetuihuo(tuihuocurrent, x, y, w)
            valuethen = self.distance(tuihuocurrent)

            # 判断是否接受该解
            if valuethen < valuenow:
                tuihuonow = tuihuocurrent.copy()
                valuenow = valuethen
                if valuethen < valuebest:
                    tuihuosolution = tuihuocurrent.copy()
                    valuebest = valuethen
            elif np.random.rand() < np.exp(-(valuethen - valuebest) / t):  # 一定概率在不是优解的情况下接受
                valuenow = valuethen
                tuihuonow = tuihuocurrent.copy()
            else:
                tuihuocurrent = tuihuonow.copy()

            t = t * r
            result.append(valuenow)

        plt.plot(np.array(result))
        plt.ylabel("valuenow")
        plt.xlabel("t")
        plt.show()
        self.value = valuebest
        return tuihuosolution

    def print_outcome(self):
        num = self.calculate()
        print("模拟退火算法近似最短路径为",end='')
        print(0, end='')
        for i in range(len(num)):
            if i != 0:
                print("->%d" % num[i], end='')
        print("-> 0")
        print("模拟退火算法近似最短路径长度为" + str(self.value))


"""
Inventarios Componentes v3, CRUD (create, read, update, and delete)
"""
from typing import Any

from sqlalchemy.orm import Session

from lib.exceptions import MyIsDeletedError, MyNotExistsError
from lib.safe_string import safe_string

from ...core.inv_componentes.models import InvComponente
from ..inv_categorias.crud import get_inv_categoria
from ..inv_equipos.crud import get_inv_equipo

def get_inv_componentes(
    database: Session,
    inv_categoria_id: int = None,
    inv_equipo_id: int = None,
    generacion: str = None,
) -> Any:
    """Consultar los componentes activos"""
    consulta = database.query(InvComponente)
    if inv_categoria_id is not None:
        inv_categoria = get_inv_categoria(database, inv_categoria_id=inv_categoria_id)
        consulta = consulta.filter(InvComponente.inv_categoria == inv_categoria)
    if inv_equipo_id is not None:
        inv_equipo = get_inv_equipo(database, inv_equipo_id=inv_equipo_id)
        consulta = consulta.filter(InvComponente.inv_equipo == inv_equipo)
    if generacion is not None:
        generacion = safe_string(generacion)
        if generacion != "":
            consulta = consulta.filter_by(generacion=generacion)
    return consulta.filter_by(estatus="A").order_by(InvComponente.id.desc())

def get_inv_componente(database: Session, inv_componente_id: int) -> InvComponente:
    """Consultar un componente por su id"""
    inv_componente = database.query(InvComponente).get(inv_componente_id)
    if inv_componente is None:
        raise MyNotExistsError("No existe ese componente")
    if inv_componente.estatus != "A":
        raise MyIsDeletedError("No es activo ese componente, está eliminado")
    return inv_componente


from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from .models import Exercise
from .serializers import ExerciseSerializer
import requests
import os

from workouts.models import Workout

# Create your views here.

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def api_exercises_list(request):
    if request.method == 'GET':
        url = 'https://exercisedb.p.rapidapi.com/exercises'
        headers = {
            'X-RapidAPI-Key': os.environ.get("EXERCISE_DB_RAPID_API_KEY"),
            'X-RapidAPI-Host': 'exercisedb.p.rapidapi.com'
        }
        response = requests.get(url=url, headers=headers)
        return Response(response.json(), status=status.HTTP_200_OK)
    return Response(status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'POST'])
@permission_classes([IsAdminUser])
def admin_exercise_list(request):
    if request.method == 'GET':
        workout_id = request.query_params.get('workout_id')
        if workout_id is not None:
            exercises = Workout.objects.get(pk=workout_id).exercise_set.all()
            serializer = ExerciseSerializer(exercises, many=True)
            return Response(serializer.data)
    if request.method == 'POST':
        workout_id = request.data.pop('workouts_id')
        serializer = ExerciseSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        new_exercise = get_object_or_404(
            Exercise, pk=serializer.data.get('id'))
        if new_exercise is not None:
            workout = get_object_or_404(Workout, id=workout_id)
            new_exercise.workouts.add(workout)
            new_exercise = get_object_or_404(
                Exercise, pk=serializer.data.get('id'))
            serializer = ExerciseSerializer(new_exercise)

        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PATCH', 'DELETE'])
@permission_classes([IsAuthenticated])
def exercise_detail(request, pk):
    exercise = get_object_or_404(Exercise, pk=pk)

    if request.method == 'GET':
        serializer = ExerciseSerializer(exercise)
        return Response(serializer.data, status=status.HTTP_200_OK)
    elif request.method == 'PATCH' and request.user.is_staff:
        serializer = ExerciseSerializer(
            exercise, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    elif request.method == 'DELETE' and request.user.is_staff:
        exercise.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    return Response(status=status.HTTP_400_BAD_REQUEST)


# -*- coding:utf-8 -*-
import os
import sys
import time
import tensorflow as tf
import seq2seqModel
import getConfig
import io

gConfig = {}

gConfig=getConfig.get_config(config_file='seq2seq.ini')

vocab_inp_size = gConfig['enc_vocab_size']
vocab_tar_size = gConfig['dec_vocab_size']
embedding_dim=gConfig['embedding_dim']
units=gConfig['layer_size']
BATCH_SIZE=gConfig['batch_size']
max_length_inp,max_length_tar=20,20

def preprocess_sentence(w):
    w ='start '+ w + ' end'
    #print(w)
    return w

def create_dataset(path, num_examples):
    lines = io.open(path, encoding='UTF-8').read().strip().split('\n')
    word_pairs = [[preprocess_sentence(w)for w in l.split('\t')] for l in lines[:num_examples]]

    return zip(*word_pairs)

def max_length(tensor):
    return max(len(t) for t in tensor)

def read_data(path,num_examples):

    input_lang,target_lang=create_dataset(path,num_examples)

    input_tensor,input_token=tokenize(input_lang)
    target_tensor,target_token=tokenize(target_lang)

    return input_tensor,input_token,target_tensor,target_token

def tokenize(lang):
    lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=gConfig['enc_vocab_size'], oov_token=3)
    lang_tokenizer.fit_on_texts(lang)

    tensor = lang_tokenizer.texts_to_sequences(lang)

    tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor, maxlen=max_length_inp,padding='post')

    return tensor, lang_tokenizer

input_tensor,input_token,target_tensor,target_token= read_data(gConfig['seq_data'], gConfig['max_train_data_size'])

def train():
    print("Preparing data in %s" % gConfig['train_data'])
    steps_per_epoch = len(input_tensor) // gConfig['batch_size']
    print(steps_per_epoch)
    enc_hidden = seq2seqModel.encoder.initialize_hidden_state()
    checkpoint_dir = gConfig['model_data']
    ckpt=tf.io.gfile.listdir(checkpoint_dir)
    if ckpt:
        print("reload pretrained model")
        seq2seqModel.checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
    BUFFER_SIZE = len(input_tensor)
    dataset = tf.data.Dataset.from_tensor_slices((input_tensor,target_tensor)).shuffle(BUFFER_SIZE)
    dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)
    checkpoint_dir = gConfig['model_data']
    checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
    start_time = time.time()

    while True:
        start_time_epoch = time.time()
        total_loss = 0
        for (batch, (inp, targ)) in enumerate(dataset.take(steps_per_epoch)):
            batch_loss = seq2seqModel.train_step(inp, targ,target_token, enc_hidden)
            total_loss += batch_loss
            print(batch_loss.numpy())

        step_time_epoch = (time.time() - start_time_epoch) / steps_per_epoch
        step_loss = total_loss / steps_per_epoch
        current_steps = +steps_per_epoch
        step_time_total = (time.time() - start_time) / current_steps

        print('训练总步数: {} 每步耗时: {}  最新每步耗时: {} 最新每步loss {:.4f}'.format(current_steps, step_time_total, step_time_epoch,
                                                                      step_loss.numpy()))
        seq2seqModel.checkpoint.save(file_prefix=checkpoint_prefix)

        sys.stdout.flush()
def predict(sentence):
    checkpoint_dir = gConfig['model_data']
    seq2seqModel.checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
    sentence = preprocess_sentence(sentence)
    inputs = [input_token.word_index.get(i,3) for i in sentence.split(' ')]
    inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs],maxlen=max_length_inp,padding='post')
    inputs = tf.convert_to_tensor(inputs)

    result = ''

    hidden = [tf.zeros((1, units))]
    enc_out, enc_hidden = seq2seqModel.encoder(inputs, hidden)

    dec_hidden = enc_hidden
    dec_input = tf.expand_dims([target_token.word_index['start']], 0)

    for t in range(max_length_tar):
        predictions, dec_hidden, attention_weights = seq2seqModel.decoder(dec_input, dec_hidden, enc_out)

        predicted_id = tf.argmax(predictions[0]).numpy()

        if target_token.index_word[predicted_id] == 'end':
            break
        result += target_token.index_word[predicted_id] + ' '

        dec_input = tf.expand_dims([predicted_id], 0)

    return result

if __name__ == '__main__':
    if len(sys.argv) - 1:
        gConfig = getConfig.get_config(sys.argv[1])
    else:

        gConfig = getConfig.get_config()

    print('\n>> Mode : %s\n' %(gConfig['mode']))

    if gConfig['mode'] == 'train':

        train()
    elif gConfig['mode'] == 'serve':

        print('Serve Usage : >> python3 app.py')


import discord

cogs_list = [
    "help",
    "unveil",
    "bet",
    "account"
]

class Dealer(discord.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for cog in cogs_list:
            self.load_extension(f"cogs.{cog}")

    async def on_ready(self):
        print(f"{self.user} has connected to Discord!")


################011011100110010101101111####
### neo Command Line #######################
############################################

def getcmdlist():
    cmds = {
            "os"		:"Open active Schedule View in Excel.",
            "ov"		:"Open selected views in Project Browser."
           }
    return cmds

def runcmd(cmd, msg, recallCL=False):

    if cmd == 'os':
        from lib.views import neocl_open_schedule_xl as os
        os.ExportActiveScheduleViewToExcel()
    elif cmd == 'ov':
        from lib.views import neocl_views_open as ov
        ov.OpenSelectedViews()
    else:
        from neocl import unknowncmd
        unknowncmd(cmd, recallCL, getcmdlist())


from __future__ import absolute_import, print_function

import json
import os
import tempfile

import mock

import mesos.cli.cfg
import mesos.cli.cmds.config

from .. import utils

config_path = os.path.normpath(os.path.join(
    os.path.dirname(__file__), "..", "data", "config.json"))

class TestConfig(utils.MockState):

    @mock.patch('os.environ', {"MESOS_CLI_CONFIG": config_path})
    @utils.patch_args(["mesos-config"])
    def test_output(self):
        mesos.cli.cmds.config.CFG = mesos.cli.cfg.Config()

        mesos.cli.cmds.config.main()

        out = json.loads(self.stdout)
        assert "master" in out["test"]

    @mock.patch('os.environ', {"MESOS_CLI_CONFIG": config_path})
    @utils.patch_args([
        "mesos-config",
        "master"
    ])
    def test_get_key(self):
        mesos.cli.cmds.config.CFG = mesos.cli.cfg.Config()

        mesos.cli.cmds.config.main()

        assert "zk://localhost:2181/mesos" in self.stdout

    @utils.patch_args([
        "mesos-config",
        "master",
        "zk://localhost:2181/mesos"
    ])
    def test_set_key(self):
        fd, fname = tempfile.mkstemp()
        with open(fname, "w") as fobj:
            fobj.write("{}")
        try:
            with mock.patch('os.environ', {"MESOS_CLI_CONFIG": fname}):
                mesos.cli.cmds.config.CFG = mesos.cli.cfg.Config()

                mesos.cli.cmds.config.main()

                with open(fname, "r") as fobj:
                    assert "zk://localhost:2181" in json.loads(
                        fobj.read())["default"]["master"]
        finally:
            os.remove(fname)


from web3 import Web3, EthereumTesterProvider
from etherscan import Etherscan
import json

class Node:
    def __init__(self, name, value, address, children=[]):
        self.name = name
        self.value = value
        self.children = children
        self.searched = False
        self.address = Web3.toChecksumAddress(address)

class NodeOperations:
    def __init__(self, web3, etherscan):
        self.web3 = web3
        self.etherscan = etherscan

    def print_tree(self, node, level=0):
        print('    ' * level + node.name + ": \t" + node.address)
        for child in node.children:
            self.print_tree(child, level+1)

    def depth_first_search(self, node, depth, current_depth=0, nodeIterator=0):
        if current_depth >= depth: #Escape after depth reached or exceeded
            return
        if node.searched == True:
            return

        availibleABI = True

        #Handler for non verified smart contracts on etherscan
        try:
            contractABI = self.etherscan.get_contract_abi(node.address) #Use Etherscan API to get the contracts ABI
        except:
            print('Problem with the ABI')
            availibleABI = False #unavailible ABI (contract code not verified)

        if availibleABI: #If contract's ABI is verified
            contractInstance = self.web3.eth.contract(address=node.address, abi=contractABI) #Use web3 Library to create an instantiation of the contract
            contractABI = json.loads(contractABI) #convert ABI to json format

            for i in range(len(contractABI)): #Examine all functions/methods/variables in the ABI
                try:
                    if contractABI[i]['outputs'][0]['type'] == 'address': #Searching exclusively for addresses on the contract
                        if len(contractABI[i]['inputs']) == 0:  #Check function call does not require input
                            childAddress = eval("contractInstance."+"functions."+contractABI[i]['name']+"()"+".call()") #RPC call to the contract, return the 20byte address
                            child = Node(contractABI[i]['name'], nodeIterator, childAddress, []) #create node
                            node.children.append(child) #Append child node
                            #nodeIterator += 1
                            #print(f'Searching node...')
                        elif len(contractABI[i]['inputs']) == 1 and contractABI[i]['inputs'][0]['type'] == 'uint256': #This is an array of addresses:
                            print('Searching Array Node...')
                            try:
                                for j in range(0,10):
                                    #print(j)
                                    childAddress = eval("contractInstance."+"functions."+contractABI[i]['name']+"("+str(j)+ ")"+".call()") #RPC call to the contract, return the 20byte address
                                    child = Node(contractABI[i]['name'], nodeIterator, childAddress, []) #create node
                                    node.children.append(child) #Append child node
                                    nodeIterator += 1
                                    #print(f'Searching node...') #NOTE: Might need to put a check in for 0x0000... etc address.
                            except:
                                break
                        else:
                            pass
                except:
                    pass

            for child in node.children:
                child.name
                self.depth_first_search(child, depth, current_depth+1, nodeIterator)

            node.searched = True
        else:
            print(node.address)
            node.name = 'NO ABI AVAILIBLE'
            node.searched = True
            pass


from bs4 import BeautifulSoup
import requests

def wsearch(word):
    word = word.replace(" ", "-")

    url = f"https://dictionary.cambridge.org/dictionary/english/{word}"
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'
    headers = {'User-Agent': user_agent}

    page = requests.get(url, headers=headers).text
    doc = BeautifulSoup(page, 'html.parser')

    try:
        entries = doc.find(
            class_="hfl-s lt2b lmt-10 lmb-25 lp-s_r-20 x han tc-bd lmt-20 english").find_all(class_="pr entry-body__el")
        if entries == []:
            # for a single entry
            entries = doc.find(
                class_="hfl-s lt2b lmt-10 lmb-25 lp-s_r-20 x han tc-bd lmt-20 english").find_all(class_="pr di superentry")
        return entries
    except AttributeError:
        return None

def compileResult(entries):
    id = 0
    res = list()
    for entry in entries:
        # get the word
        word = entry.find(class_="di-title").text

        # get the word type
        try:
            wordType = entry.find(
                True, class_="pos dpos").text
        except AttributeError:
            wordType = ''

        # get the list of audio tags
        audioTags = []
        for tag in entry.find_all(class_="region dreg"):
            audioTags.append(tag.text)

        # get the list of audio links
        audioLinks = []
        for tag in entry.find_all('source', {"type": "audio/mpeg"}):
            audioLinks.append("https://dictionary.cambridge.org" + tag['src'])

        # merge the two lists
        mergedAudioList = []
        for tag, link in zip(audioTags, audioLinks):
            mergedAudioList.append({"tag": tag,
                                    "link": link})

        groups = entry.find_all(class_="def-block ddef_block")
        explanation = list()
        for group in groups:
            groupList = list()
            groupText = group.find_all(
                True, {"class": ["def ddef_d db", "eg deg"]})
            for text in groupText:
                c = ' '.join(text['class'])
                if c == "def ddef_d db":
                    groupList.append(
                        {
                            "type": "main",
                            "content": text.text
                        }
                    )
                elif c == "eg deg":
                    groupList.append(
                        {
                            "type": "example",
                            "content": text.text
                        }
                    )
            explanation.append(groupList)

        res.append(
            {"id": id,
             "word": word,
             "wordType": wordType,
             "audioLinks": mergedAudioList,
             "explanation": explanation
             }
        )
        id += 1
    return res

if __name__ == "__main__":
    entries = wsearch("hi")
    res = compileResult(entries)


import subprocess
import json
import argparse
import os
import requests

args = None

def main():
    global args
    parser = argparse.ArgumentParser(
        description='update cloudflare dns records')

    parser.add_argument('Domain',
                        metavar='domain',
                        type=str,
                        help='domain to update')

    parser.add_argument('--dryrun',
                        action='store_true',
                        help='dry run')

    parser.add_argument('--kind',
                        action='store',
                        type=str,
                        default='A',
                        help='type of record, e.g. A')

    parser.add_argument('--zone',
                        action='store',
                        type=str,
                        help='dns zone')

    parser.add_argument('--id',
                        action='store',
                        type=str,
                        help='ID of record to update')

    parser.add_argument('--email',
                        action='store',
                        type=str,
                        help='email')

    parser.add_argument('--api-token',
                        action='store',
                        type=str,
                        help='API token')

    parser.add_argument('--api-key',
                        action='store',
                        type=str,
                        help='API key')

    parser.add_argument('--a-name',
                        action='store',
                        type=str,
                        help='record  A name')

    parser.add_argument('--a-ip',
                        action='store',
                        type=str,
                        help='record  A IP')

    args = parser.parse_args()

    domain = args.Domain

    if (args.api_token == None):
        atoken = os.getenv('CF_API_TOKEN')
        if (atoken == None):
            print("can't find CF_API_TOKEN")
            os.exit(1)
        args.api_token = atoken

    if (args.api_key == None):
        akey = os.getenv('CF_API_KEY')
        if (akey == None):
            print("can't find CF_API_KEY")
            os.exit(1)
        args.api_key = akey

    if (args.zone== None):
        azone = os.getenv('CF_ZONE_ID')
        if (azone== None):
            print("can't find CF_ZONE_ID")
            os.exit(1)
        args.zone = azone

    find_gcp_vms_ip(callback1)

def find_gcp_vms_ip(cb):
    instances = subprocess.Popen(['gcloud', 'compute', 'instances', 'list', '--format=json'], stdout=subprocess.PIPE).communicate()[0]
    instances2 = json.loads(instances.decode('utf-8').replace('\n', ' '))
    for inst in instances2:
        name = inst['name']
        interface = inst['networkInterfaces'][0]
        if (interface == None):
            return
        accessConfigs = interface['accessConfigs']
        if (accessConfigs == None):
            return
        externalIP = accessConfigs[0]['natIP']
        if (externalIP == None):
            return
        cb(name,externalIP)

def cloudflare_update(name,ip,domain):
    url = f"https://api.cloudflare.com/client/v4/zones/{args.zone}/dns_records"
#    print(url)
    bearer_token = f"Bearer {args.api_token}"

    headers = {
        'Authorization': bearer_token,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
#    print(bearer_token)
#        'X-Auth-Email': f"{args.email}",
#        'X-Auth-Key': f"{args.api_key}",

    response = requests.post(
        url,
        headers=headers,
        data = {
            'type': args.kind,
            'name': name,
            'content': ip,
            'priority': 10,
            'ttl':120,
            'proxied':'false'
        }
    )
    print(response.json())

def callback1(name,externalIP):
    #print(args)
    #print(name,externalIP)
    cloudflare_update(name,externalIP,args.Domain)

if __name__ == "__main__":
    main()


#!/usr/bin/python
import httplib
import random
import argparse
import sys

#Get options
parser = argparse.ArgumentParser(
         description='Testing vote app')

parser.add_argument(
        '-port',
        type=int,
        help='port of server',
        default=8000)

parser.add_argument(
        '-host',
        type=str,
        help='server name/ip',
        default="localhost")

args = parser.parse_args()

#Color table
colorList = ["blue", "orange", "red", "green", "yellow" ]
colorSize = len(colorList) - 1

#Connect with server
conn = httplib.HTTPConnection(args.host, args.port)

#initial request
conn.request("GET", "/")
r1 = conn.getresponse()
#print(r1.status, r1.reason)
print(r1.read())

#vote loop
count = 0
while count < 100 :
    count = count + 1

    nColor = random.randint(0, colorSize)

    conn.request("GET", "/v1/vote?color="+colorList[nColor])
    r1 = conn.getresponse()
    #print(r1.read())

print

# view current results
conn.request("GET", "/v1/listVotes")
r1 = conn.getresponse()
print(r1.read())

conn.request("GET", "/v1/listWorkers")
r1 = conn.getresponse()
print(r1.read())

conn.close()