#!/usr/bin/env python

import click
from .__meta__ import (__version__, __name__)
from jinja2 import (Environment, StrictUndefined)
from datetime import date
from os.path import (dirname, join, split)
from re import (match, compile as r)
import hjson

def __setup__():
    path = dirname(dirname(__file__))
    pattern = join(r"(.*)", r"lib", r"python\d\.\d", r"site-packages")
    is_static = match(pattern, path)
    if is_static:
        path = is_static.groups()[0]
    return (path, join(path, "etc"))

RE_VARIABLIZE = r(r"\s")
RE_PARSEDELTA = r(r"^(w|h)(\d+)(px|%)$")

def variablize(string):
    return RE_VARIABLIZE.sub("", string).lower()

def parsedelta(delta):
    if isinstance(delta, StrictUndefined):
        return ""

    match = RE_PARSEDELTA.match(delta)
    if not match:
        raise Exception("This is an invalid delta value.")

    prefix = match.groups()[0]
    value = match.groups()[1]
    suffix = match.groups()[2]

    if prefix == "w":
        return ('style="width: calc(100% - {}{})"').format(value, suffix)
    else:
        return ('style="height: calc(100% - {}{})"').format(value, suffix)

MODULE_LOC, CONFIG_LOC = __setup__()
CONFIG_EXT = ".hjson"
HTML_EXT = ".html"

JENV = Environment(undefined=StrictUndefined)
JENV.filters["min"] = JENV.filters.get("min", min)
JENV.filters["max"] = JENV.filters.get("max", max)
JENV.filters["variablize"] = variablize
JENV.filters["parsedelta"] = parsedelta

@click.group()
@click.version_option(version=__version__, prog_name=__name__)
def Tabler():
    pass

@click.command()
@click.option("--out", type=click.Path(file_okay=True),
              prompt="Enter desired configuration path/filename")
def new(**kwargs):
    # Standardizing output path extension
    odir, ofile = split(kwargs.get("out"))
    pattern = join(r"^([^\.]*)(\..*)?$")
    ofile = match(pattern, ofile).groups()[0] + CONFIG_EXT
    ofilename = join(odir, ofile)

    # Generate render args
    render_args = {
        "date": date.today().strftime("%D"),
        "version": __version__,
    }

    # Read in raw hjson template
    with open(join(CONFIG_LOC, "tabler", "template.hjson.j2")) as tf:
        tmp = tf.read()

    # Render hjson template
    tmp = JENV.from_string(tmp)
    tmp = tmp.render(**render_args)

    # Write out hjson template
    with open(ofilename, "w") as tf:
        tf.write(tmp)

    print("Configuration file", ofilename, "has been created.")

@click.command()
@click.option("--in", type=click.Path(exists=True, file_okay=True),
              prompt="Enter desired configuration path/filename")
@click.option("--out", type=click.Path(file_okay=True), default=None)
def generate(**kwargs):
    # Standardizing input path extension
    idir, ifile = split(kwargs.get("in"))
    pattern = join(r"^([^\.]*)(\..*)?$")
    ifilebase = match(pattern, ifile).groups()[0]
    ifile = ifilebase + CONFIG_EXT
    ifilename = join(idir, ifile)

    # Standardizing output path extension
    if kwargs.get("out") is None:
        ofile = ifilebase + HTML_EXT
        ofilename = join(idir, ofile)
    else:
        odir, ofile = split(kwargs.get("out"))
        pattern = join(r"^([^\.]*)(\..*)?$")
        ofile = match(pattern, ofile).groups()[0] + HTML_EXT
        ofilename = join(odir, ofile)

    # Generate render args by reading in hjson file
    with open(ifilename) as tf:
        render_args = hjson.load(tf)

    # Sort sponsors alphabetically
    def sortkey(sponsor):
        return sponsor["name"].lower()

    for block in render_args["blocks"]:
        block["sponsors"] = sorted(block["sponsors"], key=sortkey)

    # Read in raw html template
    with open(join(CONFIG_LOC, "tabler", "template.html.j2")) as tf:
        tmp = tf.read()

    # Render html template
    tmp = JENV.from_string(tmp)
    tmp = tmp.render(**render_args)

    # Write out html template
    with open(ofilename, "w") as tf:
        tf.write(tmp)

    print("Table file", ofilename, "has been created.")

Tabler.add_command(new)
Tabler.add_command(generate)


import gobject
import gtk
import cairo

def draw_round_rect(context,x,y,w,h,r):
	# Copiado de http://www.steveanddebs.org/PyCairoDemo/
	# "Draw a rounded rectangle"
	#   A****BQ
	#  H      C
	#  *      *
	#  G      D
	#   F****E

	context.move_to(x+r,y)                      # Move to A
	context.line_to(x+w-r,y)                    # Straight line to B
	context.curve_to(x+w,y,x+w,y,x+w,y+r)       # Curve to C, Control points are both at Q
	context.line_to(x+w,y+h-r)                  # Move to D
	context.curve_to(x+w,y+h,x+w,y+h,x+w-r,y+h) # Curve to E
	context.line_to(x+r,y+h)                    # Line to F
	context.curve_to(x,y+h,x,y+h,x,y+h-r)       # Curve to G
	context.line_to(x,y+r)                      # Line to H
	context.curve_to(x,y,x,y,x+r,y)             # Curve to A
	return


from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import get_template
from django.shortcuts import render, redirect

from .models import Word
from .forms import WordCreateForm

def index(request):
    word_list = Word.objects.order_by('-timestamp')
    template = get_template('word/index.html')
    context = {
        'word_list': word_list,
    }
    return HttpResponse(template.render(context, request))

def create(request):
    if request.method == "POST":
        form = WordCreateForm(request.POST)
        if form.is_valid():
            word = form.save(commit=False)
            word.save()
            return index(request)
    else:
        form = WordCreateForm()
    return render(request, 'word/create.html', {'form': form})


def file_list(file_name):
    file = open(file_name, 'r', encoding='utf-8')
    newfile = file.read()
    file.close()
    newfile = newfile.split('\n')
    for line in range(len(newfile)):
        newfile[line] = newfile[line].split('|')
        line += 1

    return newfile


from lettuce import step, world
from src.krasn.data import DataSet
from src.krasn.error import get_classification_error
import numpy as np

################################################################################
#Common#########################################################################
################################################################################
@step('I have classifier which always return (\d+)')
def have_classifier_always_return_same(step, val):
    def classifier(row):
        return int(val)
    world.classifier = classifier

@step("I try to calculate error")
def try_to_calc_error(step):
    world.was_exception = False
    try:
        world.error = get_classification_error(world.classifier, world.data_set)
    except Exception:
        world.was_exception = True

################################################################################
#Error for empty data set#######################################################
################################################################################
@step("I have empty data set")
def have_empty_data_set(step):
    world.data_set = DataSet(
        n_features = 10,
        n_samples = 0,
        data = [],
        target = [],
        target_names = [0],
        feature_class_names = {},
        feature_names = [f for f in xrange(10)],
        row_weights = [1] *10
    )

@step("I got en exception")
def got_exception(step):
    assert world.was_exception, "was exception"

################################################################################
#Error for data set#############################################################
################################################################################
@step("I have data set with labels \[(\d+), (\d+), (\d+), (\d+)\]")
def have_data_set_with_labels(step, a, b, c, d):
    a, b, c, d = int(a), int(b), int(c), int(d)
    world.data_set = DataSet(
        n_features = 10,
        n_samples = 4,
        data = np.empty((10, 4)),
        target = [a, b, c, d],
        target_names = [a, b, c, d],
        feature_class_names = {},
        feature_names = [f for f in xrange(10)],
        row_weights = [1] *10
    )

@step("I got error = (\d+\.\d+)")
def i_got_error(step, error):
    assert world.error == float(error), "correct classification error"


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

import os
import sys
import time
import twitter
import secret

def main():
    dic = secret.drvtv_dict
    api = twitter.Api(
            consumer_key = dic["consumer_key"],
            consumer_secret = dic["consumer_secret"],
            access_token_key = dic["access_token_key"],
            access_token_secret = dic["access_token_secret"]
            )

    followers = api.GetFollowers()
    fp = open("followers_new.txt", "w")
    for follower in followers:
        fp.write(follower.name + "(@" + follower.screen_name + ")\n")
    fp.close()

if __name__ == "__main__":
  main()


from math import *
from kge import *

# Keep python scripts write only?

physics = 0

def create():
	owner.scheduleUpdate(tick)
	global physics
	physics = owner.getState("physics")

def tick():
	left = kge.input.isPressing(kge.input.LEFT)
	right = kge.input.isPressing(kge.input.RIGHT)

	if left ^ right:
		vx = physics.velocityX
		mv = kge.time.dt * 20.0
		if left:
			physics.velocityX = max(-5.0, vx - mv)
		else:
			physics.velocityX = min(5.0, vx + mv)

	if (kge.input.didPress(kge.input.SPACE)):
		kge.physics.gravityY = -kge.physics.gravityY

def updatePos():
	owner.interpolate({
				'start' : (transform.x, transform.y),
				'end' : (game.x, game.y),
				'duration' : 0.25,
				'callback': setPos
			})

def setPos(x, y):
	transform.x = x
	transform.y = y


"""
Sorting Algorithms

"""

#Print function to print arrays

def printArr(array, sort_name):
    print("")
    print("Sorted by ", sort_name)
    for x in array:
        print(x, end=", ")

"""
Heap Sort
    -Look at the array as a Heap
    -convert the Heap to a max heap
    -Repeatedly:
        - switch the first and last element
        - remove the last element
        - reduce length of array by one
        - convert to max heap

    Complexity: n log(n) : Converting into max heap takes log(n) time - and we do this 'n' times.
    In place sort
    Not a stable sort - duplicates order is not preserved
"""

def maxheapify(array, start_node, l):
    #max heapify procedure
    #parent node should be largest node
    largest = start_node

    #left_child
    l_c = 2*start_node + 1

    #right_child
    r_c = 2*start_node + 2

    #compare

    if l_c < l and array[largest] < array[l_c]:
        largest = l_c

    if r_c < l and array[largest] < array[r_c]:
        largest = r_c

    if largest != start_node:
        array[largest], array[start_node] = array[start_node], array[largest]
        maxheapify(array, largest, l)

def heap_sort(array):

    #length of the array
    l = len(array)

    #last non leaf node
    start_index = int(l/2) - 1

    #convert the array to a max heap
    #start from last non leaf node and go up to the root
    for i in range(start_index, -1, -1):
        #maxheapify
        maxheapify(array, i, l)

    #switch first and last
    #reduce length by one
    #max heapify starting from root
    #repeat from the switch
    for n in range(l-1, 0, -1):
        array[n], array[0] = array[0], array[n]
        #max heapify on root with length = n
        maxheapify(array, 0, n)

    return

input_array = [22, 66, 94, 71, 59, 17, 4, 103]
heap_sort(input_array)
printArr(input_array, "Heap Sort")

"""
Quicksort

    - We select a pivot
    - we move all elements less than the pivot to the left
    - we keep all elements greater than the pivot to the right
    - then the repeat this process on the left and right arrays - excluding the pivot

    Complexity: n log n - best case - n^2 worst case (if we select the largest element as the pivot everytime)
    In place sort
    Stable sort - No
"""

def pivotFunction(array, start, end):

    pivot = end

    #last swapped element
    s = start - 1

    for i in range(start, pivot):
        if array[i] < array[pivot]:
            s += 1
            array[s], array[i] = array[i], array[s]

    #bring pivot to split point
    array[s+1], array[pivot] = array[pivot], array[s+1]

    return s+1

def quickSort(array, start, end):
    if start < end:

        #pivot function
        #give us the pivot index
        p = pivotFunction(array, start, end)

        #recursive call on the subarrays formed on either side of the pivot
        quickSort(array, start, p-1)
        quickSort(array, p+1, end)

    return

input_array = [22, 66, 94, 71, 59, 17, 4, 103]
length = len(input_array) - 1
quickSort(input_array, 0, length)
printArr(input_array, "Quick Sort")

"""

Insertion Sort

 - Split the given array into two arrays - sorted array and unsorted array
 - You iterate over each element
 - And find the right place to insert it in the sorted array

 Complexity - n^2 - best case is n
 In place sort
 Stable - yes

"""

def insertionSort(array):

    l = len(array)

    for i in range(1,l):
        if array[i] < array[i-1]:
            j = i
            while array[j] < array[j-1] and j > 0:
                array[j], array[j-1] = array[j-1], array[j]
                j -= 1

    return

input_array = [22, 66, 94, 71, 59, 17, 4, 103]
insertionSort(input_array)
printArr(input_array, "Insertion Sort")

"""
Merge Sort

 - First divide the array into it's smallest elements
 - Sort the elements into place on the way up

 Complexity - nlog(n)
 In place sort - Nope
 Stable sort - yes
"""

def mergeSort(array):
    if len(array) > 1:

        l = len(array)
        #find midpoint
        m = int(l/2)

        #create the two subarrays
        l_array = array[0:m]
        r_array = array[m:]

        #recurse on the two subarrays
        mergeSort(l_array)
        mergeSort(r_array)

        i = j = k = 0
        #iterate over each of the two sub arrays

        while i < len(l_array) and j < len(r_array):
            if l_array[i] < r_array[j]:
                array[k] = l_array[i]
                i += 1
                k += 1
            else:
                array[k] = r_array[j]
                j += 1
                k += 1

        while i < len(l_array):
            array[k] = l_array[i]
            i += 1
            k += 1

        while j < len(r_array):
            array[k] = r_array[j]
            j += 1
            k += 1

        return array

input_array = [22, 66, 94, 71, 59, 17, 4, 103]
output_array = mergeSort(input_array)
printArr(output_array, "Merge Sort")

"""
Selection Sort
    - splits the array into two subarrays - sorted array and unsorted array
    - Iterate over each position
    - for each position - we select the smallest element in the unsorted array and swap it with the element in the current position

    Complexity - n^2
    Inplace sort - yes
    Stable Sort - yes
"""

def selectionSort(array):

    #length of the array
    l = len(array)

    for i in range(l):
        smallest = i
        for j in range(i+1,l):
            if array[j] < array[smallest]:
                array[j], array[smallest] = array[smallest], array[j]

    return

input_array = [22, 66, 94, 71, 59, 17, 4, 103]
selectionSort(input_array)
printArr(input_array, "Selection Sort")

"""

Counting Sort

   - we are dealing with values in a particular range
   - Count the number of occurances of each value in the array
   - Store those values in a count array
   - Use those values to put the elements in the sorted array

   - Complexity: linear - n - only works for values in a particular range
   - Not an in place sort
   - It is a stable sort

"""

def countingSort(array, key):

    l = len(array)

    #a count array
    count_array = [0 for _ in range(key)]

    #the sorted array
    sorted_array = [0 for _ in range(l)]

    #count the number of occurances of each elements in the array
    for x in array:
        count_array[x] += 1

    #we need to do the addition operation on the counts
    for i in range(1, key):
        count_array[i] = count_array[i] + count_array[i-1]

    #we need to place the elements into the sorted array based on their count value
    for x in array:
        sorted_array[count_array[x]-1] = x
        count_array[x] -= 1

    return sorted_array

input_array = [9, 6, 3, 3, 4, 9, 9, 7, 6, 4, 4]
output_array = countingSort(input_array, 10)
printArr(output_array, "Counting Sort")

"""
BubbleSort

 - We iterate through the array
 - we compare adjacent elements
 - if left element is less than right element - we swap them - end result is - largest element moves to last place
 - we repeat this for reducing lengths

 Complexity: n^2
 Stable - yes
 In place sort
"""

def bubbleSort(array):

    l = len(array)

    for n in range(l,0,-1):
        for i in range(1,n):
            if array[i] < array[i-1]:
                array[i], array[i-1] = array[i-1], array[i]

    return

input_array = [22, 66, 94, 71, 59, 17, 4, 103]
bubbleSort(input_array)
printArr(input_array, "Bubble Sort")

"""
Radix Sort

    - here we sort numbers based on their decimal places
    - start from units place and go on till the largest decimal place of the largest number in the array

    Complexity - linear
    Very slow - it is type of mechanical sort
    not an in place sort
    not a stable sort

"""

def countSort(array, exp):

    l = len(array)

    count_array = [0 for _ in range(10)]

    sorted_array = [0 for _ in range(l)]

    #count the elements
    for x in array:
        index = int(x/exp)
        count_array[index%10] += 1

    #increment count value
    for i in range(1, 10):
        count_array[i] = count_array[i] + count_array[i-1]

    #place the elements into the sorted array base on the count value:

    for x in reversed(array):
        index = int(x/exp)
        sorted_array[count_array[index%10]-1] = x
        count_array[index%10] -= 1

    return sorted_array

def radixSort(array):

    l = len(array)

    #largest value in the array
    largest = max(array) #thankyou python

    exp = 1

    while int(largest/exp) > 0:
        array = countSort(array, exp)
        exp *= 10

    return array

input_array = [22, 66, 94, 71, 59, 17, 4, 103]
sortedArr = radixSort(input_array)
printArr(sortedArr, "Radix Sort")


from django.conf.urls import patterns, include, url

from django.contrib import admin
from blog import settings
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'blog.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^weblog/', include('zinnia.urls', namespace='zinnia')),
    url(r'^comments/', include('django.contrib.comments.urls')),
    url(r'^weixin/help$', 'weixin.views.help'),
    url(r'^weixin/', 'weixin.views.serv'),
    url(r'^store/version', 'store.views.version'),
    url(r'^store/download', 'store.views.download'),
    url(r'^store/', 'store.views.index'),
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root':settings.MEDIA_ROOT,}),
)


"""
Polymer
=======

#. :class:`.Linear`

"""

import logging
import numpy as np

from .topology_graph import TopologyGraph, Vertex, Edge

logger = logging.getLogger(__name__)

class _LinearVertex(Vertex):
    """
    Represents a vertex in the middle of a linear polymer chain.

    Attributes
    ----------
    id : :class:`int`
        The id of the vertex. This should be its index in
        :attr:`TopologyGraph.vertices`.

    edges : :class:`list` of :class:`.Edge`
        The edges the :class:`Vertex` is connected to.

    """

    def __init__(self, x, y, z, orientation):
        """
        Initialize a :class:`.LinearVertex`.

        Parameters
        ----------
        x : :class:`float`
            The x coordinate.

        y : :class:`float`
            The y coordinate.

        z : :class:`float`
            The z coordinate.

        orientation : :class:`float`
            Can be any number from ``0`` to ``1``, both inclusive. It
            specifies the probability the building block placed on the
            vertex will have its orientation along the chain flipped.

        """

        self._orientation = orientation
        super().__init__(x, y, z)

    def clone(self, clear_edges=False):
        """
        Return a clone.

        Parameters
        ----------
        clear_edges : :class:`bool`, optional
            If ``True`` the :attr:`edges` attribute of the clone will
            be empty.

        Returns
        -------
        :class:`Vertex`
            The clone.

        """

        clone = super().clone(clear_edges)
        clone._orientation = self._orientation
        return clone

    def place_building_block(self, building_block):
        """
        Place `building_block` on the :class:`.Vertex`.

        `building_block` is placed such that its bonder-bonder
        direction vector is either parallel or anti-parallel to the
        polymer chain.

        Parameters
        ----------
        building_block : :class:`.Molecule`
            The building block molecule which is to be placed on the
            vertex.

        Returns
        -------
        :class:`numpy.nadarray`
            The position matrix of `building_block` after being
            placed.

        """

        if len(building_block.func_groups) > 2:
            logger.warning(
                'You are placing a building block which has more than '
                'two functional groups along the backbone of '
                'a Linear topology. You can remove extra functional '
                'groups from the func_groups attribute to remove '
                'this message.'
            )

        building_block.set_centroid(
            position=self._position,
            atom_ids=building_block.get_bonder_ids(fg_ids=(0, 1))
        )
        bonder_vector = next(
            building_block.get_bonder_direction_vectors(
                fg_ids=(0, 1)
            )
        )[-1]

        p = [1-self._orientation, self._orientation]
        direction = np.random.choice([1, -1], p=p)
        building_block.apply_rotation_between_vectors(
            start=bonder_vector,
            target=[direction, 0, 0],
            origin=self._position
        )
        return building_block.get_position_matrix()

    def assign_func_groups_to_edges(self, building_block):
        """
        Assign functional groups to edges.

        Each :class:`.FunctionalGroup` of the `building_block` needs
        to be associated with one of the :class:`.Edge` instances in
        :attr:`edges`.

        Parameters
        ----------
        building_block : :class:`.Molecule`
            The building block molecule which is needs to have
            functional groups assigned to edges.

        Returns
        -------
        :class:`dict`
            A mapping from the id of a functional group in
            `building_block` to the id of the edge in :attr:`edges` it
            is assigned to.

        """

        func_groups = building_block.func_groups
        fg1, fg2 = sorted(
            range(len(building_block.func_groups)),
            key=lambda fg_id: building_block.get_centroid(
                atom_ids=func_groups[fg_id].get_bonder_ids()
            )[0]
        )
        return {
            fg1: self.edges[0].id,
            fg2: self.edges[1].id
        }

    def __str__(self):
        x, y, z = self._position
        return (
            f'Vertex(id={self.id}, '
            f'position={[x, y, z]}, '
            f'orientation={self._orientation})'
        )

class _TerminalVertex(_LinearVertex):
    """
    Represents a vertex at the end of a polymer chain.

    Do not instantiate this class directly, use :class:`.HeadVertex` or
    :class:`.TailVertex` instead.

    Attributes
    ----------
    id : :class:`int`
        The id of the vertex. This should be its index in
        :attr:`TopologyGraph.vertices`.

    edges : :class:`list` of :class:`.Edge`
        The edges the :class:`Vertex` is connected to.

    """

    def place_building_block(self, building_block):
        """
        Place `building_block` on the :class:`.Vertex`.

        `building_block` is placed such that the centroid-centroid
        direction vector is always pointing away from the center of the
        chain, when `building_block` has only one
        :class:`.FunctionalGroup`.

        If the `building_block` has more than one
        :class:`.FunctionalGroup` then this method behaves in the same
        was as for :class:`.LinearVertex`.

        Parameters
        ----------
        building_block : :class:`.Molecule`
            The building block molecule which is to be placed on the
            vertex.

        Returns
        -------
        :class:`numpy.nadarray`
            The position matrix of `building_block` after being
            placed on the :class:`.Vertex`.
        """

        if len(building_block.func_groups) != 1:
            return super().place_building_block(building_block)

        building_block.set_centroid(
            position=self._position,
            atom_ids=building_block.get_bonder_ids(fg_ids=(0, )),
        )
        centroid_vector = (
            building_block.get_centroid_centroid_direction_vector()
        )
        building_block.apply_rotation_between_vectors(
            start=centroid_vector,
            # _cap_direction is defined by a subclass.
            target=[self._cap_direction, 0, 0],
            origin=self._position
        )
        return building_block.get_position_matrix()

    def assign_func_groups_to_edges(self, building_block):
        """
        Assign functional groups to edges.

        Each :class:`.FunctionalGroup` of the `building_block` needs
        to be associated with one of the :class:`.Edge` instances in
        :attr:`edges`.

        Parameters
        ----------
        building_block : :class:`.Molecule`
            The building block molecule which is needs to have
            functional groups assigned to edges.

        Returns
        -------
        :class:`dict`
            A mapping from the id of a functional group in
            `building_block` to the id of the edge in :attr:`edges` it
            is assigned to.

        Raises
        ------
        :class:`ValueError`
            If `building_block` does not have one or two functional
            groups.

        """

        if len(building_block.func_groups) == 2:
            func_groups = building_block.func_groups
            fgs = sorted(
                range(len(func_groups)),
                key=lambda fg_id: building_block.get_centroid(
                    atom_ids=func_groups[fg_id].get_bonder_ids()
                )[0]
            )
            fg_index = 0 if self._cap_direction == 1 else -1
            return {fgs[fg_index]: self.edges[0].id}

        elif len(building_block.func_groups) == 1:
            return {0: self.edges[0].id}

        else:
            raise ValueError(
                'The building block of a polymer '
                'must have 1 or 2 functional groups.'
            )

class _HeadVertex(_TerminalVertex):
    """
    Represents a vertex at the head of a polymer chain.

    Attributes
    ----------
    edges : :class:`list` of :class:`.Edge`
        The edges the :class:`Vertex` is connected to.

    """

    # The direction to use if the building block placed on the
    # vertex only has 1 FunctionalGroup.
    _cap_direction = -1

class _TailVertex(_TerminalVertex):
    """
    Represents a vertex at the tail of a polymer chain.

    Attributes
    ----------
    edges : :class:`list` of :class:`.Edge`
        The edges the :class:`Vertex` is connected to.

    """

    # The direction to use if the building block placed on the
    # vertex only has 1 FunctionalGroup.
    _cap_direction = 1

class Linear(TopologyGraph):
    """
    Represents linear polymer topology graphs.

    Attributes
    ----------
    vertices : :class:`tuple` of :class:`.Vertex`
        The vertices which make up the topology graph.

    edges : :class:`tuple` of :class:`.Edge`
        The edges which make up the topology graph.

    Examples
    --------
    Linear polymers require building blocks with functional groups

    .. code-block:: python

        import stk

        bb1 = stk.BuildingBlock('NCCN', ['amine'])
        bb2 = stk.BuildingBlock('O=CCC=O', ['aldehyde'])
        polymer = stk.ConstructedMolecule(
            building_blocks=[bb1, bb2],
            topology_graph=stk.polymer.Linear('AB', 12)
        )

    However building blocks with a single functional group can
    also be provided as capping units

    .. code-block: python

        bb3 = stk.BuildingBlock('CCN', ['amine'])
        polymer = stk.ConstructedMolecule(
            building_blocks=[bb1, bb2, bb3],
            topology_graph=stk.polymer.Linear('ABABC', 1)
        )

    """

    def __init__(
        self,
        repeating_unit,
        num_repeating_units,
        orientations=None,
        num_processes=1
    ):
        """
        Initialize a :class:`Linear` instance.

        Parameters
        ----------
        repeating_unit : :class:`str`
            A string specifying the repeating unit of the polymer.
            For example, ``'AB'`` or ``'ABB'``. Letters are assigned to
            building block molecules in the order they are passed to
            :meth:`.ConstructedMolecule.__init__`.

        num_repeating_units : :class:`int`
            The number of repeating units which are used to make the
            polymer.

        orientations : :class:`tuple` of :class:`float`
            For each character in the repeating unit, a value
            between ``0`` and ``1`` (both inclusive) must be given in
            a :class:`tuple`. It indicates the probability that each
            monomer will have its orientation along the chain flipped.
            If ``0`` then the monomer is guaranteed not to flip. If
            ``1`` it is guaranteed to flip. This allows the user to
            create head-to-head or head-to-tail chains, as well as
            chain with a preference for head-to-head or head-to-tail if
            a number between ``0`` and ``1`` is chosen. If ``None``
            then ``0`` is picked in all cases.

        num_processes : :class:`int`, optional
            The number of parallel processes to create during
            :meth:`construct`.

        """

        if orientations is None:
            orientations = tuple(
                0. for i in range(len(repeating_unit))
            )

        # Keep these for __repr__
        self._repeating_unit = repeating_unit
        self._orientations = orientations
        self._num_repeating_units = num_repeating_units

        head, *body, tail = orientations*num_repeating_units
        vertices = [_HeadVertex(0, 0, 0, head)]
        edges = []
        for i, orientation in enumerate(body, 1):
            v = _LinearVertex(
                x=i, y=0, z=0, orientation=orientation
            )
            vertices.append(v)
            edges.append(Edge(vertices[i-1], vertices[i]))

        vertices.append(
            _TailVertex(len(vertices), 0, 0, tail)
        )
        edges.append(Edge(vertices[-2], vertices[-1]))

        super().__init__(
            vertices=tuple(vertices),
            edges=tuple(edges),
            construction_stages=(),
            num_processes=num_processes
        )

    def assign_building_blocks_to_vertices(self, building_blocks):
        """
        Assign `building_blocks` to :attr:`vertices`.

        Parameters
        ----------
        building_blocks : :class:`list` of :class:`.Molecule`
            The :class:`.BuildingBlock` and
            :class:`ConstructedMolecule` instances which
            represent the building block molecules used for
            construction. Only one instance is present per building
            block molecule, even if multiples of that building block
            join up to form the :class:`ConstructedMolecule`.

        Returns
        -------
        :class:`dict`
            Maps the `building_blocks`, to the
            :class:`~.topologies.base.Vertex` objects in
            :attr:`vertices` they are placed on during construction.
            The :class:`dict` has the form

            .. code-block:: python

                building_block_vertices = {
                    BuildingBlock(...): [Vertex(...), Vertex(...)],
                    BuildingBlock(...): [
                        Vertex(...),
                        Vertex(...),
                        Vertex(...),
                    ]
                    ConstructedMolecule(...): [Vertex(...)]
                }

        """

        polymer = self._repeating_unit*self._num_repeating_units
        bb_map = {
            letter: bb for letter, bb in zip(polymer, building_blocks)
        }
        building_block_vertices = {}
        for letter, vertex in zip(polymer, self.vertices):
            bb = bb_map[letter]
            building_block_vertices[bb] = (
                building_block_vertices.get(bb, [])
            )
            building_block_vertices[bb].append(vertex)
        return building_block_vertices

    def _get_scale(self, mol):
        """
        Get the scale used for the positions of :attr:`vertices`.

        Parameters
        ----------
        mol : :class:`.ConstructedMolecule`
            The molecule being constructed.

        Returns
        -------
        :class:`float` or :class:`list` of :class:`float`
            The value by which the position of each :class:`Vertex` is
            scaled. Can be a single number if all axes are scaled by
            the same amount or a :class:`list` of three numbers if
            each axis is scaled by a different value.

        """

        return max(
            bb.get_maximum_diameter()
            for bb in mol.building_block_vertices
        )

    def __repr__(self):
        return (
            f'polymer.Linear({self._repeating_unit!r}, '
            f'{self._num_repeating_units!r}, '
            f'{self._orientations!r})'
        )


# -*- coding: utf-8 -*-
"""
Created on Sun Oct 23 13:30:27 2016

@author: Lorenzo
"""
import pandas as pd
import numpy as np

start_date='2016-05-31 05:23:00'
end_date='2016-08-02 18:18:00'
dates=pd.date_range(start_date,end_date,freq='1min' )

# empty dataframe
df1=pd.DataFrame(index=dates,columns=['Open','High', 'Low', 'Close', 'Volume'])
#df1=pd.DataFrame(index=dates)

dfup = pd.read_csv('forex/EURUSDup.csv',sep=',',header=None,
                 names=['Date', 'Time', 'Open','High', 'Low', 'Close', 'Volume'],
                 index_col='Date_Time', parse_dates=[[0, 1]], na_values=['nan'])
                     # date_parser=parse)

dfdown = pd.read_csv('forex/EURUSDdown.csv',sep=',',header=None,
                 names=['Date', 'Time', 'Open','High', 'Low', 'Close', 'Volume'],
                 index_col='Date_Time', parse_dates=[[0, 1]], na_values=['nan'])
                     # date_parser=parse)
#df.iloc[[2]]=np.nan

#df1.combine_first(dfup)
#dfup.combine_first(dfdown)

#df1.update(df[df1.isnull()==True])

#dfup.set_index('Date_Time', inplace=True)
#dfdown.set_index('Date_Time', inplace=True)
df2 = dfup.merge(dfdown.ix[:,dfdown.columns.difference(dfup.columns)], left_index=True, right_index=True, how="outer")
df2.update(dfdown[df2.isnull()==True])

# let's erase the columns we don't need
#del df['Tid']
#del df['Dealable']

# group every 15 minutes and create an OHLC bar
#grouped_data = df.resample('15Min', how='ohlc')


from __future__ import print_function
import sys
from flask import Flask, render_template, request, redirect
from flask.ext.uploads import UploadSet, configure_uploads, TEXT
from bokeh.embed import components
from bokeh.plotting import figure
from bokeh.charts import Histogram
from bokeh.charts import Bar
from bokeh.resources import INLINE
from bokeh.util.string import encode_utf8
import numpy as np
import quandl
from quandl.errors.quandl_error import NotFoundError
import pandas as pd

from chessfunctions import get_castling_move
from chessfunctions import get_moves
from chessfunctions import analyze_moves
from chessfunctions import read_player_games

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

app = Flask(__name__)
app.vars = {}

#flaskext.uploads.TEXT OR
# ?? check http://pythonhosted.org/Flask-Uploads/
#app.config['UPLOADED_USERPGNGAMES_DEST'] = 'static/games'
app.config['UPLOADED_USERPGNGAMES_DEST'] = '/home/vagrant/jim-day-8/static/games'
userpgngames = UploadSet('userpgngames', ('pgn',))

#UPLOADED_FILES_ALLOW PGN?
configure_uploads(app, (userpgngames,))

@app.route('/index',methods=['GET','POST'])
#def main():
#  return redirect('/index')
def index():
    #show the query html if this is the landing page
    if request.method == 'GET':
        return render_template('index.html')
    else:
        #request was a POST, so grab the query and plot
        app.yourstock = request.form['stock_query']
        return redirect('/data')

@app.route('/upload', methods=['GET','POST'])
def upload():
    if request.method == 'POST' and 'games' in request.files: #games here is same as next line and same as name in upload.html
        app.filename = userpgngames.save(request.files['games'])
#        return filename
        return redirect('/results')
    return render_template('upload.html')

def create_hist(the_data,current_feature_name, bins):
    p = Histogram(the_data, current_feature_name, title=current_feature_name, #color='Species',
         bins=bins, legend='top_right', width=600, height=400)

    # Set the x axis label
    p.xaxis.axis_label = current_feature_name

    # Set the y axis label
    p.yaxis.axis_label = 'Count'
    return p

@app.route('/results',methods=['GET','POST'])
def results():
    print (type(userpgngames))
    print (userpgngames)
    print (app.filename)
#IOError: File JWFgames_18.pgn does not exist
    hist_1600 = pd.read_csv("static/games/castling_1600_1699.txt",names=["rating","side","move_num"])

    eprint("static/games/"+app.filename)
    playersDF = read_player_games("static/games/"+app.filename)
#    players_games = pd("static/games/"+app.filename) #TODO Use this for the player's games

#    eprint(playersDF.info())
#    eprint(playersDF)

    #dataset should be move_num, relative frequency, and another categorical variable ("1600", or "player")
    player_name = playersDF["White"].value_counts().index[0]

    hist_1600["count"]=1
    hist_1600["ID"]="1600"

    castling_hist = hist_1600[["move_num","count","ID"]]
    eprint(castling_hist.info())
    eprint(castling_hist.describe())
    for index,row in playersDF.iterrows():
        if row["White"]==player_name:
            tmp = pd.Series([int(row["WhiteCastledMoveNum"]),1,player_name], index=["move_num","count","ID"])
            castling_hist = castling_hist.append(tmp,ignore_index=True)
        else:
            tmp = pd.Series([int(row["BlackCastledMoveNum"]),1,player_name], index=["move_num","count","ID"])
            castling_hist = castling_hist.append(tmp,ignore_index=True)

    eprint(castling_hist.info())
    eprint(castling_hist.describe())

# ID for player not needed anymore since we filter that out above
#    castling_hist_to_show = castling_hist[((castling_hist["ID"]==player_name)  | (castling_hist["ID"]=="1600")) &
    castling_hist_to_show = castling_hist[((castling_hist["ID"]==player_name)  | (castling_hist["ID"]=="1600")) &
        (castling_hist["move_num"]>0) & (castling_hist["move_num"]<=30)]
    adjust_dict ={}
    ID_counts =  castling_hist_to_show["ID"].value_counts()

    eprint(castling_hist_to_show)
    #this line gives a warning
    castling_hist_to_show['weighted'] = castling_hist_to_show.apply(lambda row: row['count']*100.0/ ID_counts[row['ID']], axis=1)

    #for each unique value in ID
    #find weighting amoutn, i.e. not 1, but 1/N
    #create another column like count_weighted and
    plot_hist_1600 = Bar(castling_hist_to_show, "move_num","weighted", group='ID', bar_width=0.5, color='ID', palette=["red", "blue"],fill_alpha=0.4)
    plot_hist_1600.legend.location = "top_right"
    plot_hist_1600.legend.click_policy="hide"
    plot_hist_1600.xaxis.axis_label = 'Castling Move Number'
    plot_hist_1600.yaxis.axis_label = 'Percent of Games'

#    plot_hist_1600_area = Area(
#hack for bokeh bug
#http://stackoverflow.com/questions/34137875/change-bar-width-with-a-python-bokeh-grouped-bar-chart
    for r in plot_hist_1600.renderers:
        try:
#            eprint(type(r.glyph))
            r.glyph.width = 1.0
#            eprint(r.glyph.x) #this is just a str of 'x'??
        except AttributeError:
            pass

    script, div = components(plot_hist_1600)

    # grab the static resources
    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    html = render_template(
        'results.html',
#         filename=userpgngames
#         filename=hist_1600,
        plot_script=script,
        plot_div=div,
        js_resources=js_resources,
        css_resources=css_resources,
    )
    return encode_utf8(html)
#@app.route('/data',methods=['GET','POST'])
#def data():

#    quandl_query = "https://www.quandl.com/api/v3/datasets/EOD/"+app.yourstock+".json?rows=30&order=desc&column_index=4&api_key=" + quandl.ApiConfig.api_key
    quandl_query = "WIKI/"+app.yourstock
    #quandl query returns Pandas; get the last 30 days
    try:
        app.stock_data = quandl.get(quandl_query,rows=30)
    except:
        return redirect('/index')

    # chart defaults
    color = '#FF0000'
    start = 0
    finish = 10

    x = list(range(start, finish + 1))
    fig = figure(x_axis_type="datetime", title="Recent "+app.yourstock+" Closing Prices")
    #plot appropriate dataframe columns
    fig.line(source=app.stock_data,x="Date", y="Close")

    # grab the static resources
    js_resources = INLINE.render_js()
    css_resources = INLINE.render_css()

    # render template
    script, div = components(fig)
    html = render_template(
        'data.html',
        plot_script=script,
        plot_div=div,
        js_resources=js_resources,
        css_resources=css_resources,
    )
    return encode_utf8(html)

if __name__ == '__main__':
# testing
    app.run(port=33507,host='0.0.0.0',debug=True)

# Heroku
#    port = int(os.environ.get("PORT", 5000))
#    app.run(host='0.0.0.0', port=port)


#! python3
# -*- encoding: utf-8 -*-
'''
Current module: rman.app.httpcase.views.testapi

Rough version history:
v1.0    Original version to use

********************************************************************
    @AUTHOR:  Administrator-Bruce Luo(罗科峰)
    MAIL:     luokefeng@163.com
    RCS:      rman.app.httpcase.views.testapi,  v1.0 2019年7月5日
    FROM:   2019年7月5日
********************************************************************
======================================================================

Provide a function for the automation test

'''
import datetime, json
from flask import request, jsonify
from flask_login import login_required
from flask.views import MethodView

from rman.app import APP_ENV
from rman.app.routes.api_0_0.httpcase import httpcase
from rman.app.routes.api_0_0.httpcase.models import db,HttpCaseQuerys, HttpCase
from rman.app.routes.api_0_0.manager.models import TestApis, TestSuiteApiRelation, TestSuites

def get_result(result, status=True, message="success"):
    return {"status": status, "message": message, "result": result}

class TestApiView(MethodView):

    def get(self):
        #/api?pj_id=xx
        param = dict(request.args.items())
        _query_project = HttpCaseQuerys.t_project()
        _query_api = HttpCaseQuerys.j_api_hcase()

        project_id = param.get("pj_id")
        if not project_id:
            return jsonify(get_result("", status = False, message = 'Parameter [pj_id] should not be null.'))

        proj_data = _query_project.filter_by(id = project_id).first()
        if not proj_data:
            return jsonify(get_result("", status = False, message = 'Testproject [id={0}] not exist.'.format(project_id)))

        result = {
            "pj_id": project_id,
            "pj_name": proj_data.name,
            "pj_module_name": proj_data.module,
            "tset_name": "administrator",
            "tset_responsible": "administrator",
            "tset_tester": "administrator",
            "apis": []
        }
        api_datas = _query_api.filter(TestApis.project_id == project_id).all()

        for pg in api_datas:
            api_data = pg.TestApis
            hc_data = pg.HttpCase

            _api = {i: json.loads(getattr(hc_data, i)) for i in ("glob_var", "glob_regx", "headers", "body", "files", "pre_command", "post_command", "verify")}
            _api["id"] = api_data.id
            _api["api_def"] = api_data.api_def
            _api["url"] = hc_data.url
            _api["method"] = hc_data.method

            result["apis"].append(_api)

        return jsonify(get_result(result, message = "Query all data  success."))

    def post(self):
        #/api?pj_id=xx
        param = dict(request.args.items())
        j_param = request.json if request.data else request.form.to_dict()
        now = datetime.datetime.now()

        _query_api = HttpCaseQuerys.t_api()
        _query_project = HttpCaseQuerys.t_project()

        project_id = param.get("pj_id")
        if not _query_project.filter_by(id = project_id).first():
            return jsonify(get_result("", status = False, message = 'Testproject [id={0}] not exist.'.format(project_id)))

        api_def= j_param.get("api_def")
        url = j_param.get("url", "")
        method = j_param.get("method", "")
        if not api_def or not url or not method:
            return jsonify(get_result("", status = False, message = 'Parameter [api_def, url, method] should not be null.'))

        api_def_data = _query_api.filter_by(project_id = project_id, api_def = api_def).first()
        if api_def_data:
            return jsonify(get_result("", status = False, message = 'Testapi [api_def={0}] already exists in Testproject[id={1}].'.format(api_def, project_id)))

        hcase_kwargs = {}
        _ = [hcase_kwargs.update({i: json.dumps(j_param.get(i,{}))}) for i in ("glob_var", "glob_regx", "headers", "body", "files")]
        _ = [hcase_kwargs.update({i: json.dumps(j_param.get(i,[]))}) for i in ("pre_command", "post_command", "verify")]
        hcase_kwargs.update({"url":url, "method":method, "create_time": now, "update_time":now})
        _httpcase = HttpCase(**hcase_kwargs)
        db.session.add(_httpcase)
        db.session.flush()

        tapi_kwargs = {
            "api_def": api_def,
            "call_manunal_id": _httpcase.id,
            "project_id": project_id,
            "create_time": now,
            "update_time":now
        }
        _api = TestApis (**tapi_kwargs)
        db.session.add(_api)
        db.session.commit()

        return jsonify(get_result("", message = "add success."))

    def put(self):
        #/api?tapi_id=xx
        param = dict(request.args.items())
        j_param = request.json if request.data else request.form.to_dict()
        now = datetime.datetime.now()

        _query_api = HttpCaseQuerys.t_api()
        _query_hcase = HttpCaseQuerys.t_hcase()

        tapi_id = param.get("tapi_id")
        tapi_data = _query_api.filter_by(id = tapi_id).first()
        if not tapi_data:
            return jsonify(get_result("", status = False, message = 'TestApi not exist with parameter [tapi_id={0}].'.format(tapi_id)))

        hcase_kwargs = {}
        api_def= j_param.get("api_def")
        url = j_param.get("url", "")
        method = j_param.get("method", "")
        if not api_def or not url or not method:
            return jsonify(get_result("", status = False, message = 'Parameter [api_def, url, method] should not be null.'))

        tapi_data.api_def = api_def
        tapi_data.update_time = now
        _ = [hcase_kwargs.update({i: json.dumps(j_param.get(i,{}))}) for i in ("glob_var", "glob_regx", "headers", "body", "files")]
        _ = [hcase_kwargs.update({i: json.dumps(j_param.get(i,[]))}) for i in ("pre_command", "post_command", "verify")]
        hcase_kwargs.update({"url":url, "method":method, "update_time":now})

        tcase_data = _query_hcase.filter_by(id=tapi_data.call_manunal_id).first()
        _ = [setattr(tcase_data, k, v) for k,v in hcase_kwargs.items()]
        db.session.flush()
        db.session.commit()

        return jsonify(get_result("", message = "update success."))

    def delete(self):
        # /api?tapi_id=xx
        param = dict(request.args.items())

        _query_tapi = HttpCaseQuerys.t_api()
        _query_hcase = HttpCaseQuerys.t_hcase()

        tapi_id = param.get("tapi_id")

        tapi_data = _query_tapi.filter_by(id = tapi_id).first()
        if not tapi_data:
            return jsonify(get_result("", message = "delete success."))

        hcase_data = _query_hcase.filter_by(id = tapi_data.call_manunal_id).first()
        print(hcase_data)
        if hcase_data:
            db.session.delete(hcase_data)

        db.session.delete(tapi_data)
        db.session.commit()
        return jsonify(get_result("", message = "delete success."))

if APP_ENV == "production":
    _view = login_required(TestApiView.as_view('tapi_view_manager'))
else:
    _view = TestApiView.as_view('tapi_view_manager')

httpcase.add_url_rule('/api', view_func=_view)


'''
75. Sort Colors

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:

A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?
'''

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
#         Best solution:
#         zero , two = 0, len(nums)-1
#         tra = 0
#         while tra < len(nums) and tra <= two:
#             if nums[tra] == 0:
#                 nums[zero], nums[tra] = nums[tra], nums[zero]
#                 zero += 1
#             if nums[tra] == 2:
#                 nums[two], nums[tra] = nums[tra], nums[two]
#                 two -= 1
#                 tra -= 1
#             tra += 1

#         Same speed solution:
#         i = 0
#         j = 0
#         n = len(nums)
#         for k in xrange(n):
#             c = nums[k]
#             nums[k] = 2
#             if c == 0:
#                 nums[j] = 1
#                 j += 1
#                 nums[i] = 0
#                 i += 1
#             elif c == 1:
#                 nums[j] = 1
#                 j += 1

        left = 0
        right = 0
        color = 0
        l = len(nums)
        while left < l and color < 3:
            if nums[left] == color:
                left += 1
                continue
            else:
                right = left
                while right < l and nums[right] != color:
                    right += 1
                if right == l:
                    color+=1
                else:
                    nums[left],nums[right] = nums[right],nums[left]


#!/urs/bin/python3
# oppgave en (classes)

class kjoretoy:
    navn = ""
    variant = "bil"
    farge = ""
    verdi = 100.000

    def besrkivelse(self):
        beskrivelse_str = " %s er en %s %s verdt kr %.2f." % (self.navn, self.farge, self.variant, self.verdi)
        print (beskrivelse_str)

bil1 = kjoretoy()
bil1.farge = "rød"
bil1.variant = "cab"
bil1.navn = "bil nummer 1"
bil1.verdi = 800000.00

bil2 = kjoretoy()
bil2.farge = "blå"
bil2.variant = "van"
bil2.navn = "bil nummer 2"
bil2.verdi = 300000.00

(bil1.besrkivelse())
(bil2.besrkivelse())


#!/usr/bin/env python3

import sys
import json
import getopt
import datetime

import warnings
# Don't show twisted warn
warnings.simplefilter("ignore")
from twisted.internet import reactor, protocol

class TcpClient(protocol.Protocol, protocol.ClientFactory):
    protocol = None
    opts = ''
    def connectionMade(self):
        self.transport.write(self.opts.encode())

    def dataReceived(self, data):
        data_list = data.decode().split('\n')
        for item in data_list:
            item = item[item.find(':') + 1:]
            try:
                parsed = json.loads(item)
                print(json.dumps(parsed, indent=4, sort_keys=True))
            except:
                print(item)
        self.transport.loseConnection()

    def connectionLost(self, reason):
        pass

    def clientConnectionFailed(self, connector, reason):
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        reactor.stop()

def print_help(prog_name):
    print('Usage: ' + prog_name + ' <opt [arg]>')
    print('opt:')
    print('\t-h: show this help')
    print('\t-i: show devices informations')
    print('\t-s: show url server')
    print('\t-t: show current time')
    print('\t-d: show current date')
    print('\t-u [server]: change server')
    print('\t-n [time hh:mm:ss]: change current time')
    print('\t-m [date aaaa-mm-dd]: change current date')

def main(prog_name, argv):
    try:
        opts, _ = getopt.getopt(argv, 'histdu:n:m:',
                ['server=', 'time=', 'date='])
    except getopt.GetoptError:
        print_help(prog_name)
        sys.exit(2)

    if len(opts) == 0:
        print_help(prog_name)

    opts_tcp = ''

    for opt, arg in opts:
        if opt == '-h':
            print_help(prog_name)
            sys.exit()
        elif opt == '-i':
            opts_tcp += 'i?\n'
        elif opt == '-s':
            opts_tcp += 's?\n'
        elif opt == '-t':
            opts_tcp += 't?\n'
        elif opt == '-d':
            opts_tcp += 'd?\n'
        elif opt in ('-u', '--server'):
            opts_tcp += 'u:' + arg + '\n'
        elif opt in ('-n', '--time'):
            opts_tcp += 'n:' + arg + '\n'
        elif opt in ('-m', '--date'):
            opts_tcp += 'm:' + arg + '\n'

    f = TcpClient()
    f.protocol = TcpClient
    f.protocol.opts = opts_tcp
    reactor.connectTCP('localhost', 1234, f)
    reactor.run()

if __name__ == '__main__':
    main(sys.argv[0], sys.argv[1:])


#Embedded file name: eveaudio\audiomanager.py
import audio2
import blue
import remotefilecache
import uthread2
from eveaudio import LANGUAGE_ID_TO_BANK
import logging
L = logging.getLogger(__name__)

class AudioManager(object):
    """Wraps an `audio2.AudManager` so the state of banks can be better managed.

    Banks are added to the list of active banks and loaded to memory if the manager is enabled
    using the 'SwapBanks' function. If the manager is disabled, then 'SwapBanks' will
    just add the name of the bank to the list of active banks that will be loaded
    into memory the next time manager is enabled.

    :type audio2Manager: audio2.AudManager
    :param banksToKeepActive: Banks to keep active when other banks are swapped.
    """

    def __init__(self, audio2Manager, banksToKeepActive):
        """
        Takes in an audio2 AudManager and a list of banks that should be loaded

        :type audio2Manager: audio2.AudManager
        :param audio2Manager: An instance of audio2.AudManager
        :type banksToKeepActive: list()
        :param banksToKeepActive: A list of banks that should be loaded at all times.
        """
        self.manager = audio2Manager
        self.defaultBanks = banksToKeepActive
        uthread2.StartTasklet(self.LoadDefaultBanks)

    def LoadDefaultBanks(self):
        prefetch = set()
        for bank in self.defaultBanks:
            filename = 'res:/Audio/' + bank
            if blue.paths.exists(filename) and not blue.paths.FileExistsLocally(filename):
                prefetch.add(filename)

        remotefilecache.prefetch_files(prefetch)
        map(self.manager.LoadBank, self.defaultBanks)

    def LoadedBanks(self):
        """Returns the names of all banks loaded into memory."""
        return self.manager.GetLoadedSoundBanks()

    def Disable(self):
        """
        Disables the audio manager, and unloads all sound banks from memory.
        """
        self.manager.SetEnabled(False)

    def Enable(self):
        """
        Enables the audio manager and loads all banks to memory.

        Even though the manager has been disabled and all banks unloaded from memory,
        all banks that have been swapped during the disabled time will load correctly
        to memory as the manager maintains an active list of banks that should be
        loaded.
        """
        self.manager.SetEnabled(True)

    def SwapBanks(self, banks):
        """
        Takes in a list of banks, compares them to the list that has already been loaded,
        unloads banks that are no longer needed and loads the banks that are needed.
        It never unloads the common banks that are defined in the constructor

        :type banks: list()
        :param banks: A list of banks what should be loaded at this time, should not include common banks.
        """
        loadedBanks = self.LoadedBanks()
        self._UnloadUnusedBanks(banks, loadedBanks)
        self._LoadNeededBanks(banks, loadedBanks)

    def _UnloadUnusedBanks(self, banks, loadedBanks):
        """
        Compairs the loaded banks, and banks to be loaded, excluding the common banks, and unloads all
        uneccesary banks.

        :type banks: list()
        :param banks: A list of banks to be loaded
        :type loadedBanks: list()
        :param loadedBanks: A list of banks that are currenty loaded
        """
        defaultsExcluded = set(loadedBanks).difference(self.defaultBanks)
        banksToUnload = defaultsExcluded.difference(banks)
        for each in banksToUnload:
            L.debug('Unloading %s' % each)
            self.manager.UnloadBank(each)
            uthread2.Yield()

    def _LoadNeededBanks(self, banks, loadedBanks):
        """
        Compairs the banks that are already loaded and loads only the banks that aren't already in the
        loaded banks list.

        :type banks: list()
        :param banks: a list of banks to be loaded
        :type loadedBanks: list()
        :param loadedBanks: A list of banks currently loaded
        :return:
        """
        banksToLoad = set(banks).difference(loadedBanks)
        for each in banksToLoad:
            L.debug('Loading %s' % each)
            self.manager.LoadBank(each)
            uthread2.Yield()

def InitializeAudioManager(languageID):
    manager = audio2.GetManager()
    io = audio2.AudLowLevelIO(u'res:/Audio/', LANGUAGE_ID_TO_BANK.get(languageID, u''))
    initConf = audio2.AudConfig()
    initConf.lowLevelIO = io
    initConf.numRefillsInVoice = 8
    initConf.asyncFileOpen = True
    manager.config = initConf
    return manager


#!/flask/bin/python3
from flask import Flask, jsonify, abort, make_response, request, url_for
#from flask.ext.httpauth import HTTPBasicAuth
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()

@auth.get_password
def get_password(username):
    if username == 'wojtek':
        return 'serafin'
    return None

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error':'Unauthorized access'}), 401)

app = Flask(__name__)
#app.config['STATIC_FOLDER'] = 'static'

tasks = [
    {
        'id':1,
        'title':'Test 1',
        'description':'Test description 1',
        'done': False
    },
    {
        'id':2,
        'title':'Test 2',
        'description':'Second test description',
        'done': False
    }
]

def make_hyperlink(task):
    new_task = {}
    for field in task:
        if field == 'id':
            new_task['uri'] = url_for('get_task', task_id=task['id'], _external= True)
        else:
            new_task[field] = task[field]
    return new_task

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error':'Not found.'}),404)

@app.route('/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        abort(400)
    if request.json['title'] == '':
        abort(400)
    newtask = {
        'id':tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(newtask)
    return jsonify({'task': newtask}), 201

@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    if not request.json:
        abort(400)
    if 'title' in request.json and type(request.json['title']) != str:
        abort(400)
    if 'description' in request.json and type(request.json['description']) is not str:
        abort(400)
    if 'done' in request.json and type(request.json['done']) is not bool:
        abort(400)
    task[0]['title'] = request.json.get('title', task[0]['title'])
    task[0]['description'] = request.json.get('description', task[0]['description'])
    task[0]['done'] = request.json.get('done', task[0]['done'])
    return jsonify({'task': task[0]})

@app.route('/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    tasks.remove(task[0])
    return jsonify({'result': True})

@app.route('/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': [make_hyperlink(task) for task in tasks]})

@app.route('/tasks/<int:task_id>', methods=['GET'])
#@auth.login_required
def get_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        abort(404)
    return jsonify({'task':task})

if __name__ == "__main__":
    app.run(host='0.0.0.0')


#!/usr/bin/env python
import numpy as np
import math
import scipy.linalg
import cvxopt
from tf.transformations import euler_from_quaternion
from geometry_msgs.msg import Twist, PoseArray, PoseStamped, PolygonStamped
from nav_msgs.msg import Odometry, Path

class Optimizer:
    def __init__(self, nstep=21, margin=0.6):
        self.x = 0.0  # x coordinates in world frame
        self.y = 0.0  # y coordinates in world frame
        self.t = 0.0  # angle from horizontal in world frame
        self.v = 0.0  # linear x velocity
        self.w = 0.0  # angular z velocity
        self.obstacles = []

        self.vision = 3.0
        self.margin = margin
        self.nobj = 0
        self.nobjsee = self.nobj
        self.nstep = nstep

        dt = 0.5
        Vx = 0.1

        #=====================
        # COST FUNCTION
        # weight
        self.c = np.array([1,10,200]) # [penalize for change between old and new path | penalize for change in velocity | penalize for change in acceleration]
        # The distance metric between the original path and the new path
        self.Q1 = np.eye(self.nstep*2)
        # The velocity
        Vconst = np.concatenate([np.concatenate([-np.eye(2), np.eye(2), np.zeros([2,(self.nstep-2)*2])], axis=1),
                                np.concatenate([np.zeros([(self.nstep-1)*2,2]), np.eye((self.nstep-1)*2)], axis=1)
                                -np.concatenate([np.eye((self.nstep-1)*2), np.zeros([(self.nstep-1)*2,2])], axis=1)])
        V_ratio = np.array([[5, 0], [0, 1]])
        Rpenalty = np.kron(np.eye(self.nstep),V_ratio)
        self.Q2 = Vconst.T.dot(Rpenalty.T.dot(Rpenalty)).dot(Vconst)
        Vref = np.array([[Vx,0]])*dt
        self.Vref_1 = self.c[1]*np.kron(np.ones([1, self.nstep]).flatten(),Vref).dot((Rpenalty.T.dot(Rpenalty)).dot(Vconst))
        # The acceleration
        Vdiff = np.eye(self.nstep*2)-np.diag(np.ones([1,(self.nstep-1)*2]).flatten(),2)                                 # 1 along diagonal, -1 at 2nd above diagonal
        Adiff = Vdiff - np.diag(np.ones([1,(self.nstep-1)*2]).flatten(),2) + np.diag(np.ones([1,(self.nstep-2)*2]).flatten(),2*2)    # [1 0 -2 0 1] repeated along/right of diagonal
        self.Q3 = Adiff[0:(self.nstep-2)*2,:].T.dot(Adiff[0:(self.nstep-2)*2,:])

    def odom_callback(self, msg):
        self.x = msg.pose.pose.position.x
        self.y = msg.pose.pose.position.y
        self.v = msg.twist.twist.linear.x
        self.w = msg.twist.twist.angular.z

        _,_,yaw = euler_from_quaternion([msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w])
        self.t = yaw

    def obstacle_callback(self, msg):
        self.obstacles += [self.polygonstampednp(p) for p in msg.polygons]
        num_obs = len(self.obstacles)
        self.obstacles = self.obstacles[(num_obs // 5):]
        self.obstacles = self.obstacles[:3]

    def polygonstampednp(self, msg):
        arr = np.array([[],[],[]])
        Rz = np.array([[np.cos(-self.t), -np.sin(-self.t), 0], [np.sin(-self.t), np.cos(-self.t), 0], [0, 0, 1]])
        for i in range(len(msg.polygon.points)):
            pts_body = self.vectornp(msg.polygon.points[i])
            pts_earth = Rz.dot(pts_body) + np.array([[self.x], [self.y], [0]])
            arr = np.concatenate([arr, pts_earth], axis=1)

        return arr

    def vectornp(self, msg):

        return np.array([[msg.x, msg.y, msg.z]]).T

    def optimize(self, obstacles):
        nobj = len(obstacles)
        nobjsee = nobj

        if False:# and obstacles == []:
            poseArray = []
            for i in range(self.nstep):
                poses = PoseStamped()
                poses.pose.position.x = self.x + .05*i
                poses.pose.position.y = self.y
                poseArray += [poses]

            waypoints = Path()
            waypoints.header.frame_id = 'odom'
            waypoints.poses = poseArray
            return waypoints

        #Generate reference trajectory
        # current_x: [x, y, theta, vx, wz]
        z0 = np.array([[self.x], [self.y]])   # current: x0, y0
        zT = np.array([[self.x+self.vision], [0]])     # target: x0+3, y0

        path = np.concatenate([[np.linspace(z0[0], zT[0],self.nstep)],
                           [np.linspace(z0[1], zT[1],self.nstep)]])

        ## Cost function update
        dir = np.array([zT[0]+6, zT[1]])
        dir_T = (1/np.linalg.norm(dir))*(np.array([zT[1], -zT[0]-6])).T
        dd = np.kron(np.ones([self.nstep,1]), dir_T.dot(np.array([[-6], [0]])))
        D = np.kron(np.eye(self.nstep),dir_T)

        # Distance to reference line
        Q1 = D.T.dot(D)
        Xdis_1 = 2*self.c[0]*dd.T.dot(D)
        # The total costj
        Qref = Q1*self.c[0] + self.Q2*self.c[1] + self.Q3*self.c[2]

        ## Extended cost
        Mcurv = np.eye(self.nstep)
        Mcurv[-1,-1] = 5
        Vcurv = np.eye(self.nstep)-np.diag(np.ones([1,self.nstep-1]).flatten(),1)
        Qcurv = 5*Mcurv

        ## The boundary constraint
        Aeq = np.zeros([2, self.nstep*2 + self.nstep + nobj*self.nstep])
        Aeq[0:2, 0:2] = np.eye(2)
        beq = path[:,0].reshape(2,1)

        ## The Iteration
        refpath = path.flatten('F')
        oripath = refpath[0:2]
        refinput = np.ones([1, self.nstep])

        for k in range(10):
            Lstack = np.array([[]]*(63+self.nstep*nobj)).T
            Sstack = np.array([[]]*1).T
            for i in range(self.nstep):
                for j in range(nobjsee):                                                 # for each object
                    poly = obstacles[j]#+obs{j}.v*np.(ones(1,4)*dt*i                 # position of obstacle at time i (initial position, + velocity*time)
                    L,S,d = self.d2poly(refpath[i*2:(i+1)*2].T, poly.T)
                    Lstack = np.concatenate([Lstack,
                                             np.concatenate([np.zeros([1,i*2]), L, np.zeros([1,(self.nstep-(i+1))*2]), np.zeros([1,self.nstep]),
                                                             np.zeros([1,i*nobj+j]), np.array([[-1]]), np.zeros([1,nobj*(self.nstep-i)-(j+1)])], axis=1)])
                    Sstack = np.concatenate([Sstack, S-self.margin])
                    # Soft constraint
                    Lstack = np.concatenate([Lstack, np.concatenate([np.zeros([1,self.nstep*3]), np.zeros([1,i*nobj+j]), np.array([[-1]]), np.zeros([1,nobj*(self.nstep-i)-(j+1)])], axis=1)])
                    Sstack = np.concatenate([Sstack, np.array([[0]])])

           ## QP
            Qe = scipy.linalg.block_diag(Qref, Qcurv)

            # enlarge A ,f for soft constraint
            H = scipy.linalg.block_diag(Qe, 50*np.diag(np.ones([1,nobj*self.nstep]).flatten()))
            f = np.concatenate([-np.concatenate([Xdis_1.T, np.zeros([self.nstep,1])])-np.concatenate([self.Vref_1.T, np.zeros([self.nstep,1])]),
                                np.zeros([nobj*self.nstep,1])])
            H = cvxopt.matrix(H)
            f = cvxopt.matrix(f)
            Lstack = cvxopt.matrix(Lstack)
            Sstack = cvxopt.matrix(Sstack)
            Aeq = cvxopt.matrix(Aeq)
            beq = cvxopt.matrix(beq)
            cvxopt.solvers.options['show_progress'] = False
            soln = cvxopt.solvers.qp(H,f,Lstack,Sstack,Aeq,beq)
            soln = soln['x']
            pathnew = soln[0:2*self.nstep]
            refinput = soln[2*self.nstep:]

            z0 = np.array([[pathnew[2], pathnew[3]]])
            zT = np.array([[pathnew[2]+self.vision, 0]])

            refpath = pathnew

        poseArray = []
        for i in range(self.nstep):
            poses = PoseStamped()
            poses.pose.position.x = refpath[2*i]
            poses.pose.position.y = refpath[2*i+1]
            poseArray += [poses]
        waypoints = Path()
        waypoints.header.frame_id = 'odom'
        waypoints.poses = poseArray
        return waypoints

    def d2poly(self, point, poly):
        # point = current position
        # poly = current position of polynomial
        poly = poly[:,0:2]
        d = np.inf
        nside = len(poly)                                                                # vertices of obstacle
        for i in range(nside):                                                               # FOR EACH VERTEX
            x1 = poly[i,0]                                                                  # x coord of i-th vertex
            y1 = poly[i,1]                                                                  # y coord of i-th vertex
            x2 = poly[np.mod(i+1,nside),0]                                                    # x coord of next vertex (loops around to 1st vertex when at the last one)
            y2 = poly[np.mod(i+1,nside),1]
            trid1 = np.linalg.norm([x1-x2,y1-y2])                                                  # distance between i-th and i+1-th vertex
            trid2 = np.linalg.norm([x1-point[0],y1-point[1]])                                      # distance between i-th vertex and current location
            trid3 = np.linalg.norm([x2-point[0],y2-point[1]])                                      # distance between i+1-th vertex and current location
            # default case
            Lr = np.array([[y1-y2,x2-x1]])                                                  # [-dy, dx]
            Sr = np.array([[-x1*y2+x2*y1]])
            vd = abs(Lr[0,0]*point[0]+Lr[0,1]*point[1]-Sr)/trid1                                # |-dy*x0 + dx*y0 - Sr|/trid1
            # case 1
            if pow(trid2,2) > pow(trid1,2)+pow(trid3,2):                                                    # theta > 90deg
                vd = trid3                                                                  # i+1-th vertex ix closer
                Lr = np.array([[point[0]-x2,point[1]-y2]])                                  # [x0 - x-coord of i+1-th vertex, y0 - y-coord of i+1-th vertex]
                Sr = np.array([[point[0]-x2,point[1]-y2]]).dot(np.array([[x2],[y2]]))       # deltaX * x2 + deltaY * y2
            # case 2
            if pow(trid3,2) > pow(trid1,2)+pow(trid2,2):
                vd = trid2
                Lr = np.array([[point[0]-x1,point[1]-y1]])
                Sr = np.array([[point[0]-x1,point[1]-y1]]).dot(np.array([[x1],[y1]]))
            if vd < d:                                                                        # if the closer of the 2 vertices is closer than any previous ones
                d = vd                                                                       # new distance = distance to vertex
                L = Lr                                                                       # new x, y distance to vertex
                S = Sr
                ii = i                                                                       # index of closest vertex
        # determine sign on L, S, d
        nL = np.linalg.norm(L)
        L = L/nL          # normalized of L
        S = S/nL           # S normalized with L
        if L.dot(poly[np.mod(ii+2,nside)].T) < S:    # vertex 2 positions later
            L = -L         #
            S = -S
        if d == 0:
            return
        area = 0
        polyarea = 0
        for i in range(nside):
            area = area + self.triArea(point,poly[i,:], poly[np.mod(i+1,nside),:])
        for i in range(1,nside-1):
            polyarea = polyarea + self.triArea(poly[0,:],poly[i,:],poly[np.mod(i,nside)+1,:])
        if np.linalg.norm(polyarea-area) < 0.01:
            d = -d
        return L, S, d

    def triArea(self, p1, p2, p3):
        a = np.linalg.norm(p1-p2)
        b = np.linalg.norm(p1-p3)
        c = np.linalg.norm(p2-p3)
        half = (a+b+c)/2
        return math.sqrt(half*(half-a)*(half-b)*(half-c))


import logging
import motor
import json
import tornado.gen

import mickey.publish
import mickey.tp
import mickey.userfetcher
import mickey.maps
import mickey.redis
import datetime

from mickey.commonconf import mongo_url, MAX_REALGROUPS, MAX_MEMBERS, conf_expire_time, REDIS_GROUPATTACH_HASH, LOCAL_NODE_NAME, REDIS_LOCK_GROUPATTACH, GROUP_PUBLIC_GROUPS, REDIS_GROUP_KPALIVE_PREFIX, REDIS_GRPBRIEF_PREFIX
from mickey.groups.libgroup import filter_mydevice, getreal_groups
from mickey.groups.mickeygroup import MickeyGroup

_logger = logging.getLogger(__name__)

_garbage = ""
for i in range(50):
    _garbage += "this only to occupy the space for user, avoid mongo to  move the data when it get bigger. "

_group_db = motor.MotorClient(mongo_url).group
_user_db = motor.MotorClient(mongo_url).contact

_publish = mickey.publish
_public_groups = []

class GroupMgrMgr(object):

    @classmethod
    @tornado.gen.coroutine
    def createGroup(cls, creater, groupbody, isadmin = False):
        if not creater or not groupbody:
            return (403, None)

        result    = {}
        owner     = groupbody.get("owner", creater)
        invite    = groupbody.get("invite", "free").lower()
        groupname = groupbody.get("name", "")
        members   = groupbody.get("members", [])

        _logger.info("begin to create group owner = %s, name = %s, invite = %s" % (owner, groupname, invite))
        _logger.info("groupbody = %r" % groupbody)

        if not isadmin and creater != owner:
            _logger.error("forbiden you can not create group for other user")
            return (403, result)

        if (invite != "free") and (invite != "admin"):
            _logger.error("invalid invite type %s" % invite)
            return (403, result)

        member_ids = [x.get("id", "") for x in members]
        if creater not in member_ids:
            members.append({"id" : creater})
            member_ids.append(creater)

        #remove repeat
        unique_member_ids = list(set(member_ids))
        format_members = [ {"id": x} for x in unique_member_ids]

        coll = _group_db.groups
        usercoll = _user_db.users

        db_groupinfo = {}
        db_groupinfo["name"] = groupname
        db_groupinfo["owner"] = owner
        db_groupinfo["invite"] = invite

        if invite == "admin":
            realgroups = yield getreal_groups(creater)
            if ((realgroups + 1) > MAX_REALGROUPS) or (len(format_members) > MAX_MEMBERS):
                return (413, result)

            canadd_members = [creater]
            my_devices =  yield filter_mydevice(creater, unique_member_ids)
            if my_devices:
                for item in my_devices:
                    canadd_members.append(item)

            db_groupinfo["appendings"] = list(filter(lambda x: x.get("id", "") not in canadd_members, format_members))
            db_groupinfo["members"] = list(filter(lambda x: x.get("id", "") in canadd_members, format_members))
        else:
            db_groupinfo["members"] = format_members
            db_groupinfo['expireAt'] = datetime.datetime.utcnow() + datetime.timedelta(days = conf_expire_time)

        db_groupinfo["garbage"] = _garbage

        db_result = yield coll.insert(db_groupinfo)

        if db_result:
            groupid = str(db_result)
            _logger.info("create group success %s" % groupid)

            mickey.tp.addgroup(groupid, owner, "")
            result["members"] = db_groupinfo.get("members", [])
            result["appendings"] = db_groupinfo.get("appendings", [])
            result["groupid"] = groupid
            result["name"] = groupname
            result["owner"] = owner
            result["invite"] = invite

            added_members = [x.get("id", "") for x in db_groupinfo.get("members", [])]
            if invite == "admin":
                for item in added_members:
                    yield usercoll.find_and_modify({"id":item},
                                                   {
                                                     "$push":{"groups":{"id": groupid}, "realgroups":groupid},
                                                     "$unset": {"garbage": 1}
                                                   })

            #notify all the members
            notify = {}
            notify["name"] = "mx.group.group_invite"
            notify["pub_type"] = "any"
            notify["nty_type"] = "app"
            notify["msg_type"] = "other"
            notify["groupname"] = groupname
            notify["groupid"] = groupid

            invite_receivers = list(filter(lambda x: x != creater, added_members))

            _publish.publish_multi(invite_receivers, notify)

            #notify all the invited members
            if invite == "admin":
                invite_receivers = [x.get("id", "") for x in db_groupinfo.get("appendings", [])]
                invite_receivers.append(creater)
                notify["name"] = "mx.group.authgroup_invited"
                notify["userid"] = creater
                opter_info = yield mickey.userfetcher.getcontact(creater)
                if opter_info:
                    notify["username"] = opter_info.get("name", "")
                _publish.publish_multi(invite_receivers, notify)

            #notify user self
            self_notify = {
              "name":"mx.group.self_group_created",
              "groupid":groupid,
              "groupname":groupname,
              "pub_type":"any",
              "nty_type":"app",
              "msg_type":"other"
            }

            _publish.publish_one(creater, self_notify)

            # add maps
            if invite == "admin":
                mickey.maps.addgroup(groupid, creater, [], 1)
            else:
                mickey.maps.addgroup(groupid, creater, added_members)

            return (200, result)
        else:
            return (500, result)

    @classmethod
    @tornado.gen.coroutine
    def getgroup(cls, groupid):
        group = MickeyGroup(groupid)
        yield group.load()

        if group.exist() == True:
            return group

        return None

    @classmethod
    @tornado.gen.coroutine
    def searchgroup(cls, openid):
        coll = _group_db.tbchats
        chat = yield coll.find_one({"id":openid})
        if not chat:
            return None

        groupid = chat.get('gid', '')

        if groupid:
            group = yield cls.getgroup(groupid)
            if group.get_openid() != "":
                return group

        return None

    @classmethod
    @tornado.gen.coroutine
    def searchgroup_by_shareid(cls, shareid):
        coll = _group_db.shareids
        if not shareid:
            return None

        shareinfo = yield coll.find_one({"id": shareid})
        if not shareinfo:
            return None

        groupid = shareinfo.get("groupid", "")
        group = yield cls.getgroup(groupid)

        return group

    @classmethod
    @tornado.gen.coroutine
    def check_attacher(cls):
        if mickey.redis.get_lock(REDIS_LOCK_GROUPATTACH, LOCAL_NODE_NAME, 120) == False:
            return

        _logger.info("%s is the leader begin to check attacher" % LOCAL_NODE_NAME)

        expired_attachers = mickey.redis.hdecall_with_limit(REDIS_GROUPATTACH_HASH, 0)
        for item in expired_attachers:
            (groupid, userid) = item.split('_')
            group = yield cls.getgroup(groupid)

            if group:
                yield group.disattach_member(userid)

            _logger.info("group %s user %s disattached" % (groupid, userid))

    @classmethod
    def keepalive_attacher(cls, groupid, userid):
        attacher_key = "%s_%s" % (groupid, userid)
        mickey.redis.hset(REDIS_GROUPATTACH_HASH, attacher_key, 6)

    @classmethod
    @tornado.gen.coroutine
    def get_group_brief(cls, groupid):
        if not groupid:
            return None

        # First load from redis
        group_rediskey = REDIS_GRPBRIEF_PREFIX + groupid
        group_raw = mickey.redis.read_from_redis(group_rediskey)
        if group_raw:
            return json.loads(group_raw)

        # Second load from mongo
        group = yield cls.getgroup(groupid)

        if group:
            groupinfo = {}
            groupinfo["id"] = groupid
            groupinfo["name"] = group.get_name()
            groupinfo["invite"] = group.get_invite()
            groupinfo["tp_chatid"] = group.get_chatid()
            groupinfo["open_id"] = group.get_openid()

            # Cache to redis
            group_raw = json.dumps(groupinfo)
            mickey.redis.write_to_redis(group_rediskey, group_raw)

            return groupinfo

        return None

    def clear_brief_cache(cls, groupid):
        if not groupid:
            return

        group_rediskey = REDIS_GRPBRIEF_PREFIX + groupid
        mickey.redis.remove_from_redis(group_rediskey)
        return

    @classmethod
    def get_kpalive_key(cls, device, userid, groupid):
        if not device or not userid or not groupid:
            return None

        kp_key = "%s_%s%s%s" % (REDIS_GROUP_KPALIVE_PREFIX, device.lower(), userid, groupid)
        return kp_key

    @classmethod
    def get_other_device(cls, device):
        if not device:
            return ""

        if device == "pc":
            return "mobile"
        else:
            return "pc"


from ae import basic_AE
import os
from keras import backend as K
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

def run(DataGen, epochs, batch_size, datatype, no_directory=None):
    #General params
    labels = {'n':0, 'y':1}
    factor = 1
    resize_row = 4*factor
    resize_col = 5*factor
    img_rows = int(1126/(4.39*factor))
    img_cols = int(636/(4.95*factor))
    optimizer = 'RMSprop'
    loss = 'mse'

    #Train params
    train_dir = '/s0/{}/train/'.format(datatype)
    valid_dir = '/s0/{}/valid/'.format(datatype)
    test_dir = '/s0/{}/test/'.format(datatype)
    lenData = len(os.listdir(train_dir))
    lenValid = len(os.listdir(valid_dir))
    lenTest = len(os.listdir(test_dir))
    shuffle = True

    #Creating class object, which is the network
    AE = basic_AE(img_rows, img_cols, batch_size=batch_size)
    AE.compiler(optimizer, loss)
    test_generator, nlayers = AE.train(DataGen, lenData, lenValid, lenTest,
                                epochs, train_dir, valid_dir, test_dir, shuffle,
                                resize_row, resize_col, no_directory)
    AE.save_result(test_generator, test_dir, resize_row, resize_col)
    savename = '{}_{}l_{}e_bm.png'.format(datatype, (nlayers-2), epochs)
    K.clear_session()
    return savename, resize_row, resize_col, img_rows, img_cols

def plot_recreate(path1, path2, v_min, v_max, savepath, savename):
    fig = plt.figure(figsize=[18,10])

    # Display real data
    file1 = os.listdir(path1)[0]
    real = np.load(path1 + file1)
    plt.subplot(131)
    normed = real/np.amax(abs(real))
    normed = ((normed+1)/2)
    plt.imshow(normed, cmap='gray', vmin=v_min, vmax=v_max)
    plt.title('Input (max=' + str(round(np.amax(normed),2)) + '),' +
                        ' (sum=' + str(round(np.sum(normed),2)) + ')')
    plt.axis('off')

    # Display reconstructed data
    file2 = os.listdir(path2)[0]
    recon_img = np.load(path2 + file2)
    plt.subplot(132)
    plt.imshow(recon_img, cmap='gray', vmin=v_min, vmax=v_max)
    plt.title('Output (max=' + str(round(np.amax(recon_img),2)) + '),' +
                        ' (sum=' + str(round(np.sum(recon_img),2)) + ')')
    plt.axis('off')

    #Display Difference
    plt.subplot(133)
    difference = abs(normed - recon_img)
    plt.imshow(difference, cmap='gray', vmin=v_min, vmax=v_max)
    plt.title('Diff (max=' + str(round(np.amax(difference),2)) + '),'
                        ' (sum=' + str(round(np.sum(difference),2)) + ')')
    plt.axis('off')
    plt.suptitle(r'Image comparison where $v_{min}=$'+ str(v_min) +
                                        r' and $v_{max} =$' + str(v_max))
    plt.savefig(savepath + savename)
    return

def plot_removal(path1, path2, no_noise, v_min, v_max, savepath, savename,
                                resize_row, resize_col, img_rows, img_cols):
    fig = plt.figure(figsize=[26, 10])

    # Plot clean data
    noisy = os.listdir(path1)[0]
    clean = np.load(no_noise + 'n' + noisy[1:]).T[:1024,:]
    clean = clean[::resize_row, ::resize_col]
    clean = np.reshape(clean, (img_rows, img_cols))
    plt.subplot(141)
    normed_clean = clean/np.amax(abs(clean))
    normed_clean = ((normed_clean+1)/2)
    plt.imshow(normed_clean, cmap='gray', vmin=v_min, vmax=v_max)
    plt.title('Clean (max=' + str(round(np.amax(normed_clean),2)) + '),' +
                        ' (sum=' + str(round(np.sum(normed_clean),2)) + ')')
    plt.axis('off')

    # plot noisy data
    real = np.load(path1 + noisy)
    plt.subplot(142)
    normed = real/np.amax(abs(real))
    normed = ((normed+1)/2)
    plt.imshow(normed, cmap='gray', vmin=v_min, vmax=v_max)
    plt.title('Input (max=' + str(round(np.amax(normed),2)) + '),' +
                        ' (sum=' + str(round(np.sum(normed),2)) + ')')
    plt.axis('off')

    # Display reconstructed data
    recon = os.listdir(path2)[0]
    recon_img = np.load(path2 + recon)
    plt.subplot(143)
    plt.imshow(recon_img, cmap='gray', vmin=v_min, vmax=v_max)
    plt.title('Output (max=' + str(round(np.amax(recon_img),2)) + '),' +
                        ' (sum=' + str(round(np.sum(recon_img),2)) + ')')
    plt.axis('off')

    #Display Difference
    plt.subplot(144)
    difference = abs(normed_clean - recon_img)
    plt.imshow(difference, cmap='gray', vmin=v_min, vmax=v_max)
    plt.title('Diff (max=' + str(round(np.amax(difference),2)) + '),'
                        ' (sum=' + str(round(np.sum(difference),2)) + ')')
    plt.axis('off')
    plt.suptitle(r'Image comparison where $v_{min}=$'+ str(v_min) +
                                        r' and $v_{max} =$' + str(v_max))
    plt.savefig(savepath + savename)
    return

def write_img(file, savepath):
    data = np.load(file)
    data = data/np.amax(abs(data))
    data = ((data+1)/2)*255
    cv2.imwrite(savepath + 'tmp.png', data.T, [0])

if __name__ == '__main__':
    mode = 2

    batch_size = 32
    epochs = 30
    datatypes = ['AGC', 'SI', 'rSI']
    datatype = datatypes[mode]
    v_min = 0.3
    v_max = 0.7
    path1 = 'tmp_files/actual_data/'
    path2 = 'tmp_files/recreated/'
    no_noise = '/s0/rSI/no/'
    savepath = 'pictures/'
    if mode == 2:
        from noise_removal_gen import DataGen
        savename, resize_row, resize_col, img_rows, img_cols = run(DataGen,
                            epochs, batch_size, datatype, no_directory=no_noise)
        plot_removal(path1, path2, no_noise, v_min, v_max, savepath, savename,
                                    resize_row, resize_col, img_rows, img_cols)
    else:
        from ae_gen import DataGen
        savename, _, _, _, _= run(DataGen, epochs, batch_size, datatype)
        plot_recreate(path1, path2, v_min, v_max, savepath, savename)


import random
from weapons import *
from constants import *
from ai import STORY_MODE, USE_AI
from enemy_data import enemies, enemy_freqs
from enemy_data import enemies, enemy_freqs, STEVENDORF_STATS

class WeaponConstructor(object):
    def __init__(self):
        self.dropped_shield = False
        self.dropped_bow = False
        self.dropped_sword = False

    def __call__(self, weapon, name, strength, durability):
        if not self.dropped_shield:
            self.dropped_shield = True
            return Defense("SHIELD", "Flimsy Shield", 2, ITEM_DURABILITIES['Flimsy Shield'])
        elif not self.dropped_bow:
            self.dropped_bow = True
            return RangedWeapon("BOW", "Slimy Bow", 4, ITEM_DURABILITIES['Slimy Bow'])
        elif not self.dropped_sword:
            self.dropped_sword = True
            return MeleeWeapon("SWORD", "Knife", 2, ITEM_DURABILITIES['Knife'])
        elif weapon == "SHIELD":
            return Defense(weapon, name, strength, durability)
        elif not self.dropped_bow or weapon == "BOW":
            return RangedWeapon(weapon, name, strength, durability)
        elif not self.dropped_sword or weapon == "SWORD":
            return MeleeWeapon(weapon, name, strength, durability)
        elif weapon == "CLUB":
            return MeleeWeapon(weapon, name, strength, durability)
        elif weapon == "CLAWS":
            return MeleeWeapon(weapon, name, strength, durability)
        raise Exception("Bad argument to weapon constructor!")

class BaseConstructorException(Exception):
    pass

class Entity(object):
    def __init__(self):
        self.health = 5
        pass

    def damage(self, num):
        self.health -= min(self.health, num)

    def isDead(self):
        return not self.health

class Player(Entity):
    def __init__(self):
        self.health = PLAYER_MAX_HEALTH
        self.hiding = False;

    def hide(self):
        assert(self.hiding == False)
        self.hiding = True;

    def unhide(self):
        assert(self.hiding == True)
        self.hiding = False;

class Enemy(Entity):
    def __init__(self):
        raise BaseConstructorException()

    def __init__(self, image, name, health, item):
        self.image = image
        self.name = name
        self.health = health
        self.item = item
        self.next_attack = 0

    def description(self):
        return {
            'name': self.name,
            'health': self.health,
            'item': self.item.description(),
            'next_attack': self.next_attack
        }

class EnemyFactory(object):
    def __init__(self):
        self.weapon_constructor = WeaponConstructor()
        self.current_level = START_LEVEL
        self.next_enemies = []
        random.seed()
        self.setLevel(START_LEVEL)
        pass

    def setLevel(self, level):
        self.current_level = level
        self.next_enemies = []
        if not level % 10 and not STORY_MODE:
            self.next_enemies.append(self.generateEnemy(level, boss=True))
        else:
            self.next_enemies.append(self.generateEnemy(level))
        for i in range(4):
            self.next_enemies.append(self.generateEnemy(level))

    def get_next_enemy(self):
        self.next_enemies.append(self.generateEnemy(self.current_level))
        return self.next_enemies.pop(0)

    def generateEnemy(self, level, boss=False, dorfweap=10):
        # compute enemy event
        choice = 0
        p = 0
        event = random.uniform(0,1)
        for i in range(len(enemy_freqs)):
            p += enemy_freqs[i]
            if event <= p:
                choice = i
                break
        # select enemy
        enemy = enemies[min(choice, level - 1)] if not boss else STEVENDORF_STATS
        item = enemy["items"][random.randint(0, len(enemy["items"])-1)]

        return Enemy(
            enemy["image"],
            enemy["name"],
            random.randint(enemy["health"]["min"], enemy["health"]["max"]),
            self.weapon_constructor(item["type"], item["name"], (item["strength"] if not boss else dorfweap), item['durability'])
        )


# Курс основы программирования на Python
# Задание по программированию: Сократите дробь
# 08.05.2019
#
# Даны два натуральных числа n и m.
#
# Сократите дробь (n / m), то есть выведите два других числа p и q
# таких, что (n / m) = (p / q) и дробь (p / q) — несократимая.
#
# Решение оформите в виде функции ReduceFraction(n, m), получающая значения
# n и m и возвращающей кортеж из двух чисел: return p, q.
#
# Тогда вывод можно будет оформить как print(*ReduceFraction(n, m)).
#
# Формат ввода
#
# Вводятся два натуральных числа.
#
# Формат вывода
#
# Выведите ответ на задачу.

def gcd(a, b):
    if a % b == 0:
        return b
    elif b % a == 0:
        return a
    if a < b:
        result = gcd(a, b % a)
    else:
        result = gcd(a % b, b)
    return result

def ReduceFraction(n, m):
    nod = gcd(n, m)
    n = n // nod
    m = m // nod
    return n, m

n, m = int(input()), int(input())
n, m = ReduceFraction(n, m)
print(n, m)

Сократите дробь.py

Сократите дробь.py


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

from shape import Shape
from color import WHITE

class Piece:
    """Define piece for tetris game"""

    def __init__(self, surface, gameboard, color=WHITE):
        """Define default piece parameters"""
        self.can_rotate = False
        self.orientation = 'up'
        self.orientation_changes = {
            'up': 'right',
            'right': 'down',
            'down': 'left',
            'left': 'up',
        }
        self.primary_shape = Shape(surface, gameboard, color)
        self.secondary_shape = Shape(surface, gameboard, color)
        self.width = 10
        self.height = 10
        self.x = 0
        self.y = 0

    def set_position(self, x, y):
        """Set x and y position on screen"""
        self.x = x
        self.y = y
        self.primary_shape.set_coords(x, y)
        self.secondary_shape.set_coords(x, y)

    def draw(self):
        """Draw piece on screen"""
        self.primary_shape.draw()
        self.secondary_shape.draw()

    def change_dimension(self):
        """Swap dimension for piece and shapes"""
        if self.can_rotate:
            self.swap_dimension()
            self.primary_shape.swap_dimension()
            self.secondary_shape.swap_dimension()

    def swap_dimension(self):
        """Swap width and height"""
        width = self.width
        height = self.height
        self.width = height
        self.height = width

    def change_orientation(self):
        """Change piece orientarion"""
        self.orientation = self.orientation_changes.get(self.orientation)

    def rotate(self):
        """Rotate piece"""
        self.change_dimension()
        self.change_orientation()

    def get_shapes(self):
        """Return piece's shapes"""
        return [self.primary_shape, self.secondary_shape]

    def save(self):
        """Save piece shapes on screen canvas"""
        self.primary_shape.save()
        self.secondary_shape.save()