# Given two strings, write a method to decide if one is a permutation of the other.
# Example, Dog is considered a permutation of God.

def checkPermutation (string1, string2):
    """
    :param string1: string #1 to check if it is considered as a permutation for string #2.
    :param string2: string #2 to check if it is considered as a permutation for string #1.
    :return: True if one string is a permutation of the other, False otherwise.
    """
    if sorted(string1.lower()) == sorted(string2.lower()):
        return True
    return False

if __name__ == '__main__':
    print(checkPermutation("dOg","God"))


import httplib
import json
import os

import requests
from nose import tools
from nose.plugins import attrib

from tests.integration import base, testing_utilities

PATH_PARAMS = {
    'base_url': 'http://0.0.0.0:5000',
    'service': 'offers',
    'list_id': 'edaa3541-7376-4eb3-8047-aaf78af900da'
}

@attrib.attr('local_integration')
class AppendListEndpointTest(base.BaseIntegrationLiveStubServerTestCase):

    @classmethod
    def setUpClass(cls, **kwargs):
        super(AppendListEndpointTest, cls).setUpClass(**kwargs)
        base.BaseIntegrationTestCase.setUpClass()

    def setUp(self):
        self.test_file = testing_utilities.copy_test_file(file_name='normal_large.csv')
        self.test_path = os.path.join('tests/samples/{}'.format(self.test_file))
        self.headers = testing_utilities.generate_headers(base_url='http://live.lcpenv')
        self.data = {'filePath': self.test_path}

    def tearDown(self):
        testing_utilities.delete_test_files(self.test_file)

    def test_append_list_missing_file(self):
        data = {}
        response = requests.put(base.ListPaths.append(**PATH_PARAMS), json.dumps(data), headers=self.headers)
        response_content = json.loads(response.content)

        tools.assert_equal(httplib.BAD_REQUEST, response.status_code)
        tools.assert_equal(1, len(response_content['errors']))
        tools.assert_equal('MISSING_FIELD', response_content['errors'][0]['code'])
        tools.assert_equal("'filePath' is required.", response_content['errors'][0]['description'])

    def test_append_list_big_file(self):
        response = requests.put(base.ListPaths.append(**PATH_PARAMS), json.dumps(self.data), headers=self.headers)
        response_content = json.loads(response.content)

        tools.assert_equal(httplib.BAD_REQUEST, response.status_code)
        tools.assert_equal(1, len(response_content['errors']))
        tools.assert_equal('BAD_REQUEST', response_content['errors'][0]['code'])
        tools.assert_equal("There are too many accounts specified.", response_content['errors'][0]['description'])


import RPi.GPIO as GPIO
from ERROR import *
from time import sleep
import sys

'''
code reference by
https://cafe.naver.com/mechawiki/30
'''

GPIO.setmode(GPIO.BCM)

class Motor:
    def __init__(self):
        self.IN=[]
        self.speed=20
        self.count=0
        # self.countsperrev=512
        self.seq = [[1,0,0,0],
                    [1,1,0,0],
                    [0,1,0,0],
                    [0,1,1,0],
                    [0,0,1,0],
                    [0,0,1,1],
                    [0,0,0,1],
                    [1,0,0,1]]
        self.stepcount = 8
        self.dir = 0
        self.waittime = self.speed/float(20000)
        self.step_counter = 0
        self.step_dir = 0

    def Set_Input(self,*args):
        if(len(args) != 4):
            raise IN_LENGTH_ERROR
        else:
            self.IN = [port for port in args]

        for pin in self.IN:
            print("setting pins....")
            GPIO.setup(pin, GPIO.OUT)
            GPIO.output(pin, False)

    def Clockwise(self):
        # for i in range(8):
        #     print(6-i)
        #     self.Set_Output(6-i)
        #     sleep(self.speed/1000)

        self.step_dir = 1

        for pin in range(0,4):
            xpin = self.IN[pin]
            if self.seq[self.step_counter][pin] != 0:
                GPIO.output(xpin, True)
            else:
                GPIO.output(xpin, False)

        self.step_counter += self.step_dir

        if self.step_counter >= self.stepcount:
            self.step_counter = 0
        if self.step_counter < 0:
            self.step_counter = self.stepcount + self.step_dir

        sleep(self.waittime)

    def Counter_Clockwise(self):
        # for i in range(8):
        #     self.Set_Output(i)
        #     sleep(self.speed/1000)

        self.step_dir = -1

        for pin in range(0, 4):
            xpin = self.IN[pin]
            if self.seq[self.step_counter][pin] != 0:
                GPIO.output(xpin, True)
            else:
                GPIO.output(xpin, False)

        self.step_counter += self.step_dir

        if self.step_counter >= self.stepcount:
            self.step_counter = 0
        if self.step_counter < 0:
            self.step_counter = self.stepcount + self.step_dir

        sleep(self.waittime)

    def Set_Output(self,out):
        for i, port in zip(range(4), self.IN):
            #GPIO.output(port,bool(Bit_Read(self.lookup[out],i)))
            print(port,bool(Bit_Read(self.lookup[out],i)))

def Bit_Read(object:str, n:int)->int:

    return int(object[-(n+1)])


import numpy as np
import cv2

def cvt_object_label(img, ori_label_color, dst_label_color=None):

    if dst_label_color is None:
        dst_label_color = ori_label_color

    height, width, channels = img.shape
    blue_mask = np.ones([height, width, 1], dtype=np.uint8) * ori_label_color[0]
    green_mask = np.ones([height, width, 1], dtype=np.uint8) * ori_label_color[1]
    red_mask = np.ones([height, width, 1], dtype=np.uint8) * ori_label_color[2]
    color_mask = cv2.merge((blue_mask, green_mask, red_mask))

    # Set label_color to 0
    img = cv2.bitwise_xor(img, color_mask)

    # Set label_color to 255
    img = cv2.bitwise_not(img)

    # Set other pixel to 0
    mask = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, mask = cv2.threshold(mask, 254, 255, cv2.THRESH_BINARY)

    mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
    img = cv2.bitwise_and(mask, np.array(dst_label_color))

    return img


#!/usr/bin/env python3

def memoize(func):
    cache = {}

    def inner(n, m, l):
        if not (n, m, l) in cache:
            cache[(n, m, l)] = func(n, m, l)
        return cache[(n, m, l)]
    return inner

@memoize
def ends_with(total_size, end_size, sizes):
    if total_size == 0:
        return 1
    elif total_size < end_size:
        return 0
    else:
        total_combinations = 0
        for front_size in range(1, total_size - end_size + 1):
            for middle_size in sizes:
                total_combinations += ends_with(front_size, middle_size, sizes)
        return total_combinations + 1

def all_combinations(total_size, sizes):
    total_combinations = 0
    for front_size in range(1, total_size + 1):
        for end_size in sizes:
            total_combinations += ends_with(front_size, end_size, sizes)
    return total_combinations + 1

if __name__ == "__main__":
    from sys import argv
    n = int(argv[1])
    print(all_combinations(n, (2, 3, 4)))


# python hash_file_checker.py -i input_file -o output.txt
# -*- coding: utf-8 -*-

import hashlib
import argparse
import sys

def hashfile(input_file):
    """
    Creates an MD5, SHA1 and SHA256 hash of any file.

    This is useful if you have downloaded a file and need to compare the hash
    values with the values published by the publisher, to ensure that it has
    not been tampered with.
    """

    block_size = 2**20
    md5 = hashlib.md5()
    sha1 = hashlib.sha1()
    sha256 = hashlib.sha256()

    try:
        with open(input_file, 'rb') as f:
            while True:
                data = f.read(block_size)
                if not data:
                    break
                md5.update(data)
                sha1.update(data)
                sha256.update(data)

    except IOError:
        print('Please check that the input file is valid\n')

    md5_digest = md5.hexdigest().upper()
    sha1_digest = sha1.hexdigest().upper()
    sha256_digest = sha256.hexdigest().upper()

    return md5_digest, sha1_digest, sha256_digest

if __name__ == '__main__':

    # Parse arguments from command line
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', dest='input_file', help='mandatory input file')
    parser.add_argument('-o', dest='output_file', help='optional output file')
    parser.add_argument('-t', dest='target', help='optional provided hash')

    args = parser.parse_args()

    # Check validity of input file
    if args.input_file is None:
        sys.exit("\nPlease specify the input file with -i [input_file]\n")

    filein = args.input_file
    fileout = args.output_file
    target = args.target

    # Compute hash
    md5_digest, sha1_digest, sha256_digest = hashfile(filein)

    # If hash has been provided, compare it to computed hash
    if target is not None:
        try:
            target = target.upper()

            if (target == sha1_digest):
                print('\nFile: %s' % filein)
                print('SHA1 Hash matched:')
                print(sha1_digest)
                print(target)
                print('\nThe file looks authentic.\n')

            elif (target == md5_digest):
                print('\nFile: %s' % filein)
                print('MD5 Hash matched:')
                print(md5_digest)
                print(target)
                print('\nThe file looks authentic.\n')

            elif (target == sha256_digest):
                print('\nFile: %s' % filein)
                print('SHA256 Hash matched:')
                print(sha256_digest)
                print(target)
                print('\nThe file looks authentic.\n')

            else:
                print('\nFile:\t%s' % filein)
                print('\nWARNING: Try to redownload the file.\n')

        except IOError:
            print('Please check the hash you provided\n')

    else:
        print("\nFile:\t%s" % filein)
        print('MD5:\t%s' % md5_digest)
        print('SHA1:\t%s' % sha1_digest)
        print('SHA256:\t%s\n' % sha256_digest)


import json
import os
import time
import uuid

from datetime import datetime

from google.appengine.api import urlfetch
from google.appengine.ext import ndb

from models import Profile

def getUserId(user, id_type="email"):
    if id_type == "email":
        return user.email()

    if id_type == "oauth":
        """A workaround implementation for getting userid."""
        auth = os.getenv('HTTP_AUTHORIZATION')
        bearer, token = auth.split()
        token_type = 'id_token'
        if 'OAUTH_USER_ID' in os.environ:
            token_type = 'access_token'
        url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s'
               % (token_type, token))
        user = {}
        wait = 1
        for i in range(3):
            resp = urlfetch.fetch(url)
            if resp.status_code == 200:
                user = json.loads(resp.content)
                break
            elif resp.status_code == 400 and 'invalid_token' in resp.content:
                url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?%s=%s'
                       % ('access_token', token))
            else:
                time.sleep(wait)
                wait = wait + i
        return user.get('user_id', '')

    if id_type == "custom":
        # implement your own user_id creation and getting algorythm
        # this is just a sample that queries datastore for an existing profile
        # and generates an id if profile does not exist for an email
        profile = Conference.query(Conference.mainEmail == user.email())
        if profile:
            return profile.id()
        else:
            return str(uuid.uuid1().get_hex())

class MultiPropInequality(object):
    """Wrapper class that handles inequalities operating on multiple properties.

    NOTE: GQL is not supported.

    The original result set returned by the underlying query will be filtered
    using post filters. Only those results that satisfy all of the post filters
    will be handed back.

    For better effeciency, set the first inequality filter that is most likely
    to return the least number of data.

    To use:

        query = MultiPropInequality(Model)

    or with search by ancestor:

        query = MultiPropInequality(Model.query(ancestor=key))

    or with pre-built query:

        query = Model.query().filter(Model.prop='value')
        query = MultiPropInequality(query)

    filter() method returns self, so chaining is posible:

        query = MultiPropInequality(Model) \
                    .filter(Model.prop1<='value2') \
                    .filter(Model.prop2!='value2')

    filter() method updates itself (instead of creating a new query), so there
    is no need to reassign the variable:

        query = query.filter(Model.prop1!=0)    # Not necessary

        query.filter(Model.prop1!=0)            # (better) query is updated

    To access the result set, iterate through:

        for result in query:
            # do something with result
    """

    def __init__(self, model_or_query):
        """Creates new instance of this class.

        Parameters:
            model_or_query - Required. An instance of a Model or a pre-built
                             Query object with at most 1 property that is being
                             evaluated for inequalities.
        """
        if isinstance(model_or_query, ndb.model.MetaModel):
            self.query = model_or_query.query()
        elif isinstance(model_or_query, ndb.query.Query):
            self.query = model_or_query
        else:
            raise TypeError(
                'Must be a subclass of Model or an instance of Query.'
            )

        self.first_inequality = self._get_first_inequality(self.query.filters)
        self.post_inq_filters = []

    def filter(self, *args):
        """Checks if each arg is an inequality filter and appends it to the list
        inequality post filters.

        If arg is an inquality filter (or at least one of its subnodes is an
        inequality filter), and operates on a property that is different from
        the first inequality, then it will be added to the list of post
        inequality filters. Otherwise, it will be passed on to the underlying
        query.

        Parameters:
            args - Optional. Node. Can be instances of any of the subclasess of
                   Node (e.g. FilterNode, ConjunctionNode, DisjunctionNode).

        Returns the instance of this class.
        """
        if not args:
            return self

        for arg in args:
            if not isinstance(arg, ndb.query.Node):
                raise TypeError('Filter should be instance of Node.')
            if not self._push_filter(arg):
                self.query = self.query.filter(arg)

        return self

    def _get_first_inequality(self, f_node):
        """Returns the first inquality of a given node. Returns None if no
        inequality can be found.
        """
        inequalities = self._get_inequalities(f_node)
        return None if len(inequalities) == 0 else inequalities[0]

    def _get_inequalities(self, f_node):
        """Returns a list of inequalities in a given node and all of it's
        subnodes
        """
        inequalities = []
        if isinstance(f_node,
                (ndb.query.DisjunctionNode, ndb.query.ConjunctionNode)):
            for f_n in f_node:
               inequalities.extend(self._get_inequalities(f_n))
        elif isinstance(f_node, ndb.query.FilterNode):
            filter_dict = self._node_to_dict(f_node)
            if filter_dict['symbol'] != '=':
                inequalities.append(filter_dict)
        return inequalities

    def _push_filter(self, filter_node):
        """Adds filter_node to the list post inquality filters if filter_node
        has at least 1 inquality that operates on a property that is different
        from the first inequality.

        Returns True if filter_node is added to the list of post inquality
        filters. If filter_node is the first inequality, returns False.
        """
        inequalities = self._get_inequalities(filter_node)
        push_to_post = False

        for inq in inequalities:
            if not self.first_inequality:
                self.first_inequality = inq
            elif self.first_inequality['name'] != inq['name']:
                push_to_post = True
                break

        if push_to_post:
            self.post_inq_filters.append(filter_node)

        return push_to_post

    def _node_to_dict(self, f_node):
        """Converts a Filter to a dictionary"""
        filter_dict = {}
        node_dict = getattr(f_node, '__dict__')
        for key, value in node_dict.items():
            if key.endswith('name'):
                filter_dict['name'] = value
            elif key.endswith('symbol'):
                filter_dict['symbol'] = value
            elif key.endswith('value'):
                filter_dict['value'] = value
        return filter_dict

    def _make_evaluator(self, filter_node):
        """Returns an evaluator for a given FilterNode"""
        def make_closure(f_d):
            if (f_d['symbol'] == '>'):
                return lambda x: getattr(x, f_d['name']) > f_d['value']
            elif (f_d['symbol'] == '<'):
                return lambda x: getattr(x, f_d['name']) < f_d['value']
            elif (f_d['symbol'] == '>='):
                return lambda x: getattr(x, f_d['name']) >= f_d['value']
            elif (f_d['symbol'] == '<='):
                return lambda x: getattr(x, f_d['name']) <= f_d['value']
            elif (f_d['symbol'] == '!='):
                return lambda x: getattr(x, f_d['name']) != f_d['value']
            elif (f_d['symbol'] == '='):
                return lambda x: getattr(x, f_d['name']) == f_d['value']
            else:
                raise NotImplementedError(
                    'Unsuported operator: {}'.format(f_d['symbol'])
                )

        f_dict = self._node_to_dict(filter_node)

        # FilterNode coverts TimeProperty and DateProperty to datetime.
        # Convert back to time or date
        prop_type = ndb.Model._kind_map[self.query.kind] \
                        ._properties[f_dict['name']].__class__.__name__
        if prop_type == 'TimeProperty' \
                and isinstance(f_dict['value'], datetime):
            f_dict['value'] = f_dict['value'].time()
        elif prop_type == 'DateProperty' \
                and isinstance(f_dict['value'], datetime):
            f_dict['value'] = f_dict['value'].date()

        return make_closure(f_dict)

    def _make_and_evaluator(self, con_node):
        """Returns an evaluator that performs AND operation on subnodes of a
        given ConjunctionNode
        """
        post_evals = self._check_node(con_node)
        def and_evaluators(x):
            for p_eval in post_evals:
                if not p_eval(x):
                    return False
            return True

        return and_evaluators

    def _make_or_evaluator(self, dis_node):
        """Returns an evaluator that performs OR operation on subnodes of a
        given DisjunctionNode
        """
        post_evals = self._check_node(dis_node)
        def or_evaluators(x):
            for p_eval in post_evals:
                if p_eval(x):
                    return True
            return False

        return or_evaluators

    def _check_node(self, a_node):
        """Returns a list of evaluator functions from a given Node"""
        output = []
        for f_n in a_node:
            if isinstance(f_n, ndb.query.ConjunctionNode):
                output.append(self._make_and_evaluator(f_n))
            elif isinstance(f_n, ndb.query.DisjunctionNode):
                output.append(self._make_or_evaluator(f_n))
            elif isinstance(f_n, ndb.query.FilterNode):
                output.append(self._make_evaluator(f_n))
            # FalseNode is ignored
            # ParameterNode is not yet supported
        return output

    def __iter__(self):
        """Iterates through the result set of the underlying query, and hands
        back only those that satify all of the post inequality filters.
        """
        post_evaluator = self._make_and_evaluator(self.post_inq_filters)
        for result in self.query:
            try:
                if post_evaluator(result):
                    yield result
            except TypeError:
                pass            # Value of a property from datastore is None


import pymysql
import time
import random

from selenium import webdriver
class main():
    def s(self,a,b):
        ti=random.randint(a,b)
        time.sleep(ti)

    def init(self,url):
        #selenium登录
        browser = "Chrome"
        if browser == "Chrome":
            option = webdriver.ChromeOptions()
            # option.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) #去掉不受支持的命令行标记
            #option.add_argument(                '--user-data-dir=C:\\Users\\coco.chen\\AppData\\Local\\Google\\Chrome\\User Data')  # 设置成用户自己的数据目录
            driver = webdriver.Chrome(chrome_options=option)
        else:
            if browser == "Firefox":
                driver = webdriver.Firefox()
            else:
                driver = webdriver.PhantomJS()

        driver.get(url)

        #等待用户自己登陆

        #判断是否登陆成功
        name = input("Go?")
        print(name)

        driver.get('https://vcp.jd.com/sub_item/item/initItemListPage')
        self.s(3, 4)

        prt_data=self.get_sku_id()
        for i in range (len(prt_data)):
            sku_id=prt_data[i][0]
            new_sku_name=prt_data[i][1]
            print(sku_id,new_sku_name)

            driver.find_element_by_id('wareId').clear()
            driver.find_element_by_id('wareId').send_keys(sku_id)

            self.s(1,2)
            driver.find_element_by_css_selector('.btn.btn-primary').click()
            self.s(2,3)

            nowhandle = driver.current_window_handle  # 在这里得到当前窗口句柄
            btn_down_path = "//table[@class='grid']/tbody/tr[1]/td[@id='td_wareId']/div/button[@class='btn btn-default dropdown-toggle']"
            driver.find_element_by_xpath(btn_down_path).click()
            self.s(1,1)
            driver.find_elements_by_xpath("//ul[@class='dropdown-menu']/li/a")[0].click()
            self.s(5, 6)
            # 需要获取新弹开的窗口
            allhandles = driver.window_handles  # 获取所有窗口句柄
            for handle in allhandles:  # 在所有窗口中查找弹出窗口
                if handle != nowhandle:
                    driver.close()
                    driver.switch_to.window(handle)
            current_url = driver.current_url
            print(current_url)
            if "https://vcp.jd.com/sub_item/item/initItemListPage" in current_url:
                self.update_caigou_price(sku_id,'reviewing')
            else:
                driver.get(current_url)
                content = driver.page_source
                # print(content)
                self.s(3, 4)
                driver.find_element_by_id('cid3Submit').click()
                self.s(2, 4)

                driver.find_element_by_id('auditedSubmit').click()
                self.s(2, 4)

                yanse = "黑色"
                driver.find_elements_by_class_name("combo-arrow")[1].click()
                if yanse == "红色":
                    yanse_xpath = "//div[@value='703187' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "黄色":
                    yanse_xpath = "//div[@value='703188' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "蓝色":
                    yanse_xpath = "//div[@value='703189' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "绿色":
                    yanse_xpath = "//div[@value='703190' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "双色":
                    yanse_xpath = "//div[@value='703193' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "黑色":
                    yanse_xpath = "//div[@value='703192' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()
                elif yanse == "白色":
                    yanse_xpath = "//div[@value='703191' ]"
                    driver.find_element_by_xpath(yanse_xpath).click()

                driver.find_element_by_id('createApply').click()
                self.s(1, 2)

            driver.get('https://vcp.jd.com/sub_item/item/initItemListPage')
            self.s(3, 4)

    def get_sku_id(self):
        db = pymysql.connect("10.168.2.147", "root", "123456", "jd_vcp")
        cursor = db.cursor()
        db.set_charset("utf8")
        cursor.execute("SET NAMES utf8;")
        cursor.execute("SET CHARACTER SET utf8;")
        cursor.execute("SET character_set_connection=utf8;")
        sql = "select sku_id,new_sku_name from sku_name_change where status is null "
        try:
            cursor.execute(sql)
            data = cursor.fetchall()
            return data
        except Exception as err:
            db.rollback()
            print('---------------Error------Message--------:' + str(err))
        cursor.close()
        db.close()

    def update_caigou_price(self,sku_id,state):
        db = pymysql.connect("10.168.2.147", "root", "123456", "jd_vcp")
        cursor = db.cursor()
        db.set_charset("utf8")
        cursor.execute("SET NAMES utf8;")
        cursor.execute("SET CHARACTER SET utf8;")
        cursor.execute("SET character_set_connection=utf8;")
        sql = "update sku_name_change set  status='%s' where sku_id ='%s'" %(state,sku_id)
        try:
            cursor.execute(sql)
            db.commit()
        except Exception as err:
            db.rollback()
            print('---------------Error------Message--------:' + str(err))
        cursor.close()
        db.close()

if __name__=="__main__":
    main=main()
    #url="http://www.baidu.com"
    url="https://passport.jd.com/new/login.aspx?rs=vc&ReturnUrl=//vcp.jd.com"
    main.init(url)

JD后台/VC后台/正阳门-商品重新提交.py

正阳门-商品重新提交.py


##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Viewlet tests

$Id: tests.py 39461 2005-10-15 10:45:13Z srichter $
"""
__docformat__ = 'restructuredtext'

import unittest
import zope.component.interfaces
import zope.interface
from zope.testing import doctest, doctestunit

from zope.app.container import contained
from zope.app.renderer import rest
from zope.app.testing import placelesssetup, setup, ztapi

def setUp(test):
    setup.placefulSetUp(True)
    zope.component.provideAdapter(contained.NameChooser,
                                  (zope.interface.Interface,))
    # Register Renderer Components
    ztapi.provideUtility(zope.component.interfaces.IFactory,
                         rest.ReStructuredTextSourceFactory,
                         'zope.source.rest')
    ztapi.browserView(rest.IReStructuredTextSource, '',
                      rest.ReStructuredTextToHTMLRenderer)

def tearDown(test):
    setup.placefulTearDown()

def test_suite():
    return unittest.TestSuite((
        doctestunit.DocFileSuite('README.txt',
                     setUp=placelesssetup.setUp,
                     tearDown=placelesssetup.tearDown,
                     optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,
                     ),
        doctestunit.DocFileSuite('session.txt',
                     setUp=setUp, tearDown=tearDown,
                     globs={'pprint': doctestunit.pprint},
                     optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,
                     ),
        doctestunit.DocFileSuite('testbrowser.txt',
                     setUp=setUp, tearDown=tearDown,
                     globs={'pprint': doctestunit.pprint},
                     optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,
                     ),
        doctestunit.DocFileSuite('directives.txt',
                     setUp=placelesssetup.setUp,
                     tearDown=placelesssetup.tearDown,
                     optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS,
                     ),
        ))

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


from numpy import array
import tensorflow as tf

# import os
# os.environ['TF_ENABLE_CONTROL_FLOW_V2'] = '1'
import numpy as np
import random
from tensorflow.keras.preprocessing.sequence import pad_sequences
#from tensorflow.keras import layers
import tensorflow as tf
#import tensorflow.compat.v1 as tf
#tf.disable_v2_behavior()

#from tensorflow.keras.layers import concatenate
#from keras.models import Model
#from keras.models import Sequential
#from keras.layers import Dense,InputLayer

from tensorflow.keras.callbacks import LearningRateScheduler, EarlyStopping, ModelCheckpoint,ReduceLROnPlateau
from tensorflow.keras.layers import Dense,Dropout, Bidirectional,BatchNormalization, LSTM, Input, Embedding, GlobalMaxPool1D
from tensorflow.keras.models import Model
#from keras.callbacks import ModelCheckpoint
#from tensorflow.keras.layers import CuDNNLSTM

from sklearn.model_selection import train_test_split

from sklearn.metrics import classification_report
from sklearn.metrics import precision_score , recall_score
from matplotlib import pyplot as plt
import sys
#tf.compat.v1.disable_eager_execution()
tf.compat.v1.enable_eager_execution()
tf.random.set_seed(2)
# tf.enable_eager_execution()
# tf.disable_eager_execution()
# config = tf.compat.v1.ConfigProto()
# config.gpu_options.allow_growth=True
# sess = tf.compat.v1.Session(config=config)
# tf.keras.backend.set_session(sess)
physical_devices = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True)

max_seq_len = int(sys.argv[1])
batch_size_input = int(sys.argv[2])
feature = str(sys.argv[3])
file_name = str(sys.argv[0][0:-3])+'_'+feature
print(file_name)
print(tf.__version__)

print(tf.keras.__version__)
print("Training ",max_seq_len)
#tf.keras.backend.clear_session()
#tf.reset_default_graph()
#sess = tf.keras.backend.get_session()
traindata =  np.load(feature+'_training31486_2100.npy')
training_labels = np.asarray([[1,0]]*int(traindata.shape[0]/2)+[[0,1]]*int(traindata.shape[0]/2))
print("Loaded Training")
validate_data = np.load(feature+'_validation6748_2100.npy')
validate_labels  = np.asarray([[1,0]]*int(validate_data.shape[0]/2)+[[0,1]]*int(validate_data.shape[0]/2))
print("Loaded Validate",validate_labels.shape)
test_data = np.load(feature+'_testing6746_2100.npy')
test_labels  = np.asarray([[1,0]]*int(test_data.shape[0]/2)+[[0,1]]*int(test_data.shape[0]/2))
print("Loaded Test")

# define class labels

#tf.keras.backend.clear_session()
#tf.compat.v1.global_variables_initializer()
seed = 2048 #2048,4
np.random.seed(seed)
#perform shuffle
print("Shuffling training")
randomize = np.arange(len(traindata))
np.random.shuffle(randomize)
traindata = traindata[randomize]
training_labels = training_labels[randomize]

print("Shuffling validate")
randomize = np.arange(len(validate_data))
np.random.shuffle(randomize)
validate_data = validate_data[randomize]
validate_labels = validate_labels[randomize]

print("Shuffling test")
randomize = np.arange(len(test_data))
np.random.shuffle(randomize)
test_data = test_data[randomize]
test_labels = test_labels[randomize]
print("Done Shuffling")

vocab_size = 2950
max_length = max_seq_len
padded_training = pad_sequences(traindata, maxlen=max_length, truncating='post', padding='post')
padded_validation = pad_sequences(validate_data, maxlen=max_length, truncating='post', padding='post')
padded_test = pad_sequences(test_data, maxlen=max_length, truncating='post', padding='post')
print("Done Padding")

# model = tf.keras.Sequential([
#     tf.keras.layers.Embedding(vocab_size, 128),

#     tf.keras.layers.LSTM(100,return_sequences=True),
#     tf.keras.layers.LSTM(100,return_sequences=True),
#     tf.keras.layers.LSTM(100,return_sequences=False),

#     #tf.keras.layers.CuDNNLSTM(128),

#     #tf.keras.layers.Dropout(0.1),

#     # tf.keras.layers.CuDNNLSTM(128,return_sequences=True),
#     # tf.keras.layers.Dropout(0.5),
#     # tf.keras.layers.CuDNNLSTM(64),
#     # tf.keras.layers.Dropout(0.5),

#     # tf.keras.layers.Bidirectional(tf.keras.layers.CuDNNLSTM(256,return_sequences=True)),
#     # tf.keras.layers.Bidirectional(tf.keras.layers.CuDNNLSTM(128)),

#     #tf.keras.layers.Dense(64, activation='relu'),
#     # tf.keras.layers.Dense(32, activation='relu'),
#     #tf.keras.layers.Dropout(0.1),
#     tf.keras.layers.Dense(2,activation='softmax')
# ])

# inp = Input(shape=(max_length,))
# emb = Embedding(vocab_size, 128)(inp)
# lstml1 = Bidirectional(LSTM(128,return_sequences=True))(emb)
# lstml2 = (LSTM(128))(lstml1)
# dense1 = Dense(64, activation= 'relu')(lstml2)
# dense2 = Dense(64, activation= 'relu')(dense1)
# outp = Dense(2, activation='softmax')(dense2)
# model = Model(inp, outp)

model = tf.keras.Sequential()
model.add(Embedding(vocab_size, 128, input_length=max_length))
model.add((LSTM(128, return_sequences=False)))
model.add(Dense(64, activation= 'relu'))
model.add(Dense(2, activation='softmax'))

print ('Compiling...')

# compile the model
# model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
#                optimizer=tf.keras.optimizers.Adam(1e-5),
#              metrics=['accuracy'])
model.compile(optimizer=tf.keras.optimizers.Nadam(1e-4), loss='binary_crossentropy', metrics=['accuracy'])
# load_weight_test = tf.keras.models.load_model('./trainedNets/train_rnn_single_450_batch128batch.h5')
#model.load_weights('./trainedNets/train_rnn_single_450_batch128batch.h5')
#model.compile(optimizer='adam', loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics=['accuracy'])

print("Done Compile")
batchSize=batch_size_input
patienceEarlyStop=15
weightDecay=0.1#0.1
patienceReduceLrLoss=10
learningRate=1e-4
oriFileName = './trainedNets3/'+file_name +'_'+ str(max_length) + '_batch' + str(batchSize) + '.h5'
#es = EarlyStopping(monitor='val_loss', mode='min', verbose=2)
es = EarlyStopping(monitor='val_loss', patience=patienceEarlyStop, verbose=2, mode='min')

mcp_save = ModelCheckpoint(oriFileName, save_best_only=True, monitor='val_loss', mode='min')
reduce_lr_loss = ReduceLROnPlateau(monitor='val_loss', factor=weightDecay, patience=patienceReduceLrLoss, verbose=2, min_delta=learningRate, mode='min')

print("Done ES")
# summarize the model
print(model.summary())
# fit the model
history = model.fit(padded_training, training_labels, validation_data=(padded_validation,validate_labels) ,epochs=500, verbose=2, batch_size = batchSize, callbacks=[es,reduce_lr_loss,mcp_save])

parentFileName = file_name +'_'+ str(max_length) + '_batch' + str(batchSize)
#plot training acc and save
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.savefig(parentFileName+'_train_acc.png')

plt.clf()
plt.cla()

#plot training loss and save
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.savefig(parentFileName+'_train_loss.png')

loaded_model = tf.keras.models.load_model(oriFileName)

print()
loss, accuracy = loaded_model.evaluate(padded_training, training_labels, verbose=2)
print('Training Accuracy: %f' % (accuracy*100))
t_accuracy = (accuracy*100)
loss, accuracy = loaded_model.evaluate(padded_validation, validate_labels, verbose=2)
print('Validation Accuracy: %f' % (accuracy*100))
v_accuracy = (accuracy*100)

loss, accuracy = loaded_model.evaluate(padded_test, test_labels, verbose=2)
print('Test Accuracy: %f' % (accuracy*100))
te_accuracy = accuracy*100

#Taking 2nd element
ylist = []
for i in test_labels:
  ylist.append(i[1])

ylist = np.asarray(ylist)
#print(ylist)

print("Printing metrics")
print("=======================================================================")
y_pred = loaded_model.predict(padded_test, batch_size=batchSize, verbose=2)
y_pred_bool = np.argmax(y_pred, axis=1)

print(classification_report(ylist, y_pred_bool))
print()
with open(str(parentFileName)+"_metrics.txt", 'w') as f:
  f.write("Training Accuracy : " +str(t_accuracy))
  f.write("\nValidation Accuracy : " +str(v_accuracy))
  f.write("\nTesting Accuracy : " +str(te_accuracy))
  f.write("\n" +str(classification_report(ylist, y_pred_bool)))
#other instructions
f.close()


import csv
import os
from multiprocessing.pool import ThreadPool
from time import time as timer

import requests

def fetch_url(entry):
    filename, uri = entry
    path = "data/2018/matches/{0}".format(filename)

    if not os.path.exists(path):
        r = requests.get(uri, stream=True)
        if r.status_code == 200:
            with open(path, 'wb') as f:
                for chunk in r:
                    f.write(chunk)
    return path

def matches_uri(end_of_uri):
    return "https://www.fifa.com{0}".format(end_of_uri)

with open("data/2018/matches.csv", "r") as teams_file:
    reader = csv.reader(teams_file, delimiter=",")
    next(reader)

    urls = []
    for row in reader:

        if int(row[0]) == 2018:
            match_id = row[1].split("/")[-2].replace("match=", "")
            api_uri = "https://api.fifa.com/api/v1/live/football/17/254645/275073/{0}".format(match_id)
            urls.append(("api/{0}.json".format(match_id), api_uri))

start = timer()
results = ThreadPool(8).imap_unordered(fetch_url, urls)
for path in results:
    print(path)
print("Elapsed Time: %s" % (timer() - start,))


import numpy as np
import math

import matplotlib.pyplot as plt

def get_mn_log_likelihood(obs,probs):
    """ Return the (log)likelihood of obs, given the probs"""
    multinomial_coeff_denom= 0
    prod_probs = 0
    for x in range(0,len(obs)): # loop through state counts in each observation
        multinomial_coeff_denom = multinomial_coeff_denom + math.log(math.factorial(obs[x]))
        prod_probs = prod_probs + obs[x]*math.log(probs[x])

    multinomial_coeff = math.log(math.factorial(sum(obs))) -  multinomial_coeff_denom
    likelihood = multinomial_coeff + prod_probs
    return likelihood

# 1st:  Coin B, {HTTTHHTHTH}, 5H,5T
# 2nd:  Coin A, {HHHHTHHHHH}, 9H,1T
# 3rd:  Coin A, {HTHHHHHTHH}, 8H,2T
# 4th:  Coin B, {HTHTTTHHTT}, 4H,6T
# 5th:  Coin A, {THHHTHHHTH}, 7H,3T
# so, from MLE: pA(heads) = 0.80 and pB(heads)=0.45

head_counts = np.array([5,9,8,4,7])
tail_counts = 10-head_counts
experiments = zip(head_counts,tail_counts)

pA_heads = np.zeros(100); pA_heads[0] = 0.60
pB_heads = np.zeros(100); pB_heads[0] = 0.50

# E-M begins!
delta = 0.001
j = 0 # iteration counter
improvement = float('inf')
while (improvement>delta):
    expectation_A = np.zeros((5,2), dtype=float)
    expectation_B = np.zeros((5,2), dtype=float)
    for i in range(0,len(head_counts)):
        e = [head_counts[i],tail_counts[i]] # i'th experiment
        ll_A = get_mn_log_likelihood(e,np.array([pA_heads[j],1-pA_heads[j]])) # loglikelihood of e given coin A
        ll_B = get_mn_log_likelihood(e,np.array([pB_heads[j],1-pB_heads[j]])) # loglikelihood of e given coin B

        weightA = math.exp(ll_A) / ( math.exp(ll_A) + math.exp(ll_B) ) # corresponding weight of A proportional to likelihood of A
        weightB = math.exp(ll_B) / ( math.exp(ll_A) + math.exp(ll_B) ) # corresponding weight of B proportional to likelihood of B

        expectation_A[i] = np.dot(weightA, e)
        expectation_B[i] = np.dot(weightB, e)

    pA_heads[j+1] = sum(expectation_A)[0] / sum(sum(expectation_A));
    pB_heads[j+1] = sum(expectation_B)[0] / sum(sum(expectation_B));
    print(pA_heads[j+1], pB_heads[j+1])
    improvement = max( abs(np.array([pA_heads[j+1],pB_heads[j+1]]) - np.array([pA_heads[j],pB_heads[j]]) ))
    j = j+1
print(j)

deltas = np.array([0.00001, 0.0001, 0.001, 0.01, 0.1])
iterations = np.array([13, 11, 8, 5, 2])

#figsize(7, 5)
plt.plot([0.00001, 0.0001, 0.001, 0.01, 0.1], [13, 11, 8, 5, 2], 'ro')
plt.axis([-0.001, 0.11, 0, 14])
plt.xlabel('Tolerance level')
plt.ylabel('Iterations')
plt.title('Relationship between tolerance level and number of iterations')
plt.savefig('coin_toss.pdf')


#!/usr/bin/env python

import os
import fnmatch
import re

from yaml import dump as yaml_dump
try:
	from yaml import CDumper as Dumper
except ImportError:
	from yaml import Dumper

try:
	from colorama import init as colorama_init
	from colorama import Fore, Style
except ImportError:
	class EmptyString(object):
		def __getattr__(self, name):
			return ''

	def colorama_init(autoreset=False):
		pass

	Fore = EmptyString()
	Style = EmptyString()
	Back = EmptyString()

verbose = True

# Lists of the file extensions to check for rospy or roscpp nodes.
python_ext = ['py']
cpp_ext = ['c', 'cpp', 'cc', 'cxx']

#def write_yaml
def write_yaml(pynodes, cppnodes):
	output = {'nodes': \
				[{'name': n['name'], 'exec':os.path.basename(n['path'])} for n in pynodes + cppnodes]
			 }

	return yaml_dump(output, default_flow_style = False)

#def check_for_errors
def check_for_errors(pynodes, cppnodes):
	nodes = pynodes + cppnodes

	### Check for multiple nodes with the same name.
	duplicates = {}
	for node in nodes:
		if node['name'] in duplicates:
			duplicates[node['name']] += 1
		else:
			duplicates[node['name']] = 1

	for node, dups in duplicates.items():
		if dups > 1:
			print(Fore.YELLOW + "Warning: " + str(dups) + " nodes found with name '" + node + "'!")

	### Check for multiple nodes defined in the same file.
	duplicates = {}
	for node in nodes:
		if node['path'] in duplicates:
			duplicates[node['path']] += 1
		else:
			duplicates[node['path']] = 1

	for node, dups in duplicates.items():
		if dups > 1:
			print(Fore.YELLOW + "Warning: " + str(dups) + " nodes initialized in source file '" + node + "'!")

	return False

#def parse_cpp
def parse_cpp(files):
	cpp_rosincludes = []
	cpp_nodes = []

	# Loop through the input files.
	for f in files:
		included = False

		# Open the file for reading.
		fread = open(f, 'r')
		if fread != None:
			# If there are no errors, loop through the lines in the file.
			for line in fread:
				match = False
				if included:
					# If we find a ros::init call, mark down that there's a node in this
					# file.  Keep searching, because it's possible that multiple nodes are
					# defined in a single file.
					match = re.search('ros::init\(.+?, ?.+?, ?"(.+?)"\)', line)
					if match:
						cpp_nodes.append({'path':f, 'name':match.group(1)})
						continue
				# If we haven't included ros.h, look for the include call.
				else:
					match = re.search('#include ((<)?(")?)ros/ros.h(?(2)>)(?(3)")', line)
					if match:
						included = True
		# If included, add to cpp_rosincludes
		if included:
			cpp_rosincludes.append(f)

	if verbose:
		if len(cpp_rosincludes) > 0:
			print(Fore.BLUE + 'Found ' + str(len(cpp_rosincludes)) + ' c++ files that include ros.h:')
			print(Fore.BLUE + '    ' + ', '.join(cpp_rosincludes))
		else:
			print(Fore.BLUE + 'Found 0 c++ files that include ros.h.')

	# We've searched all files, so let's return our results.
	return cpp_nodes

### This function parses the python files to find rospy imports
### and calls to rospy.init_node.
def parse_py(files):
	py_rosimports = []
	py_nodes = []

	# Loop through the input files.
	for f in files:
		imported = False
		modname = 'rospy'

		# Open the file for reading.
		fread = open(f, 'r')
		if fread != None:
			# If there are no errors, loop through the lines in the file.
			for line in fread:
				match = False
				# If we've imported rospy, try to find an init_node call.
				match = re.search(modname + '.init_node\(\'(.+?)\'', line)
				if imported:
					# If we find a init_node call, mark down that there's a node in this
					# file.  Keep searching, because it's possible that multiple nodes are
					# defined in a single file.
					if match:
						py_nodes.append({'path':f, 'name':match.group(1)})
						continue
				# If we haven't imported rospy, look for the import.
				else:
					# Try first to match the import ... as ... statement.
					match = re.search('import rospy as (.+)', line)
					# If successful, save the name rospy was imported as.
					if match:
						imported = True
						modname = match.group(1)
					# If not, try to match 'import rospy'.
					else:
						match = re.search('import rospy', line)
						if match:
							imported = True

			# We've reached EOF.  Keep track of nodes that have been imported.
			if imported:
				py_rosimports.append(f)

	if verbose:
		if len(py_rosimports) > 0:
			print(Fore.BLUE + 'Found ' + str(len(py_rosimports)) + ' python files with rospy imports:')
			print(Fore.BLUE + '    ' + ', '.join(py_rosimports))
		else:
			print(Fore.BLUE + 'Found 0 python files with rospy imports.')

	# We've searched all files, so let's return our results.
	return py_nodes

### This function generates two lists, one of c++ source files
### recursively below this directory, and the second of python
### source files.  This is a "dumb" function - it only filters
### using file extensions, it doesn't infer type from content.
def gen_file_lists():
	file_lists = ([], [])
	for root, dirs, files in os.walk('.'):
		for pext in python_ext:
			for f in fnmatch.filter(files, '*.' + pext):
				file_lists[0].append(os.path.join(root, f))
		for cext in cpp_ext:
			for f in fnmatch.filter(files, '*.' + cext):
				file_lists[1].append(os.path.join(root, f))

	return file_lists

def main():
	# Initialize colorama for colored output.
	colorama_init(autoreset=True)

	# Get the list of files for consideration.
	py_files, cpp_files = gen_file_lists()

	# Filter the python files to the ones that call rospy.init_node().
	py_nodes = parse_py(py_files)
	# Filter the c++ files to the ones that call ros::init().
	cpp_nodes = parse_cpp(cpp_files)

	# If there are no errors, convert the node lists to YAML and write them to project.yaml.
	if not check_for_errors(py_nodes, cpp_nodes):
		projfile = open('project.yaml', 'w')
		projfile.write(write_yaml(py_nodes, cpp_nodes))

		print(Fore.GREEN + "RIDE node file generated without errors!")
		print(Style.BRIGHT + "Make sure to look at the generated file, as it is likely incorrect/incomplete.")

if __name__ == '__main__':
	main()


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

import threading
import time
import sys
import os
from random import randint

clocks = ["\U0001F550", "\U0001F551", "\U0001F552", "\U0001F553", "\U0001F554", "\U0001F555", "\U0001F556", "\U0001F557", "\U0001F558", "\U0001F559", "\U0001F55A", "\U0001F55B"]

def background():
        i = randint(0, 9)
        while True:
            time.sleep(0.5)
            os.system('clear')
            print(clocks[i])
            i += 1
            if(i==12):
                i=0

def other_function():
    print('action')

# now threading1 runs regardless of user input
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()

while(1):
    dumb = input()
    print(dumb)
    quit()


import socket
import threading
import sys
from tkinter import *
import json

username = ''
ip = ''
client = None

with open('./Client/latest.json') as json_file:
	latest = json.load(json_file)

def addd(new_data):
	global latest
	if new_data in latest:
		pass
	else:
		if len(latest) == 10:
			latest.remove(latest[-1])
		latest = [new_data] + latest
		with open('./Client/latest.json', 'w') as outfile:
			json.dump(latest, outfile)

class con:

	def __init__(self):
		self.root = Toplevel(window)
		self.root.geometry('250x250')
		self.root.title('Connection')
		Label(self.root, text='Username', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=40, y=30)
		n = StringVar()
		self.Name=Entry(self.root, text=n)
		self.Name.place(x=40, y=60)
		Label(self.root, text='Server IP', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=40, y=90)
		i = StringVar()
		self.IP=Entry(self.root, text=i)
		self.IP.place(x=40, y=120)
		Button(self.root, text='Confirm', bg='#F0F8FF', font=('arial', 12, 'normal'), command=self.send).place(x=70, y=150)
		self.root.mainloop()

	def send(self):
		global username
		global ip
		global client
		username = self.Name.get()
		ip = self.IP.get()
		username = username.strip()
		ip = ip.strip()
		if ((len(username) > 0) and (len(ip) > 0)):
			client = Client(ip, username)
			print('Connected to {} as {}.'.format(ip, username))
			messages.insert(INSERT, 'Connected to {} as {}.\n\n'.format(ip, username))
			messages.see(END)
			client.sendMsg('joined the chat.')
			addd((ip, username))
			self.root.destroy()
			#threading.Thread(target=client.work)

def recon(conn):
	global client
	client = Client(conn[0], conn[1])
	print('Connected to {} as {}.'.format(conn[0], conn[1]))
	messages.insert(INSERT, 'Connected to {} as {}.\n\n'.format(conn[0], conn[1]))
	client.sendMsg('joined server')
	messages.see(END)

window = Tk()
input_user = StringVar()
input_field = Entry(window, text=input_user)
input_field.pack(side=BOTTOM, fill=X)
sb = Scrollbar(window)
messages = Text(window)
sb.pack(side = RIGHT, fill = Y)
messages.pack()

sb.config( command = messages.yview )

menubar = Menu(window)

menubar.add_command(label="Connect", command=con)
if len(latest) > 0:
	reco = Menu(menubar, tearoff=0)
	for item in latest:
		reco.add_command(label='As {} to {}'.format(item[1], item[0]), command=lambda: recon(item))
	menubar.add_cascade(label="Reconnect", menu=reco)
menubar.add_command(label="Exit", command=window.quit)
window.config(menu=menubar)

#input_user = StringVar()
#input_field = Entry(window, text=input_user)
#input_field.pack(side=BOTTOM, fill=X)

def Enter_pressed(event):
	input_get = input_field.get()
	input_user.set('')
	input_get = input_get.strip()
	if len(input_get) > 0:
		client.sendMsg(input_get)
		#messages.insert(INSERT, '%s\n' % input_get)
		messages.see(END)
		return "break"

frame = Frame(window)
input_field.bind("<Return>", Enter_pressed)
frame.pack()

class Client:

	def sendMsg(self, mes):
		self.sock.send(bytes(str([self.name, mes]), 'utf-8'))

	def __init__(self, address, username):
		self.name = username
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		address, port = address.split(':')
		self.sock.connect((address, int(port)))

		iThread = threading.Thread(target=self.work)
		iThread.daemon = True
		iThread.start()

	def work(self):
		while True:

			data = self.sock.recv(1024)
			if not data:
				break
			data = str(data, 'utf-8')
			data = eval(data)
			user, data = data[0], data[1]
			if len(user)>7:
				user += '\t'
			else:
				user += '\t\t'
			messages.insert(INSERT, user + str(data) + '\n\n')
			messages.see(END)
			#return user + str(data)

#client = Client(address, username)
window.mainloop()


import view
import user_input
import todo_controller
import database

def see_all_todos():
    view.see_all_todos()
    todo_controller.print_todos()

def what_to_update(index):
    index -= 1
    while True:
        view.update_description_or_set_done()
        chosen = user_input.return_int()
        if chosen == 1:
            todo_controller.set_new_description(index)
            break
        elif chosen == 2:
            todo_controller.set_todo_done(index)
            break
        elif chosen == 3:
            todo_controller.set_todo_undone(index)
            break
        elif chosen == 0:
            break
        else:
            view.invalid_input()

def update_todos():
    view.update_todos()
    todo_controller.print_todos()
    view.choose_todo()

    while True:
        chosen_todo = user_input.return_int()
        if 1 <= chosen_todo <= todo_controller.number_of_todos():
            what_to_update(chosen_todo)
            break
        elif chosen_todo == 0:
            break
        else:
            view.invalid_input()

def delete_todos():
    view.delete_todos()
    todo_controller.print_todos()
    view.choose_todo_delete()

    while True:
        chosen_todo = user_input.return_int()
        if 1 <= chosen_todo <= todo_controller.number_of_todos():
            todo_controller.delete_specific_todo(chosen_todo)
            break
        elif chosen_todo == 0:
            break
        else:
            view.invalid_input()

def sub_menus(choice):
    if choice in '1':
        see_all_todos()
    elif choice in '2':
        todo_controller.create_todo()
    elif choice in '3':
        update_todos()
    elif choice in '4':
        delete_todos()
    else:
        view.wrong_message()

def menu_choice():
    choice = user_input.return_str()
    if choice in '1234':
        sub_menus(choice)
        return True
    elif choice in '5':
        view.bye_message()
        return False
    else:
        view.invalid_input()

    return True

# todo_controller.developer_mode()
todo_controller.read_from_database()

run_program = True

while run_program:
    view.welcome_message()
    view.main_menu()
    run_program = menu_choice()

todo_controller.save_to_database()


""" Display url using the default browser.
    by frost (passion-xbmc.org)
"""

import sys
import webbrowser
from traceback import print_exc

import xbmc
from xbmcaddon import Addon

Addon = Addon( sys.argv[ 1 ] )

def notification( header="", message="", sleep=5000, icon=Addon.getAddonInfo( "icon" ) ):
    """ Will display a notification dialog with the specified header and message,
        in addition you can set the length of time it displays in milliseconds and a icon image.
    """
    xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i,%s)" % ( header, message, sleep, icon ) )

def launchUrl( url ):
    try: webbrowser.open( url )
    except: print_exc()

def Main():
    try:
        url = sys.argv[ 2 ]
        # notify user
        notification( Addon.getAddonInfo( "name" ), url )
        # launch url
        launchUrl( url )
    except:
        print_exc()

if ( __name__ == "__main__" ):
    #print sys.argv
    Main()


import random
import sys
import math
import time
import copy
from mpi4py import MPI
import numpy
import itertools
from matplotlib import pyplot as plt

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
stat = MPI.Status()

# Initialize Grid and Generation
prob = 0.7
COLS = 400
ROWS_TOTAL = 198
generations = 20
ROWS = ROWS_TOTAL//size+2

#==== init first array
N=numpy.random.binomial(1,prob,size=(ROWS+2)*COLS)
M=numpy.reshape(N,(ROWS+2,COLS))

M[0,:] = 0
M[ROWS+1,:] = 0
M[:,0] = 0
M[:,COLS-1] = 0

initM = numpy.copy(M)
print(initM)
print("First Generation")

#plt.imshow(initM, interpolation='nearest')
#plt.show()

#==== init first array

if size > ROWS:
    print("Not enough ROWS")
    exit()

# MPI core functions
def msgUp(subGrid):
	# Sends and Recvs rows with (Rank+1)%size for cylindricaly
    comm.send(subGrid[ROWS-2],dest=(rank+1)%size)
    subGrid[ROWS-1]=comm.recv(source=(rank+1)%size)
    return 0

def msgDn(subGrid):
	# Sends and Recvs rows with (Rank-1)%size for cylindrical
    comm.send(subGrid[1],dest=(rank-1)%size)
    subGrid[0] = comm.recv(source=(rank-1)%size)
    return 0

def computeGridPoints(M):
    intermediateM = numpy.copy(M)
    for ROWelem in range(1,ROWS+1):
        for COLelem in range(1,COLS-1):
            sum = ( M[ROWelem-1,COLelem-1]+M[ROWelem-1,COLelem]+M[ROWelem-1,COLelem+1]
                    +M[ROWelem,COLelem-1]+M[ROWelem,COLelem+1]
                    +M[ROWelem+1,COLelem-1]+M[ROWelem+1,COLelem]+M[ROWelem+1,COLelem+1] )
#               print(ROWelem," ",COLelem," ",sum)
            if M[ROWelem,COLelem] == 1:
                if sum < 2:
                        intermediateM[ROWelem,COLelem] = 0
                elif sum > 3:
                        intermediateM[ROWelem,COLelem] = 0
                else:
                        intermediateM[ROWelem,COLelem] = 1
                if M[ROWelem,COLelem] == 0:
                        if sum == 3:
                                intermediateM[ROWelem,COLelem] = 1
                        else:
                                intermediateM[ROWelem,COLelem] = 0
    M = numpy.copy(intermediateM)
    return M

def printf(format, *args):
    sys.stdout.write(format % args)

def showgraph(nx,ny,arr):
    for i in range(len(arr)):
        for j in range(nx-1):
            if arr[i][j] == 1:
                printf('\033[45m'"%d "'\033[0m',arr[i][j])
            else:
                printf('\033[43m'"%d "'\033[0m',arr[i][j])
        printf("\n")
    printf('\x1b[2J\x1b[H')
    time.sleep(1)

for step in range(generations):
    # Game of Life Role
    computeGridPoints(M)
    # cylindrical boundaries : no need (rank==0) and (rank==n-1)	conditions
    msgUp(M)
    msgDn(M)
    tempGrid=comm.gather(M[1:ROWS-1],root=0)

    if rank == 0:
        newGrid=list(itertools.chain.from_iterable(tempGrid))
        if step%5 ==0:
            print("-----------Generation:", step, "---------------")
            showgraph(COLS, ROWS, newGrid)


# -*- coding: utf-8 -*-
import datetime
from odoo import models, fields, api
"""
@miguel.cabrera

"""
class CoreGeneradorFolios(models.Model):
    _name = 'core_generador_folio';
    nombre_folio = fields.Char(string='Nombre del folio', required=True)
    prefijo = fields.Char(string='Prefijo', required=True,
                          help='Se se usará como parte fundamental en el folio generado')
    contador = fields.Integer(default=0)
    incrementar = fields.Integer(default=lambda self: 1)
    numero_zeros = fields.Integer(string='Número de ceros a la izquierda', default=0)
    formato_fecha = fields.Char(string='Ingrese el formato de la fecha si lo requiere',
                                help='Por ejemplo: %Y-%m-%d o %Y%m%d%H%%i%s')

    tipo_folio_id = fields.Many2one(
        'core_formato_folio',
        string='Formato del folio',
        inverse_name='formato',
        ondelete='set null'
    )

    # agregar el constrain de prefijo unico

    @api.multi
    def getFolio(self, par_prefijo_folio):
        coreFolio = self.env['core_generador_folio'].search([('prefijo','=', par_prefijo_folio)])
        folio = ""
        if coreFolio:
            contador_actual = coreFolio.contador + coreFolio.incrementar
            folio = self.crearFolioByFormato(coreFolio.tipo_folio_id.formato, coreFolio, contador_actual)
            coreFolio.write({'contador': contador_actual})
        return folio

    def crearFolioByFormato(self, par_formato, par_campos, contador_actual):
        folio_final = str(par_formato)
        fields_search = [
            'prefijo',
            'numero_zeros',
            'contador',
            'formato_fecha'
        ]
        for val in fields_search:
            if val in par_campos:
                key = par_campos[val]
                if val == 'contador':
                    key = str(contador_actual).zfill(par_campos.numero_zeros)
                elif val == 'formato_fecha' and key:
                    key = str(datetime.datetime.now().strftime(key))
                key = str(key)
                folio_final = folio_final.replace('{' + val + '}', key)
        return folio_final;

    def createGenericFolio(self, data):
        self.create(data)
        # print (data)
        return self.getFolio(data['prefijo'])


import subprocess
import sys
from helpers import command

def _safe_to_float(str, default):
    try:
        return float(str)
    except (ValueError, TypeError):
        return default

def _cache(input, opts, env):
    opts['-d'] = input
    opts['--cache_file'] = env.cache_path_gen.get(input)
    return (opts, run(build_command(env.vw_path, opts), env.logger))

def _cache_func(input):
    return _cache(input[0], input[1], input[2])

def _cache_multi(opts, env):
    input_files = env.txt_provider.get()
    inputs = list(map(lambda i: (i, opts, env), input_files))
    result = env.job_pool.map(_cache_func, inputs)
    return result

def _train(cache_file, opts, env):
    opts['--cache_file'] = cache_file
    opts['-f'] = env.model_path_gen.get(cache_file, opts)
    result = (opts, run(build_command(env.vw_path, opts), env.logger))
    return result

def _train_func(input):
    return _train(input[0], input[1], input[2])

def _train_multi(opts, env):
    cache_files = env.cache_provider.get()
    for c in cache_files:
        inputs = list(map(lambda o: (c, o, env), opts))
        result = env.job_pool.map(_train_func, inputs)
        opts = list(map(lambda r: r[0], result))
        for o in opts:
            o['-i'] = o['-f']
    return result

def _predict(cache_file, command_name, command, env):
    command['-p'] = env.pred_path_gen.get(cache_file, command_name)
    _train(cache_file, command, env)
    return command_name, command

def _predict_func(input):
    return _predict(input[0], input[1], input[2], input[3])

def _predict_multi(labeled_opts, env):
    cache_files = env.cache_provider.get()
    for c in cache_files:
        inputs = list(map(
            lambda lo: (c, lo[0], lo[1], env), labeled_opts.items()))
        labeled_opts = dict(env.job_pool.map(_predict_func, inputs))
        for k, v in labeled_opts.items():
            labeled_opts[k]['-i'] = v['-f']

def _parse_vw_output(txt):
    result = {}
    for line in txt.split('\n'):
        if '=' in line:
            index = line.find('=')
            key = line[0:index].strip()
            value = line[index + 1:].strip()
            result[key] = value
    return result

def run(command, logger):
    process = subprocess.Popen(
        command.split(),
        universal_newlines=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    output, error = process.communicate()
    logger.debug(command)
    return _parse_vw_output(error)

def build_command(path, opts):
    return ' '.join([path, command.to_commandline(opts)])

def cache(opts, env):
    _cache_multi(opts, env)
    command.generalize(opts)

def train(opts, env):
    if not isinstance(opts, list):
        opts = [opts]

    result = _train_multi(opts, env)
    for r in result:
        command.generalize(r[0])
    return list(map(lambda r: (r[0], _safe_to_float(r[1]['average loss'],
                sys.float_info.max)), result))

def predict(labeled_commands, env):
    if not isinstance(labeled_commands, dict):
        labeled_commands = {'Default', labeled_commands}

    _predict_multi(labeled_commands, env)
    for kv in labeled_commands.items():
        command.generalize(kv[1])

if __name__ == '__main__':
    multiprocessing.freeze_support()