import os
import sys
import boto3
import urllib3
from datetime import datetime
import logging as logger

from hysds.celery import app
from util import OrphanedDatasetsFinder, read_context, pull_all_data_sets, publish_dataset

urllib3.disable_warnings()

if __name__ == '__main__':
    # python purge_orphaned_datasets.py aria-ops-dataset-bucket slc PRETEND
    GRQ_ES_URL = app.conf['GRQ_ES_URL'] + '/_search'

    try:
        bucket = sys.argv[1]
        dataset_type = sys.argv[2]
        mode = sys.argv[3]  # ['PRETEND', 'PERMANENT']
    except Exception as e:
        cxt = read_context()
        bucket = cxt['bucket']
        dataset_type = cxt['dataset_type']
        mode = cxt['mode']

    if mode == 'PERMANENT':
        print('PROD PURGE TURNED ON, WILL PURGE S3 FILES')
    else:
        print('PRETEND mode ON, WILL NOT PURGE')

    current_timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    starting_prefix = 'datasets/' + dataset_type + '/'  # Make sure you provide / in the end
    s3_client = boto3.client('s3')
    s3_resource = boto3.resource('s3')
    bucket_resource = s3_resource.Bucket(bucket)
    product_id = 'orphaned_datasets_report-%s-%s' % (current_timestamp, dataset_type)

    if not os.path.exists('%s/%s' % (os.getcwd(), product_id)):
        os.mkdir('%s/%s' % (os.getcwd(), product_id))

    csv_filename = '%s/%s/%s-%s-%s-%s.csv' % (os.getcwd(), product_id, product_id, dataset_type, current_timestamp, mode)
    results_file = open(csv_filename, 'w')

    LOG_FILE_NAME = os.getcwd() + '/orphaned_%s_%s_%s.log' % (dataset_type, current_timestamp, mode)
    logger.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
                       filename=LOG_FILE_NAME,
                       filemode='w',
                       level=logger.INFO)

    logger.info('PULLING ALL %s FROM GRQ' % dataset_type)
    all_data_sets_in_grq = pull_all_data_sets(GRQ_ES_URL, dataset_type)
    logger.info('PULLED %i %s FROM GRQ' % (len(all_data_sets_in_grq), dataset_type))

    dataset_finder = OrphanedDatasetsFinder(mode, s3_client, bucket_resource, bucket, all_data_sets_in_grq,
                                            results_file, logger)
    dataset_finder.traverse_s3_bucket(starting_prefix, 1)
    publish_dataset(product_id)


from nbconvert.preprocessors import Preprocessor

class WrapHtmlPreprocessor(Preprocessor):
    """
    Wraps html ouput from cells in the shortcode `rawhtml`.

    The `rawhtml` shortcode is a file which should be placed in `layouts/shortcodes/rawhtml.html` with this contents:

        <!-- raw html -->
        {{.Inner}}

    Hugo starting from version 0.60 (see discussion: https://discourse.gohugo.io/t/raw-html-getting-omitted-in-0-60-0/22032)
    doesn't render html tags by default, it needs the `unsafe = true` flag instead.

    However, it doesn't handle blocks of HTML very well even if `unsafe = true` in the config.toml and the approach of
    having a shortcode works better.
    """

    def preprocess_cell(self, cell, resources, index):
        outputs = cell.get("outputs", [])
        for output in outputs:
            data = output.get("data", {})
            if "text/html" in data:
                data["text/html"] = (
                    "{{< rawhtml >}}\n" + data["text/html"] + "\n{{< /rawhtml >}}"
                )
        return cell, resources


# decisiontrees.py
# Import the relevant modules from graphviz. Digraph means a graph with directions.
from graphviz import Digraph

# Create a type called Node. A class is a complex object with associated attributes and functions.
class Node(object):
    ''' An object corresponding to an individual node in a decision tree.
    There are three types of nodes: event, decision, or outcome (or value) nodes.

        The attributes are:
            - name: a user specified string that denotes the Node.
            - type: a string that specifies the type of the node. Outcome nodes are denoted using the name "value."
            - children: list of the immediate nodes that descend from this node. Empty if is an outcome/value node.
            - probabilities: (exists for event nodes only) a list of the corresponding probabilities for the children.
            - value: (exists for outcome nodes only) the value of the node.

        The functions are:
            evaluate(): Return the value of the node using backward induction.
            graph(showValues): Return a graphviz object that corresponds to the decision tree.
                Use showValues=True to see the values after solving by backward induction.
                Use showValues=False to see the structure of the tree without solving.

    '''
    def __init__(self,name,children=[],probabilities=[],value=0):
        ''' To create a node, use the following syntax:
            x=Node(name,children,probabilities) (For event nodes)
            x=Node(name,children) (For decision nodes)
            x=Node(name,value=value) (For outcome nodes)
        '''
        self.name=name
        # Decide what type of node it is based on existence of function inputs.
        if probabilities:
            self.type='event'
            self.children=children
            self.probabilities=probabilities
            assert len(probabilities)==len(children), 'The length of the lists "children" and "probabilities" must equal!'
        elif children:
            self.type='decision'
            self.children=children
        else:
            self.type='value'
            self.children=[]
            self.value=value

    def evaluate(self):
        ''' Function that evaluates the current node by backward induction '''
        if self.type=='value':
            # For outcome nodes, return value
            return self.value
        elif self.type=='event':
            # For event nodes, return expected value
            return sum([self.probabilities[i]*self.children[i].evaluate() for i in range(len(self.children))])
        else:
            # For decision nodes, return the value of the best decision
            return max([self.children[i].evaluate() for i in range(len(self.children))])

    def _drawNodes(self,graph,showValues=True):
        ''' Function to draw all nodes that are descendent of the current node.'''
        if self.type=='value':
            graph.attr('node',shape='plaintext')
        elif self.type=='event':
            graph.attr('node',shape='oval')
        else:
            graph.attr('node',shape='square')
        if showValues:
            myLabel='{:.0f}'.format(self.evaluate())
        else:
            myLabel=self.type
        graph.node(str(self),myLabel)
        for child in self.children:
            child._drawNodes(graph,showValues)

    def _drawEdges(self,graph):
        ''' Function to draw all edges that are descendent of the current node.'''
        for i,child in enumerate(self.children):
            if self.type=='decision':
                myLabel=child.name
            else:
                myLabel='{0} ({1:.0%})'.format(child.name,self.probabilities[i])
            graph.edge(str(self),str(child),label=myLabel)
        for child in self.children:
            child._drawEdges(graph)

    def graph(self,showValues=True,treeName='decision tree'):
        ''' Function to return a graphviz object that graphically represent the decision tree from this node
        Inputs:
            - showValues: True if draw the values; False if draw the shape only.
            - treeName: a name for the decision tree that is used by the underlying graphviz package.
        '''
        graph=Digraph(treeName)
        self._drawNodes(graph,showValues)
        self._drawEdges(graph)
        return graph


from flask import Flask, jsonify
from .api.v0_1 import v0_1

application = Flask(__name__)
versions = dict()
versions["versions"] = dict()

def add_version(blueprint, prefix):
    application.register_blueprint(blueprint, url_prefix=prefix)
    versions["versions"][blueprint.name] = prefix

add_version(v0_1, "/v0-1")

@application.route("/")
def summary():
    return jsonify(versions)

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


# A simple Python program for traversal of a linked list
# Node class
class Node:
    # Function to initialise the node object
    def __init__(self, data):
        self.data = data  # Assign data
        self.next = None  # Initialize next as null
# Linked List class contains a Node object
class LinkedList:
    # Function to initialize head
    def __init__(self):
        self.head = None

##################
## Main Methods ##
##################
def asgn3(*args):
    l1, l2, loutput = None, None, None
    if len(args) == 2:
        l1, l2 = args[0], args[1]
        loutput = addTwoLists(l1, l2)
    else:
        l1 = args[0]
        loutput = reverseListByWords(l1)
    printList(loutput)
    return loutput

def addTwoLists(l1, l2):
    ## Convert these to integers
    l1int, l2int = listToInt(l1), listToInt(l2)
    addedList = l1int + l2int
    return intToList(addedList)

def reverseListByWords(l):
    lString = listToStr(l)
    lArr = list(lString.split(' '))
    lArrRev = lArr[::-1]
    lStrRev = ' '.join(lArrRev)
    lArrRevMerge = list(lStrRev)
    return arrToList(lArrRevMerge, 'str')

#######################
## From List Methods ##
#######################
def listToInt(l):
    return int(listToStr(l))

def listToStr(l):
    lString = ''
    currNode = l.head
    while (currNode.next != None):
        lString += str(currNode.data)
        currNode = currNode.next
    lString += str(currNode.data)
    return lString

#####################
## To List Methods ##
#####################
def strToList(string):
    return arrToList(string, 'str')

def intToList(i):
    iString = str(i)
    iArr= list(iString)
    return arrToList(iArr, 'int')

def arrToList(arr, operationType):
    arrList = LinkedList()
    if operationType == 'int':
        arrList.head = Node(int(arr[0]))
    elif operationType == 'str':
        arrList.head = Node(str(arr[0]))
    currNode = arrList.head
    for data in arr[1:]:
        if operationType == 'int':
            currNode.next = Node(int(data))
        elif operationType == 'str':
            currNode.next = Node(str(data))
        currNode = currNode.next
    return arrList

#############
## Printer ##
#############
def printList(l):
    currNode = l.head
    while (currNode.next != None):
        print(currNode.data)
        currNode = currNode.next
    print(currNode.data)

def main():
    arr1, arr2 = [1, 2, 3, 4], [1, 2, 3, 4]
    intl1, intl2 = arrToList(arr1, 'int'), arrToList(arr2, 'int')

    string = 'my name is jorge canedo'
    strl1 = strToList(string)

    asgn3(intl1, intl2)
    print()
    asgn3(strl1)

if __name__ == '__main__':
    main()


from __future__ import print_function

import compas
import compas_rhino

from compas.utilities import geometric_key

from compas_rhino.geometry import RhinoSurface

from compas_rhino.artists import MeshArtist

from compas_rhino.modifiers import Modifier
from compas_rhino.modifiers import VertexModifier
from compas_rhino.modifiers import EdgeModifier
from compas_rhino.modifiers import FaceModifier

from compas_rhino.selectors import VertexSelector
from compas_rhino.selectors import EdgeSelector
from compas_rhino.selectors import FaceSelector

try:
    import Rhino
    import scriptcontext as sc
    import rhinoscriptsyntax as rs

except ImportError:
    compas.raise_if_ironpython()

__all__ = [
    'mesh_from_guid',
    'mesh_from_surface',
    'mesh_from_surface_uv',
    'mesh_from_surface_heightfield',

    'mesh_draw',
    'mesh_draw_vertices',
    'mesh_draw_edges',
    'mesh_draw_faces',
    'mesh_draw_vertex_labels',
    'mesh_draw_edge_labels',
    'mesh_draw_face_labels',

    'mesh_select_vertices',
    'mesh_select_vertex',
    'mesh_select_edges',
    'mesh_select_edge',
    'mesh_select_faces',
    'mesh_select_face',

    'mesh_update_vertex_attributes',
    'mesh_update_edge_attributes',
    'mesh_update_face_attributes',
    'mesh_move_vertex',
    'mesh_move_vertices',
    'mesh_identify_vertices',
]

# ==============================================================================
# constructors
# ==============================================================================

def mesh_from_guid(cls, guid):
    """Construct a mesh from a Rhino mesh.

    Parameters
    ----------
    cls : Mesh
        A mesh type.
    guid : str
        The GUID of the Rhino mesh.

    Returns
    -------
    Mesh
        A mesh object.

    """
    vertices, faces = compas_rhino.get_mesh_vertices_and_faces(guid)
    faces = [face[:-1] if face[-2] == face[-1] else face for face in faces]
    mesh  = cls.from_vertices_and_faces(vertices, faces)
    return mesh

def mesh_from_surface(cls, guid):
    """Construct a mesh from a Rhino surface.

    Parameters
    ----------
    cls : Mesh
        A mesh type.
    guid : str
        The GUID of the Rhino surface.

    Returns
    -------
    Mesh
        A mesh object.

    """
    gkey_xyz = {}
    faces = []
    obj = sc.doc.Objects.Find(guid)

    if not obj.Geometry.HasBrepForm:
        return

    brep = Rhino.Geometry.Brep.TryConvertBrep(obj.Geometry)

    for loop in brep.Loops:
        curve = loop.To3dCurve()
        segments = curve.Explode()
        face = []
        sp = segments[0].PointAtStart
        ep = segments[0].PointAtEnd
        sp_gkey = geometric_key(sp)
        ep_gkey = geometric_key(ep)
        gkey_xyz[sp_gkey] = sp
        gkey_xyz[ep_gkey] = ep
        face.append(sp_gkey)
        face.append(ep_gkey)

        for segment in segments[1:-1]:
            ep = segment.PointAtEnd
            ep_gkey = geometric_key(ep)
            face.append(ep_gkey)
            gkey_xyz[ep_gkey] = ep

        faces.append(face)

    gkey_index = {gkey: index for index, gkey in enumerate(gkey_xyz)}
    vertices = [list(xyz) for gkey, xyz in gkey_xyz.items()]
    faces = [[gkey_index[gkey] for gkey in f] for f in faces]
    mesh = cls.from_vertices_and_faces(vertices, faces)

    return mesh

def mesh_from_surface_uv(cls, guid, density=(10, 10)):
    """Construct a mesh from a point cloud aligned with the uv space of a Rhino NURBS surface.

    Parameters
    ----------
    cls : Mesh
        The mesh type.
    guid : str
        The GUID of the surface.
    density : tuple
        The density of the point grid in the u and v directions.

    Returns
    -------
    Mesh
        A mesh object.

    See Also
    --------
    * :class:`compas_rhino.geometry.RhinoSurface`

    Examples
    --------
    >>>

    """
    return mesh_from_surface_heightfield(cls, guid, density=density)

def mesh_from_surface_heightfield(cls, guid, density=(10, 10)):
    """Create a mesh data structure from a point grid aligned with the uv space of a Rhino NURBS surface.

    Parameters
    ----------
    cls : Mesh
        The mesh type.
    guid : str
        The GUID of the surface.
    density : tuple
        The density of the point grid in the u and v directions.

    Returns
    -------
    Mesh
        A mesh object.

    See Also
    --------
    * :class:`compas_rhino.geometry.RhinoSurface`

    Examples
    --------
    >>>

    """
    try:
        u, v = density
    except Exception:
        u, v = density, density

    surface = RhinoSurface(guid)

    mesh = cls()

    vertices = surface.heightfield(density=(u, v), over_space=True)

    for x, y, z in vertices:
        mesh.add_vertex(x=x, y=y, z=z)

    for i in range(u - 1):
        for j in range(v - 1):
            face = ((i + 0) * v + j,
                    (i + 0) * v + j + 1,
                    (i + 1) * v + j + 1,
                    (i + 1) * v + j)
            mesh.add_face(face)

    return mesh

# ==============================================================================
# drawing
# ==============================================================================

def mesh_draw(mesh,
              layer=None,
              clear_layer=False,
              clear_vertices=False,
              clear_faces=False,
              clear_edges=False,
              show_faces=True,
              show_vertices=False,
              show_edges=False,
              vertexcolor=None,
              edgecolor=None,
              facecolor=None):
    """
    Draw a mesh object in Rhino.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        The mesh object.
    layer : str (None)
        The layer to draw in.
        Default is to draw in the current layer.
    clear_layer : bool (False)
        Clear the drawing layer.
    show_faces : bool (True)
        Draw the faces.
    show_vertices : bool (False)
        Draw the vertices.
    show_edges : bool (False)
        Draw the edges.
    vertexcolor : str, tuple, list, dict (None)
        The vertex color specification.
        Default is to use the color of the parent layer.
    edgecolor : str, tuple, list, dict (None)
        The edge color specification.
        Default is to use the color of the parent layer.
    facecolor : str, tuple, list, dict (None)
        The face color specification.
        Default is to use the color of the parent layer.

    Notes
    -----
    Colors can be specifiedin different ways:

    * str: A hexadecimal color that will be applied to all elements subject to the specification.
    * tuple, list: RGB color that will be applied to all elements subject to the specification.
    * dict: RGB or hex color dict with a specification for some or all of the related elements.

    Notes
    -----
    RGB colors specified as values between 0 and 255, should be integers.
    RGB colors specified as values between 0.0 and 1.0, should be floats.

    """
    artist = MeshArtist(mesh)
    artist.layer = layer

    if clear_layer:
        artist.clear_layer()

    if clear_vertices:
        artist.clear_vertices()
    if clear_edges:
        artist.clear_edges()
    if clear_faces:
        artist.clear_faces()

    if show_faces:
        artist.draw_faces(color=facecolor)
    if show_edges:
        artist.draw_edges(color=edgecolor)
    if show_vertices:
        artist.draw_vertices(color=vertexcolor)

    artist.redraw()

def mesh_draw_vertices(mesh,
                       keys=None,
                       color=None,
                       layer=None,
                       clear_layer=False,
                       clear_vertices=False,
                       redraw=True):
    """Draw a selection of vertices of the mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    keys : list (None)
        A list of vertex keys identifying which vertices to draw.
        Default is to draw all vertices.
    color : str, tuple, dict (None)
        The color specififcation for the vertices.
        Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
        To apply the same color to all vertices, provide a single color specification.
        Individual colors can be assigned using a dictionary of key-color pairs.
        Missing keys will be assigned the default vertex color (``self.defaults['vertex.color']``).
        Default is use the color of the parent layer.
    layer : str (None)
        The layer in which the vertices are drawn.
        Default is to draw in the current layer.
    clear_layer : bool (False)
        Clear the drawing layer.
    redraw : bool (True)
        Redraw the view after adding the vertices.

    Notes
    -----
    The vertices are named using the following template:
    ``"{}.vertex.{}".format(self.mesh.attributes['name'], key)``.
    This name is used afterwards to identify vertices of the meshin the Rhino model.

    Examples
    --------
    >>>

    """
    artist = MeshArtist(mesh)
    artist.layer = layer

    if clear_layer:
        artist.clear_layer()

    if clear_vertices:
        artist.clear_vertices()

    guids = artist.draw_vertices(color=color)

    if redraw:
        artist.redraw()

    return guids

def mesh_draw_edges(mesh,
                    keys=None,
                    color=None,
                    layer=None,
                    clear_layer=False,
                    redraw=True):
    """Draw a selection of edges of the mesh.

    Parameters
    ----------
    keys : list
        A list of edge keys (as uv pairs) identifying which edges to draw.
        Default is to draw all edges.
    color : str, tuple, dict
        The color specififcation for the edges.
        Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
        To apply the same color to all faces, provide a single color specification.
        Individual colors can be assigned using a dictionary of key-color pairs.
        Missing keys will be assigned the default face color (``self.defaults['face.color']``).
        Default is use the color of the parent layer.
    layer : str (None)
        The layer in which the edges are drawn.
        Default is to draw in the current layer.
    clear_layer : bool (False)
        Clear the drawing layer.
    redraw : bool (True)
        Redraw the view after adding the edges.

    Notes
    -----
    All edges are named using the following template:
    ``"{}.edge.{}-{}".fromat(self.mesh.attributes['name'], u, v)``.
    This name is used afterwards to identify edges of the mesh in the Rhino model.

    Examples
    --------
    >>> mesh_draw_edges(mesh)
    >>> mesh_draw_edges(mesh, color='#ff0000')
    >>> mesh_draw_edges(mesh, color=(255, 0, 0))
    >>> mesh_draw_edges(mesh, keys=mesh.edges_on_boundary())
    >>> mesh_draw_edges(mesh, color={(u, v): '#00ff00' for u, v in mesh.edges_on_boundary()})

    """
    artist = MeshArtist(mesh)
    artist.layer = layer

    if clear_layer:
        artist.clear_layer()

    artist.clear_edges()
    guids = artist.draw_edges(color=color)

    if redraw:
        artist.redraw()

    return guids

def mesh_draw_faces(mesh,
                    keys=None,
                    color=None,
                    layer=None,
                    clear_layer=False,
                    clear_faces=False,
                    redraw=True,
                    join_faces=False):
    """Draw a selection of faces of the mesh.

    Parameters
    ----------
    keys : list (None)
        A list of face keys identifying which faces to draw.
        Default is to draw all faces.
    color : str, tuple, dict (None)
        The color specififcation for the faces.
        Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
        To apply the same color to all faces, provide a single color specification.
        Individual colors can be assigned using a dictionary of key-color pairs.
        Missing keys will be assigned the default face color (``self.defaults['face.color']``).
        Default is to use the color of the parent layer.
    layer : str (None)
        The layer in which the edges are drawn.
        Default is to draw in the current layer.
    clear_layer : bool (False)
        Clear the drawing layer.
    redraw : bool (True)
        Redraw the view after adding the edges.
    join_faces : bool (False)
        Join the faces into a polymesh object.

    Notes
    -----
    The faces are named using the following template:
    ``"{}.face.{}".format(self.mesh.attributes['name'], key)``.
    This name is used afterwards to identify faces of the mesh in the Rhino model.

    Examples
    --------
    >>>

    """
    artist = MeshArtist(mesh)
    artist.layer = layer

    if clear_layer:
        artist.clear_layer()

    if clear_faces:
        artist.clear_faces()

    guids = artist.draw_faces(color=color)

    if redraw:
        artist.redraw()

    if join_faces:
        guid = rs.JoinMeshes(guids, delete_input=True)
        return guid

    return guids

def mesh_draw_vertex_labels(mesh,
                            attr_name=None,
                            layer=None,
                            color=None,
                            formatter=None):
    """Draw labels for the vertices of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    attr_name : str (None)
        The name of the attribute value to display in the label.
        Default is is to display the vertex key.
    layer : str (None)
        The layer to draw in.
        Default is to draw in the current layer.
    color : str, tuple, list, dict (None)
        The color specififcation for the labels.
        Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
        To apply the same color to all face labels, provide a single color specification.
        Individual colors can be assigned using a dictionary of key-color pairs.
        Missing keys will be assigned the default vertex color (``self.defaults['vertex.color']``).
        Default is to inherit color from the parent layer.
    formatter : callable (None)
        A formatting function.
        Defaults to the built-in ``str`` function.

    Notes
    -----
    The labels are named using the following template:
    ``"{}.vertex.label.{}".format(self.mesh.name, key)``.
    This name is used afterwards to identify vertices of the meshin the Rhino model.

    Examples
    --------
    >>>

    """
    if not attr_name:
        attr_name = 'key'

    if formatter:
        assert callable(formatter), 'The provided formatter is not callable.'
    else:
        formatter = str

    text = {}
    for index, (key, attr) in enumerate(mesh.vertices(True)):
        if 'key' == attr_name:
            value = key
        elif 'index' == attr_name:
            value = index
        else:
            value = attr[attr_name]
        text[key] = formatter(value)

    artist = MeshArtist(mesh)
    artist.layer = layer
    artist.clear_vertexlabels()
    artist.draw_vertexlabels(text=text, color=color)
    artist.redraw()

def mesh_draw_edge_labels(mesh, attr_name=None, layer=None, color=None, formatter=None):
    """Display labels for the edges of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    attr_name : str (None)
        The name of the attribute value to display in the label.
        Default is to display the edge keys.
    layer : str (None)
        The layer to draw in.
        Default is to draw in the current layer.
    color : str, tuple, list, dict (None)
        The color specififcation for the labels.
        Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
        To apply the same color to all face labels, provide a single color specification.
        Individual colors can be assigned using a dictionary of key-color pairs.
        Missing keys will be assigned the default edge color (``self.defaults['edge.color']``).
        Default is to inherit color from the parent layer.
    formatter : callable (None)
        A formatting function.
        Defaults to the built-in ``str`` function.

    Notes
    -----
    The labels are named using the following template:
    ``"{}.edge.label.{}".format(self.mesh.name, key)``.
    This name is used afterwards to identify edges of the mesh in the Rhino model.

    Examples
    --------
    >>>

    """

    if not attr_name:
        attr_name = 'key'

    if formatter:
        assert callable(formatter), 'The provided formatter is not callable.'
    else:
        formatter = str

    text = {}
    for index, (u, v, attr) in enumerate(mesh.vertices(True)):
        if 'key' == attr_name:
            value = '{}-{}'.format(u, v)
        elif 'index' == attr_name:
            value = index
        else:
            value = attr[attr_name]
        text[(u, v)] = formatter(value)

    artist = MeshArtist(mesh)
    artist.layer = layer
    artist.clear_edgelabels()
    artist.draw_edgelabels(text=text, color=color)
    artist.redraw()

def mesh_draw_face_labels(mesh,
                          attr_name=None,
                          layer=None,
                          color=None,
                          formatter=None):
    """Display labels for the faces of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    attr_name : str (None)
        The name of the attribute value to display in the label.
        Default is is to display the face key.
    layer : str (None)
        The layer to draw in.
        Default is to draw in the current layer.
    color : str, tuple, list, dict (None)
        The color specififcation for the labels.
        Colors should be specified in the form of a string (hex colors) or as a tuple of RGB components.
        To apply the same color to all face labels, provide a single color specification.
        Individual colors can be assigned using a dictionary of key-color pairs.
        Missing keys will be assigned the default face color (``self.defaults['face.color']``).
        Default is to inherit color from the parent layer.
    formatter : callable (None)
        A formatting function.
        Defaults to the built-in ``str`` function.

    Notes
    -----
    The labels are named using the following template:
    ``"{}.face.label.{}".format(self.mesh.name, key)``.
    This name is used afterwards to identify faces of the meshin the Rhino model.

    Examples
    --------
    >>>

    """
    if not attr_name:
        attr_name = 'key'

    if formatter:
        assert callable(formatter), 'The provided formatter is not callable.'
    else:
        formatter = str

    text = {}
    for index, (key, attr) in enumerate(mesh.faces(True)):
        if 'key' == attr_name:
            value = key
        elif 'index' == attr_name:
            value = index
        else:
            value = attr[attr_name]
        text[key] = formatter(value)

    artist = MeshArtist(mesh)
    artist.layer = layer
    artist.clear_facelabels()
    artist.draw_facelabels(text=text, color=color)
    artist.redraw()

# ==============================================================================
# selections
# ==============================================================================

def mesh_select_vertices(mesh, message="Select mesh vertices."):
    """Select vertices of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    message : str ("Select mesh vertices.")
        The message to display to the user.

    Returns
    -------
    list
        The keys of the selected vertices.

    See Also
    --------
    * :func:`mesh_select_edges`
    * :func:`mesh_select_faces`

    """
    return VertexSelector.select_vertices(mesh)

def mesh_select_vertex(mesh, message="Select a mesh vertex"):
    """Select one vertex of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    message : str ("Select a mesh vertex.")
        The message to display to the user.

    Returns
    -------
    hashable
        The key of the selected vertex.

    See Also
    --------
    * :func:`mesh_select_vertices`

    """
    return VertexSelector.select_vertex(mesh)

def mesh_select_edges(mesh, message="Select mesh edges"):
    """Select edges of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    message : str ("Select mesh edges.")
        The message to display to the user.

    Returns
    -------
    list
        The keys of the selected edges.

    See Also
    --------
    * :func:`mesh_select_vertices`
    * :func:`mesh_select_faces`

    """
    return EdgeSelector.select_edges(mesh)

def mesh_select_edge(mesh, message="Select a mesh edge"):
    """Select one edge of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    message : str ("Select a mesh edge.")
        The message to display to the user.

    Returns
    -------
    tuple
        The key of the selected edge.

    See Also
    --------
    * :func:`mesh_select_edges`

    """
    return EdgeSelector.select_edge(mesh)

def mesh_select_faces(mesh, message='Select mesh faces.'):
    """Select faces of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    message : str ("Select mesh faces.")
        The message to display to the user.

    Returns
    -------
    list
        The keys of the selected faces.

    See Also
    --------
    * :func:`mesh_select_vertices`
    * :func:`mesh_select_edges`

    """
    return FaceSelector.select_faces(mesh)

def mesh_select_face(mesh, message='Select face.'):
    """Select one face of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    message : str ("Select a mesh face.")
        The message to display to the user.

    Returns
    -------
    hashable
        The key of the selected face.

    See Also
    --------
    * :func:`mesh_select_faces`

    """
    return FaceSelector.select_face(mesh)

# ==============================================================================
# modifications
# ==============================================================================

def mesh_update_attributes(mesh):
    """Update the attributes of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.

    Returns
    -------
    bool
        ``True`` if the update was successful.
        ``False`` otherwise.

    See Also
    --------
    * :func:`mesh_update_vertex_attributes`
    * :func:`mesh_update_edge_attributes`
    * :func:`mesh_update_face_attributes`

    """
    return Modifier.update_attributes(mesh)

def mesh_update_vertex_attributes(mesh, keys, names=None):
    """Update the attributes of the vertices of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    keys : tuple, list
        The keys of the vertices to update.
    names : tuple, list (None)
        The names of the atrtibutes to update.
        Default is to update all attributes.

    Returns
    -------
    bool
        ``True`` if the update was successful.
        ``False`` otherwise.

    See Also
    --------
    * :func:`mesh_update_attributes`
    * :func:`mesh_update_edge_attributes`
    * :func:`mesh_update_face_attributes`

    """
    return VertexModifier.update_vertex_attributes(mesh, keys, names=names)

def mesh_move_vertex(mesh, key, constraint=None, allow_off=False):
    """Move on vertex of the mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    key : str
        The vertex to move.
    constraint : Rhino.Geometry (None)
        A Rhino geometry object to constrain the movement to.
        By default the movement is unconstrained.
    allow_off : bool (False)
        Allow the vertex to move off the constraint.

    """
    return VertexModifier.move_vertex(mesh, key, constraint=constraint, allow_off=allow_off)

def mesh_move_vertices(mesh, keys):
    """Move on vertices of the mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    keys : list
        The vertices to move.
    constraint : Rhino.Geometry (None)
        A Rhino geometry object to constrain the movement to.
        By default the movement is unconstrained.
    allow_off : bool (False)
        Allow the vertex to move off the constraint.

    """
    return VertexModifier.move_vertices(mesh, keys)

def mesh_update_edge_attributes(mesh, keys, names=None):
    """Update the attributes of the edges of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    keys : tuple, list
        The keys of the edges to update.
    names : tuple, list (None)
        The names of the atrtibutes to update.
        Default is to update all attributes.

    Returns
    -------
    bool
        ``True`` if the update was successful.
        ``False`` otherwise.

    See Also
    --------
    * :func:`mesh_update_attributes`
    * :func:`mesh_update_vertex_attributes`
    * :func:`mesh_update_face_attributes`

    """
    return EdgeModifier.update_edge_attributes(mesh, keys, names=names)

def mesh_update_face_attributes(mesh, fkeys, names=None):
    """Update the attributes of the faces of a mesh.

    Parameters
    ----------
    mesh : compas.datastructures.Mesh
        A mesh object.
    fkeys : tuple, list
        The keys of the faces to update.
    names : tuple, list (None)
        The names of the atrtibutes to update.
        Default is to update all attributes.

    Returns
    -------
    bool
        ``True`` if the update was successful.
        ``False`` otherwise.

    See Also
    --------
    * :func:`mesh_update_attributes`
    * :func:`mesh_update_vertex_attributes`
    * :func:`mesh_update_edge_attributes`

    """
    return FaceModifier.update_vertex_attributes(mesh, fkeys, names=names)

# ==============================================================================
# identify
# ==============================================================================

def mesh_identify_vertices(mesh, points, precision=None):
    keys = []
    gkey_key = {geometric_key(mesh.vertex_coordinates(key), precision): key for key in mesh.vertices()}
    for xyz in points:
        gkey = geometric_key(xyz, precision)
        if gkey in gkey_key:
            key = gkey_key[gkey]
            keys.append(key)
    return keys

# ==============================================================================
# Main
# ==============================================================================

if __name__ == "__main__":

    import compas
    from compas.datastructures import Mesh
    from compas_rhino import mesh_draw
    from compas_rhino import mesh_select_vertex
    from compas_rhino import mesh_move_vertex

    mesh = Mesh.from_obj(compas.get_data('quadmesh_planar.obj'))

    mesh_draw(mesh, layer='test', clear_layer=True)


import torch
import time
from torch.autograd import Variable
import numpy as np

def mAP(bicode, label):
    if type(bicode)==torch.autograd.variable.Variable:
        bicode=bicode.data
    if type(label)==torch.autograd.variable.Variable:
        label=label.data
    bicode = torch.sign(bicode.cpu()).type(torch.FloatTensor)
    label = label.cpu()
    sampleNum = label.size(0)

    hashingDistance = -torch.mm(bicode, bicode.transpose(0,1))
    sorted, indices = torch.sort(hashingDistance)
    sorted_distance_labels = torch.gather(torch.stack([label]*sampleNum),1,indices)
    print('1')
    sorted_sim_matrix = (torch.stack([label]*sampleNum).transpose(0,1)==sorted_distance_labels).type(torch.FloatTensor)
    sorted_sim_matrix[:,0] = 0
    rank_matrix = torch.mm(sorted_sim_matrix.type(torch.FloatTensor), torch.FloatTensor(np.triu(np.ones([sampleNum,sampleNum])))) * sorted_sim_matrix
    print(1)
    tmp = torch.FloatTensor([list(range(sampleNum))]*sampleNum)
    tmp[:,0] = 1
    mapvalue = ((rank_matrix/tmp).sum(1)/(sorted_sim_matrix.sum(1)+1e-7)).sum()/float(sampleNum)
    return mapvalue

# cuda verison is smaller than cpu version
# have no idea why this happend now
def mAP_cuda(bicode, label):
    bicode = torch.sign(bicode).type(torch.cuda.FloatTensor)
    laebl = label.type(torch.cuda.FloatTensor)

    sampleNum = label.size(0)

    hashingDistance = -torch.mm(bicode, bicode.transpose(0,1))
    sorted, indices = torch.sort(hashingDistance)

    sorted_distance_labels = torch.gather(torch.stack([label]*sampleNum),1,indices)

    sorted_sim_matrix = (torch.stack([label]*sampleNum).transpose(0,1)==sorted_distance_labels).type(torch.cuda.FloatTensor)
    sorted_sim_matrix[:,0] = 0

    rank_matrix = torch.mm(sorted_sim_matrix, Variable(torch.FloatTensor(np.triu(np.ones([sampleNum,sampleNum])))).cuda()) * sorted_sim_matrix

    tmp = Variable(torch.FloatTensor([list(range(sampleNum))]*sampleNum)).cuda()
    tmp[:,0] = 1
    mapvalue = ((rank_matrix/tmp).sum(1)/(sorted_sim_matrix.sum(1)+1e-7)).sum()/float(sampleNum)
    mapvalue = mapvalue.cpu().data[0]

    return mapvalue

# mapvalue = mAP(bicode, label)


from flask import Flask, render_template, redirect
from flask_pymongo import pymongo
import scrape_mars

# Create instance of Flask app
app = Flask(__name__)

# Flask_pymongo to set up mongo connection
mongo = PyMongo(app, uri="mongodb://localhost:27017/mars_app")

# Create route that renders index.html template
@app.route("/")
def index():
    # Find one record of data from the mongo mars database
    mars_data = mongo.db.mars_data.find_one()

    # Return template and data
    return render_template("index.html, mars_data=mars_data")

# Create route that triggers the scrape function
@app.route("/scrape")
def scrape():

    # Run the scrape function
    mars_data = mongo.db.mars_data
    mars_data_scrape = scrape_mars.scrape()

    # Update mongo database using update and upsert=True
    mars_data.update({}, mars_data_scrape, upsert=True)

    # Redirect back to home page
    return redirect("/", code=302)

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


#!/usr/bin/env python3
"""
Zombies agent.
Copyright (C) 2014, <<<<<<<<<<< YOUR NAMES HERE >>>>>>>>>>>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.

"""

import zombies
import minimax

class Agent(zombies.Agent, minimax.Game):
    """This is the skeleton of an agent to play the Zombies game."""

    def __init__(self, name="Agent"):
        self.name = name
        self.player = zombies.PLAYER1

    def successors(self, state):
        """The successors function must return (or yield) a list of
        pairs (a, s) in which a is the action played to reach the
        state s; s is the new state, i.e. a triplet (b, p, st) where
        b is the new board after the action a has been played,
        p is the player to play the next move and st is the next
        step number.
        """
        actions = state[0].get_actions(state[1], state[2])
        for a in actions:
            newState = self.apply_action(state, a)
            yield a, newState

    def apply_action(self, state, action):
        import zombies

        newBoard= state[0].clone()

        if action[0] == 'P':
            newBoard.place_piece(action[1], action[2], state[1])
        elif action[0] == 'M':
            newBoard.move_piece(action[1], action[2], state[1])
        else:
            pass

        if state[1] is zombies.PLAYER1:
            newPlayer = zombies.PLAYER2
        else:
            newPlayer = zombies.PLAYER1
        newStep = state[2]+1

        return (newBoard, newPlayer, newStep)

    def cutoff(self, state, depth):
        """The cutoff function returns true if the alpha-beta/minimax
        search has to stop; false otherwise.
        """
        return depth >= 2 or state[0].is_finished()

    def evaluate(self, state):
        """The evaluate function must return an integer value
        representing the utility function of the board.
        """
        import zombies

        board = state[0]
        if self.player == zombies.PLAYER1:
            if board.get_score(self.player) > board.get_score(zombies.PLAYER2):
                return 1
            elif board.get_score(self.player) < board.get_score(zombies.PLAYER2):
                return -1
            else:
                return 0
        else:
            if board.get_score(self.player) > board.get_score(zombies.PLAYER1):
                return 1
            elif board.get_score(self.player) < board.get_score(zombies.PLAYER1):
                return -1
            else:
                return 0

    def play(self, board, player, step, time_left):
        """This function is used to play a move according
        to the board, player and time left provided as input.
        It must return an action representing the move the player
        will perform.
        """
        import minimax
        self.player = player
        self.time_left = time_left
        state = (board, player, step)
        return minimax.search(state, self)

if __name__ == "__main__":
    zombies.agent_main(Agent())


#!/usr/bin/env python
import website.bigfoot.models as models
from website.bigfoot.utils import config, siteaction, ajaxian, mailman, dataplus
import datetime

def handle(request):
    try:
        logged_in_type = siteaction.getLoggedInAccountType(request)
        if logged_in_type == 'U':
            myself = siteaction.getLoggedInUser(request)
        elif logged_in_type == 'R':
            myself = siteaction.getLoggedInRecruiter(request)
        else:
            return ajaxian.getFailureResp('not_logged_in')

        quest_to_user = dataplus.dictGetVal(request.REQUEST, 'questToUser')
        question_text = dataplus.dictGetSafeVal(request.REQUEST, 'question')

        question = models.ResumeQuestion()
        question.sender = myself.account
        question.receiver = models.User.objects.get(username=quest_to_user)
        question.question = question_text
        question.answer = ''
        question.is_answered = False
        question.is_public = False
        question.sent_at = datetime.datetime.utcnow()
        question.save()

        html_message = myself.name + ' wants to know more about your resume and has asked this question, "' + \
            question_text + '"

You may want to Answer this question'

        text_message = myself.name + ' wants to know more about your resume and has asked this question, "' + \
            question_text + '"\r\n\r\nYou can answer this question by visiting this url: ' + \
            config.server_base_url + '/me/answerresumequestion.htm?qid=' + str(question.id)

        def internalSender(rcvr_accounts):
            mailman.sendToInbox(myself.username, rcvr_accounts[0].username, 'A question for you!', html_message, 'TM', 'H')

        def externalSender(rcvr_accounts):
            sender = '"' + myself.name + '" <' + myself.username + '-profile@socialray.org>'
            receivers = ['"' + rcvr.name + '" <' + rcvr.email + '>'  for rcvr in rcvr_accounts]
            mailman.sendMail(sender, receivers, 'A question for you!', html_message,
                None, None, text_message, reply_to=myself.email)

        mailman.sendBySettings([question.receiver.account], internalSender, externalSender, 'ResumeQuestion')

        return ajaxian.getSuccessResp('')
    except:
        return ajaxian.getFailureResp('unknown')


#encoding:utf-8
import datetime

from django.utils import simplejson
from django.db.models import Q

from dajaxice.decorators import dajaxice_register
from dajaxice.utils import deserialize_form
from dajax.core import Dajax

from Programas.models import TipoSeguro, SubTipoSeguro, Programa, Cobertura, CoberturaPrograma, AreaInfluenciaPrograma
from ConexosAgropecuarios.models import AreaInfluencia, Municipio, Persona
from Programas.forms import ProgramaForm
from ConexosAgropecuarios.models import ContratoFondo,Moneda
from Cotizador.models import Cotizador

@dajaxice_register
def cargar_Combo_TipoSeguro(request): # Método que busca los tipos de seguro y los carga en el combo IdTipoSeguro.
    dajax = Dajax()
    tiposSeguros = TipoSeguro.objects.using('catalogos').all()

    out = []
    out.append("<option value='#'>%s</option>" % "---------")
    for tipo in tiposSeguros:
        out.append("<option value='" + str(tipo.IdTipoSeguro) + "'>%s</option>" % tipo.DescripcionTipoSeguro)

    dajax.assign('#IdTipoSeguro', 'innerHTML', ''.join(out))

    return dajax.json()

@dajaxice_register
def cargar_Combo_SubTipoSeguro(request, idTipoSeguro): # Método que busca los sub tipos de seguro pasandole el id del tipo de seguro
    dajax = Dajax()
    subTipoSeguros = SubTipoSeguro.objects.using('catalogos').filter(TipoSeguro_id = idTipoSeguro)

    out = []
    for subTipo in subTipoSeguros:
        out.append("<option value='" + str(subTipo.IdSubTipoSeguro) + "'>%s</option>" % subTipo.DescripcionSubTipoSeguro)

    dajax.assign('#IdSubTipoSeguro', 'innerHTML', ''.join(out))

    return dajax.json()

@dajaxice_register
def cargar_Combo_Coberturas(request, idTipoSeguro): # Método que busca las coberturas ligadas al id tipo seguro.
    dajax = Dajax()
    try:
        coberturasTipoSeguro = Cobertura.objects.using('catalogos').filter(TipoSeguro_id = idTipoSeguro)
        datos = list()

        for cobertura in coberturasTipoSeguro:
            datos.append({'IdCobertura':cobertura.IdCobertura, 'Descripcion':cobertura.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'coberturas':datos})

@dajaxice_register
def guardar_programas(request, formulario, coberturas, folio, areaInfluencia):# Método que recibe el formulario de programas obtenido de programa.html y lo deserializa para obtener la información de sus controles y lo valida con ProgramaForm, si la información es valida guarda los datos y limpia los controles del formulario mediante una función de js.
    dajax = Dajax()

    formulario_deserializado = deserialize_form(formulario)

    datos = {'IdTipoSeguro':formulario_deserializado.get('IdTipoSeguro'), 'IdSubTipoSeguro':formulario_deserializado.get('IdSubTipoSeguro'),
             'IdTipoMoneda':formulario_deserializado.get('IdTipoMoneda'), 'Ejercicio':formulario_deserializado.get('Ejercicio'),
             'Observaciones':formulario_deserializado.get('Observaciones'), 'PersonaHabilitador': formulario_deserializado.get('varIdHabilitador')}
    formulario = ProgramaForm(datos)

    if formulario.is_valid():

        if formulario_deserializado.get('varIdPrograma') == '':

            fechaPrograma = datetime.datetime.now()

            programaAGuardar = Programa(IdTipoSeguro = formulario_deserializado.get('IdTipoSeguro'), IdSubTipoSeguro = formulario_deserializado.get('IdSubTipoSeguro'),
                                      IdTipoMoneda = formulario_deserializado.get('IdTipoMoneda'), Ejercicio = formulario_deserializado.get('Ejercicio'),
                                      FechaPrograma = fechaPrograma, Observaciones = formulario_deserializado.get('Observaciones').upper(),
                                      IdContratoFondo = formulario_deserializado.get('IdContratoFondo'), Utilizado = 0, PersonaHabilitador_id = formulario_deserializado.get('varIdHabilitador'))
            programaAGuardar.save()

            folioAGuardar = folio.upper() + str(programaAGuardar.IdPrograma)

            Programa.objects.filter(IdPrograma = programaAGuardar.IdPrograma).update(FolioPrograma = folioAGuardar)

            for cobertura in coberturas:
                guardarCoberturas(cobertura, programaAGuardar.IdPrograma)

            for area in areaInfluencia:
                guardarAreaInfluencia(area, programaAGuardar.IdPrograma)

            dajax.add_data(folioAGuardar, 'mensajePrograma')

        else:
            actualizar_programa(formulario_deserializado, coberturas, areaInfluencia)
            dajax.script('manejadorMensajes(2);')

    else:
        dajax.alert('El formulario es invalido')

    return dajax.json()

def guardarCoberturas(cobertura, idPrograma): # Método que permite guardar las coberturas en la base de datos pasando el id del programa para enlazar.
    dajax = Dajax()

    cuberturaAGuardar = CoberturaPrograma(Programa_id = idPrograma, IdCobertura = cobertura)
    cuberturaAGuardar.save()

    return dajax.json()

def guardarAreaInfluencia(area, idPrograma): # Método que permite guardar el área de influencia de un programa.
    dajax = Dajax()

    areaInfluenciaAGuardar = AreaInfluenciaPrograma(Programa_id = idPrograma, IdAreaInfluencia = area)
    areaInfluenciaAGuardar.save()

    return dajax.json()

def actualizar_coberturas(coberturas, idPrograma): # Método que permite actualizar las coberturas en la base de datos.
    dajax = Dajax()

    coberturasGuardadas = CoberturaPrograma.objects.filter(Programa_id = idPrograma)

    encontradoAElimiar = 1
    for coberturaAEliminar in coberturasGuardadas:
        for coberturaABuscar in coberturas:
            if coberturaABuscar == coberturaAEliminar.IdCobertura:
                encontradoAElimiar = 0
                break
        if encontradoAElimiar == 1:
            eliminar_cobertura(coberturaAEliminar.IdCoberturaPrograma)

    coberturaAGuardar = 1
    for cobertura in coberturas:
        for coberturaEncontrada in coberturasGuardadas:
            if coberturaEncontrada.IdCobertura == cobertura:
                coberturaAGuardar = 0
                break

        if coberturaAGuardar == 1:
            guardarCoberturas(cobertura, idPrograma)

    return dajax.json()

def actualizar_area_influencia_programa(areaInfluencia, idPrograma): # Método que permite actualizar las coberturas en la base de datos.
    dajax = Dajax()

    areaInfluenciaGuardadas = AreaInfluenciaPrograma.objects.filter(Programa_id = idPrograma)

    encontradoAElimiar = 1
    for areaProgramaAEliminar in areaInfluenciaGuardadas:
        for area in areaInfluencia:
            if area == areaProgramaAEliminar.IdAreaInfluencia:
                encontradoAElimiar = 0
                break
        if encontradoAElimiar == 1:
            eliminar_area_influencia_programa(areaProgramaAEliminar.IdAreaInfluenciaPrograma)

    coberturaAGuardar = 1
    for area in areaInfluencia:
        for areaProgramaGuardada in areaInfluenciaGuardadas:
            if areaProgramaGuardada.IdAreaInfluencia == area:
                coberturaAGuardar = 0
                break
        if coberturaAGuardar == 1:
            guardarAreaInfluencia(area, idPrograma)

    return dajax.json()

@dajaxice_register
def eliminar_area_influencia_programa(idAreaInfluenciaPrograma): #Método que recibe el id cobertura programa para eliminarlo de la base de datos.
    dajax = Dajax()
    AreaInfluenciaPrograma.objects.filter(IdAreaInfluenciaPrograma = idAreaInfluenciaPrograma).delete()

    return dajax.json()

@dajaxice_register
def eliminar_cobertura(idCoberturaPrograma): #Método que recibe el id cobertura programa para eliminarlo de la base de datos.
    dajax = Dajax()
    CoberturaPrograma.objects.filter(IdCoberturaPrograma = idCoberturaPrograma).delete()

    return dajax.json()

def actualizar_programa(formularioPrograma, coberturas, areaInfluencia): # Método que permite actualizar los datos del programa.
    dajax = Dajax()

    Programa.objects.filter(IdPrograma = formularioPrograma.get('varIdPrograma')).update(
                            IdTipoSeguro = formularioPrograma.get('IdTipoSeguro'), IdSubTipoSeguro = formularioPrograma.get('IdSubTipoSeguro'),
                            Ejercicio = str(formularioPrograma.get('Ejercicio')), IdTipoMoneda = formularioPrograma.get('IdTipoMoneda'),
                            Observaciones = formularioPrograma.get('Observaciones').upper(), IdContratoFondo = formularioPrograma.get('IdContratoFondo'),
                            PersonaHabilitador = formularioPrograma.get('varIdHabilitador'))

    actualizar_coberturas(coberturas, formularioPrograma.get('varIdPrograma'))
    actualizar_area_influencia_programa(areaInfluencia, formularioPrograma.get('varIdPrograma'))

    return dajax.json()

@dajaxice_register
def obtener_programas(req): # Función que busca todos los programas ingresados a la base de datos para mostrarlos en el listado de programas.
    dajax = Dajax()
    try:
        datos = list()
        listaProgramas = Programa.objects.all().order_by("-IdPrograma")
        tieneCotizador = 0

        for programa in listaProgramas:
            tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0]
            subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0]
            contrato = ContratoFondo.objects.filter(IdContratoFondo = programa.IdContratoFondo)[0]
            cotizadores = Cotizador.objects.filter(Programa_id = programa.IdPrograma)

            if cotizadores:
                tieneCotizador = 1

            datos.append({'IdPrograma':programa.IdPrograma,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro,
            'Ejercicio':programa.Ejercicio,'IdTipoSeguro':programa.IdTipoSeguro,'IdSubTipoSeguro':programa.IdSubTipoSeguro,
            'IdTipoMoneda':programa.IdTipoMoneda,'Observaciones':programa.Observaciones,'NumeroContrato':contrato.NumeroContrato,'FolioPrograma':programa.FolioPrograma,
            'Utilizado':programa.Utilizado, 'TieneCotizador':int(tieneCotizador)})

    except:
        return dajax.json()

    return simplejson.dumps({'programas':datos})

@dajaxice_register
def obtener_areas_infuencia_fondo(req): # Función que busca todos los programas ingresados a la base de datos para mostrarlos en el listado de programas.
    dajax = Dajax()
    try:
        datos = list()
        listaAreaInfluencia = AreaInfluencia.objects.all()

        for areaInfluencia in listaAreaInfluencia:
            municipio = Municipio.objects.using('catalogos').filter(IdMunicipio = areaInfluencia.Municipio_id)[0]

            datos.append({'IdAreaInfluencia':areaInfluencia.IdAreaInfluencia,'Descripcion':municipio.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'areasInfluencia':datos})

@dajaxice_register
def buscar_programas_ejercicio_actual(req, buscarPrograma, tipoSolicitud): # Función que busca todos los programas con cotizador ingresados a la base de datos para mostrarlos en el listado de programas.
    dajax = Dajax()
    try:
        datos = list()
        year = datetime.datetime.now().year

        programasFiltrados = TipoSeguro.objects.using('catalogos').filter(Q(DescripcionTipoSeguro__contains = buscarPrograma))
        listaProgramas = Programa.objects.filter(Ejercicio = year, Utilizado=1)

        for programaFiltrado in programasFiltrados:
            for programa in listaProgramas:
                # tipoSolicitud = 1 ANUAL, tipoSolicitud = 2 A DECLARACION
                # ANUAL solo muestra los programas PATRIMONIAL y MAQUINARIA
                # A DECLARACION muestra programas PATRIMONIAL (BODEGAS, SILOS Y CONTENIDOS), TRANSPORTE Y RIESGOS ALGODONEROS
                if programaFiltrado.IdTipoSeguro == int(programa.IdTipoSeguro) and (((programaFiltrado.IdTipoSeguro == 1 or programaFiltrado.IdTipoSeguro == 3) and tipoSolicitud==1) or ((programaFiltrado.IdTipoSeguro == 1 or programaFiltrado.IdTipoSeguro == 2 or programaFiltrado.IdTipoSeguro == 4) and tipoSolicitud==2)):
                    tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0]
                    subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0]
                    contrato = ContratoFondo.objects.filter(IdContratoFondo = programa.IdContratoFondo)[0]
                    descripcionMoneda = Moneda.objects.using('catalogos').filter(IdMoneda = programa.IdTipoMoneda)[0]

                    datos.append({'IdPrograma':programa.IdPrograma,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro,
                    'Ejercicio':programa.Ejercicio,'IdTipoSeguro':programa.IdTipoSeguro,'IdSubTipoSeguro':programa.IdSubTipoSeguro, 'DescripcionMoneda':descripcionMoneda.Nombre,
                    'IdTipoMoneda':programa.IdTipoMoneda,'Observaciones':programa.Observaciones, 'NumeroContrato':contrato.NumeroContrato,'FolioPrograma':programa.FolioPrograma})

    except:
        return dajax.json()

    return simplejson.dumps({'programas':datos})

@dajaxice_register
def obtener_programas_ejercicio_actual(req): # Método ue busca todos los programas del ciclo actual pasandole el año.
    dajax = Dajax()

    try:
        datos = list()
        year = datetime.datetime.now().year
        programasEjercicioActual = Programa.objects.filter(Ejercicio = year, Utilizado = 0)

        for programa in programasEjercicioActual:
            tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0]
            subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0]
            descripcionMoneda = Moneda.objects.using('catalogos').filter(IdMoneda = programa.IdTipoMoneda)[0]

            datos.append({'IdPrograma':programa.IdPrograma,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro,
            'Ejercicio':programa.Ejercicio,'IdTipoMoneda':programa.IdTipoMoneda,'FolioPrograma':programa.FolioPrograma,'DescripcionMoneda':descripcionMoneda.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'programasActuales':datos})

@dajaxice_register
def buscar_programa(request, idPrograma): # Método que busca la información del programa pasandole el id del programa a buscar.
    dajax = Dajax()

    try:
        programasEncontrados = Programa.objects.filter(IdPrograma = idPrograma)
        datos = list()
        for programa in programasEncontrados:
            persona = Persona.objects.filter(IdPersona = programa.PersonaHabilitador_id)[0]
            contrato = ContratoFondo.objects.filter(IdContratoFondo = programa.IdContratoFondo)[0]
            tipoSeguro = TipoSeguro.objects.using('catalogos').filter(IdTipoSeguro = programa.IdTipoSeguro)[0]
            subTipoSeguro = SubTipoSeguro.objects.using('catalogos').filter(IdSubTipoSeguro = programa.IdSubTipoSeguro)[0]
            datos.append({'IdPrograma':programa.IdPrograma, 'IdTipoSeguro': programa.IdTipoSeguro,'IdSubSeguro':programa.IdSubTipoSeguro,
                          'IdTipoMoneda':programa.IdTipoMoneda, 'Ejercicio':programa.Ejercicio, 'Observaciones':programa.Observaciones,
                          'IdContratoFondo':programa.IdContratoFondo, 'Utilizado':programa.Utilizado, 'RazonSocial':persona.RazonSocial,
                          'IdPersona':persona.IdPersona, 'NumeroContrato':contrato.NumeroContrato,'TipoSeguro':tipoSeguro.DescripcionTipoSeguro,
                          'SubTipoSeguro':subTipoSeguro.DescripcionSubTipoSeguro, 'FolioPrograma':programa.FolioPrograma})

    except:
        return dajax.json()

    return simplejson.dumps({'programaEncontrado':datos})

@dajaxice_register
def buscar_cobertura_programa(request, idPrograma): # Método que busca la información del programa pasandole el id del programa a buscar.
    dajax = Dajax()

    try:
        coberturasPrograma = CoberturaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()
        for cobertura in coberturasPrograma:
            datos.append({'IdCobertura':cobertura.IdCobertura})

    except:
        return dajax.json()

    return simplejson.dumps({'coberturasprograma':datos})

@dajaxice_register
def buscar_cobertura_programa_descripcion(request, idPrograma): # Método que busca la información de las coberturas pasandole el id del programa a buscar.
    dajax = Dajax()

    try:
        coberturasPrograma = CoberturaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()
        for cobertura in coberturasPrograma:
            coberturaCatalogos = Cobertura.objects.using('catalogos').filter(IdCobertura = cobertura.IdCobertura)[0]
            datos.append({'Descripcion':coberturaCatalogos.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'coberturasprograma':datos})

@dajaxice_register
def buscar_area_influencia_descripcion(request, idPrograma): # Método que busca la información de las areas de influencia pasandole el id del programa a buscar.
    dajax = Dajax()

    try:
        areaInfluenciaPrograma = AreaInfluenciaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()
        for areaInfluencia in areaInfluenciaPrograma:
            areaCatalogo = AreaInfluencia.objects.filter(IdAreaInfluencia = areaInfluencia.IdAreaInfluencia)[0]
            municipio = Municipio.objects.using('catalogos').filter(IdMunicipio = areaCatalogo.Municipio_id)[0]
            datos.append({'Descripcion':municipio.Descripcion})

    except:
        return dajax.json()

    return simplejson.dumps({'areasInfluenciaDescripcion':datos})

@dajaxice_register
def obtener_cobertura_con_idprograma(req, idPrograma): # Método que obtiene de la base de datos las coberturas pasandole el id de programa y buscando la descripcion en los catalogos.
    dajax = Dajax()

    try:
        coberturasProgramas = CoberturaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()

        for coberturaPrograma in coberturasProgramas:
            coberturaCatalogo = Cobertura.objects.using('catalogos').filter(IdCobertura = coberturaPrograma.IdCobertura)[0]

            remocion = 0
            if coberturaPrograma.IdCobertura == 3:
                remocion = 1

            datos.append({'IdCoberturaPrograma':coberturaPrograma.IdCoberturaPrograma,'Descripcion':coberturaCatalogo.Descripcion, 'Remocion':remocion})

    except:
        return dajax.json()

    return simplejson.dumps({'coberturasPorPrograma':datos})

@dajaxice_register
def obtener_area_influencia_con_idprograma(req, idPrograma): # Método que obtiene de la base de datos el área de influencia del programa pasando el id del mismo.
    dajax = Dajax()

    try:
        areaInfluenciaPrograma = AreaInfluenciaPrograma.objects.filter(Programa_id = idPrograma)
        datos = list()

        for area in areaInfluenciaPrograma:
            datos.append({'IdAreaInfluenciaPrograma':area.IdAreaInfluenciaPrograma,'IdAreaInfluencia':area.IdAreaInfluencia})

    except:
        return dajax.json()

    return simplejson.dumps({'areaInfluenciaPrograma':datos})

@dajaxice_register
def eliminar_programa(request, idPrograma): #Función que permite eliminar el programa seleccionado de la base de datos.
    dajax = Dajax()
    Programa.objects.filter(IdPrograma = idPrograma).delete()

    return dajax.json()

@dajaxice_register
def programaUtilizado(request, idPrograma): #Función que permite verificar si un programa se encuentra con cotizador, la función devuelve un 0 si no esta utilizado y un 1 si esta utilizado.

    tieneCotizador = 0

    cotizadores = Cotizador.objects.filter(Programa_id = idPrograma)

    if cotizadores:
        tieneCotizador = 1

    return simplejson.dumps({'tieneCotizador':tieneCotizador})


__author__ = 'jsmorrison'
from dnd.management.config import config

from django.core.management.base import BaseCommand
from ...models import OscarCategories, Winners
import os
import pandas as pd
import datetime

# python manage.py oscar_csv_to_db

class Command(BaseCommand):
    def add_arguments(self, parser):
        pass

    def handle(self, *args, **options):
        self.add_oscar()
        self.add_place_holder_winners()

    def add_oscar(self):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        file_name = dir_path + "/../../static/oscar/csv/Oscars_2021.csv"

        df = pd.read_csv(file_name)
        df.columns = ["Year", "Cat", "Selection"]

        for index, row in df.iterrows():
            year = row["Year"]
            cat = row["Cat"]
            sel = row["Selection"].replace('“','').replace('”','').replace('"','')

            (oscar_instance, oscar) = OscarCategories.objects.update_or_create(
                Year =year,
                Cat = cat,
                Name = sel,
            )

    def add_place_holder_winners(self):
        now = datetime.datetime.now()
        y = str(now.year)

        catarr = {"Best Picture": 3, "Best Actor": 3, "Best Actress": 3, "Best Supporting Actor": 3, "Best Supporting Actress": 3,
                  "Best Director": 3, "Best Animated Feature": 3, "Best Animated Short": 1 , "Best Adapted Screenplay": 3, "Best Original Screenplay": 3,
                  "Best Cinematography": 2, "Best Documentary Feature": 2, "Best Live-Action Short Film": 1, "Best International Feature": 2,
                  "Best Film Editing": 2, "Best Sound": 2, "Best Production Design": 2,
                  "Best Original Score": 2, "Best Original Song": 2, "Best Hair and Makeup": 2, "Best Costume Design": 2, "Best Visual Effects": 2,
                  "Best Documentary Short Subject": 1}

        for key,val in catarr.items():
            (oscar_instance, oscar) = Winners.objects.update_or_create(
                Year=y,
                Cat=key,
                Name="NA",
                Weight = val,
            )


# uncompyle6 version 3.7.4
# Python bytecode 2.6 (62161)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-i686/egg/coils/logic/foundation/set_acl.py
# Compiled at: 2012-10-12 07:02:39
from sqlalchemy import *
from coils.core import *
from get_access import NO_ACL_ENTITIES

class SetACL(Command):
    __domain__ = 'object'
    __operation__ = 'set-acl'

    def __init__(self):
        Command.__init__(self)

    def parse_parameters(self, **params):
        Command.parse_parameters(self, **params)
        if 'object' in params or 'id' in params:
            if 'object' in params:
                self._object_id = params.get('object').object_id
                self.obj = params.get('object')
            else:
                self._object_id = int(params.get('id'))
                self.obj = None
        else:
            raise CoilsException('No object specified for ACL creation.')
        self._permissions = params.get('permissions', 'r')
        if self._permissions:
            self._permissions = self._permissions.lower().strip()
        else:
            self._permissions = None
        self._context_id = int(params.get('context_id', self._ctx.account_id))
        self._action = params.get('action', 'allowed').lower().strip()
        return

    def run(self, **params):
        if self.obj:
            kind = self.obj.__entityName__
        else:
            kind = self._ctx.type_manager.get_type(self._object_id)
        db = self._ctx.db_session()
        if kind == 'Project':
            if self._action != 'allowed':
                raise CoilsException('Access revocation not supported on Project entities.')
            acls = db.query(ProjectAssignment).filter(and_(ProjectAssignment.parent_id == self._object_id, ProjectAssignment.child_id == self._context_id)).all()
            if len(acls) == 0:
                db.add(ProjectAssignment(self._object_id, self._context_id, permissions=self._permissions, info=None))
                self.set_result(True)
            elif len(acls) == 1:
                acls[0].rights = self._permissions
                self.set_result(True)
            else:
                raise CoilsException('Inconsistency detected in ProjectAssignment data; multiple results.')
                self.set_result(False)
        elif kind == 'Unknown':
            self.set_result(False)
        else:
            acls = db.query(ACL).filter(and_(ACL.parent_id == self._object_id, ACL.action == self._action, ACL.context_id == self._context_id)).all()
            if acls:
                if len(acls) == 1:
                    if self._permissions:
                        acls[0].permissions = self._permissions
                    else:
                        db.delete(acls[0])
                    self.set_result(True)
                else:
                    raise CoilsException('Inconsistency detected in ACL data; multiple results.')
                    self.set_result(False)
            else:
                if self._permissions:
                    acl = ACL(self._object_id, self._context_id, permissions=self._permissions, action=self._action)
                    db.add(acl)
                self.set_result(True)
        return


import sys

from pathlib import Path
home = str(Path.home())
path = home+'/Platform/'

sys.path.insert (0, path)

import pandas as pd
import json
import requests
import time
import argparse

from queue_req_resp import *
from ServiceManager.platform_input_stream import *
from ServiceManager.platform_output_stream import *

class FlowerAnalysisService:
    def __init__(self, service_id, run_on_gateway, serving_addrs, model):
        self.service_id = service_id
        self.run_on_gateway = run_on_gateway
        self.serving_addrs = serving_addrs
        self.model = model

    def input_data_cb(self, ch, method, properties, input_data):
        if not isinstance(input_data, str):
            input_data = input_data.decode()

        #print ("Received input: ", input_data)

        data = json.loads(input_data)

        req = {}
        req["signature_name"] = "predict"
        req["instances"] = []

        # content is a list received as a string e.g. "[a, b, c, d]"
        # converting it into an actual list
        data["content"] = data["content"][1:-1].split(', ')

        instance = {}
        instance["sepal_length"] = [float(data["content"][0])]
        instance["sepal_width"] = [float(data["content"][1])]
        instance["petal_length"] = [float(data["content"][2])]
        instance["petal_width"] = [float(data["content"][3])]

        req["instances"].append(instance)

        req_str = json.dumps(req)
        headers = {"content-type" : "application/json"}

        # get IP of the tensorflow serving from Service Manager
        serving_addrs = "192.168.43.30:9500"
        json_response = requests.post('http://' + serving_addrs + "/v1/models/iris:predict", data=req_str, headers=headers)
        json_response = json.loads(str(json_response.text))
        inference = json_response["predictions"][0]

        if inference['classes'] == ['0']:
            flower = "Iris-Setosa"
        elif inference['classes'] == ['1']:
            flower = "Iris-Virginica"
        elif inference['classes'] == ['2']:
            flower = "Iris-Versicolor"
        else:
            print ("It shouldn't reach here!!")
            sys.exit(1)

        if self.run_on_gateway == "no":
            output_stream = PlatformOutputStream()
            output_stream.service_output_send(self.service_id, flower)

        #print ("FlowerAnalysisService Inference:", flower)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--service_id", default="-1")
    parser.add_argument("--run_on_gateway", default="no")
    parser.add_argument("--is_first_instance", default="no")
    parser.add_argument("--serving_addrs", default="127.0.0.1:9500")
    parser.add_argument("--model", default="")

    (args, unknown) = parser.parse_known_args()

    flower_analysis_service = FlowerAnalysisService(args.service_id, args.run_on_gateway, args.serving_addrs, args.model)

    sensor_name = "FLOWER_ANALYSIS_SENSOR"

    if args.run_on_gateway == "no":
        input_stream = PlatformInputStream()

        if args.is_first_instance == "yes":
            input_stream.service_register_request(args.service_id, sensor_name, "default_rate")

        input_stream.service_recv_input_request(args.service_id, flower_analysis_service.input_data_cb)


class SentenceGetter(object):

    def __init__(self, data):
        self.n_sent = 0
        self.data = data
        self.empty = False

        self.sentences = list()
        sentence = list()
        for index, row in data.iterrows():
            if row['Word'] == '.' and row['POS'] == '.' and row['Chunk'] == 'O' and row['Tag'] == 'O':
                if len(sentence) == 0:
                    continue
                self.sentences.append(sentence)
                sentence = list()
            else:
                sentence.append((row['Word'], row['POS'], row['Chunk'], row['Tag']))

    def get_next(self):
        try:
            s = self.sentences[self.n_sent]
            self.n_sent += 1
            return s
        except:
            return None


# ------------------------------------------------------------------------------------------------ #
# MIT License                                                                                #
#                                                                                #
# Copyright (c) 2020, Microsoft Corporation                                                        #
#                                                                                #
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software    #
# and associated documentation files (the "Software"), to deal in the Software without             #
# restriction, including without limitation the rights to use, copy, modify, merge, publish,       #
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the    #
# Software is furnished to do so, subject to the following conditions:                             #
#                                                                                #
# The above copyright notice and this permission notice shall be included in all copies or         #
# substantial portions of the Software.                                                            #
#                                                                                #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING    #
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND       #
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,     #
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,   #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.          #
# ------------------------------------------------------------------------------------------------ #

from gym.spaces import Box

from ..utils import default_preprocessor
from ..proba_dists import DiscretizedIntervalDist
from ..value_transforms import ValueTransform
from .base_stochastic_func_type2 import BaseStochasticFuncType2

__all__ = (
    'StochasticV',
)

class StochasticV(BaseStochasticFuncType2):
    r"""

    A state-value function :math:`v(s)`, represented by a stochastic function
    :math:`\mathbb{P}_\theta(G_t|S_t=s)`.

    Parameters
    ----------
    func : function

        A Haiku-style function that specifies the forward pass.

    env : gym.Env

        The gym-style environment. This is used to validate the input/output structure of ``func``.

    value_range : tuple of floats

        A pair of floats :code:`(min_value, max_value)`.

    num_bins : int, optional

        The space of rewards is discretized in :code:`num_bins` equal sized bins. We use the default
        setting of 51 as suggested in the `Distributional RL <https://arxiv.org/abs/1707.06887>`_
        paper.

    observation_preprocessor : function, optional

        Turns a single observation into a batch of observations in a form that is convenient for
        feeding into :code:`func`. If left unspecified, this defaults to
        :func:`default_preprocessor(env.observation_space) <coax.utils.default_preprocessor>`.

    value_transform : ValueTransform or pair of funcs, optional

        If provided, the target for the underlying function approximator is transformed:

        .. math::

            \tilde{G}_t\ =\ f(G_t)

        This means that calling the function involves undoing this transformation using its inverse
        :math:`f^{-1}`. The functions :math:`f` and :math:`f^{-1}` are given by
        ``value_transform.transform_func`` and ``value_transform.inverse_func``, respectively. Note
        that a ValueTransform is just a glorified pair of functions, i.e. passing
        ``value_transform=(func, inverse_func)`` works just as well.

    random_seed : int, optional

        Seed for pseudo-random number generators.

    """
    def __init__(
            self, func, env, value_range, num_bins=51, observation_preprocessor=None,
            value_transform=None, random_seed=None):

        self.value_transform = value_transform
        self.value_range = self._check_value_range(value_range)
        proba_dist = self._get_proba_dist(self.value_range, value_transform, num_bins)

        # set defaults
        if observation_preprocessor is None:
            observation_preprocessor = default_preprocessor(env.observation_space)
        if self.value_transform is None:
            self.value_transform = ValueTransform(lambda x: x, lambda x: x)
        if not isinstance(self.value_transform, ValueTransform):
            self.value_transform = ValueTransform(*value_transform)

        super().__init__(
            func=func,
            observation_space=env.observation_space,
            action_space=env.action_space,
            observation_preprocessor=observation_preprocessor,
            proba_dist=proba_dist,
            random_seed=random_seed)

    @property
    def num_bins(self):
        return self.proba_dist.space.n

    @classmethod
    def example_data(
            cls, env, value_range, num_bins=51, observation_preprocessor=None,
            value_transform=None, batch_size=1, random_seed=None):

        value_range = cls._check_value_range(value_range)
        proba_dist = cls._get_proba_dist(value_range, value_transform, num_bins)

        if observation_preprocessor is None:
            observation_preprocessor = default_preprocessor(env.observation_space)

        return super().example_data(
            env=env,
            observation_preprocessor=observation_preprocessor,
            proba_dist=proba_dist,
            batch_size=batch_size,
            random_seed=random_seed)

    def __call__(self, s, return_logp=False):
        r"""

        Sample a value.

        Parameters
        ----------
        s : state observation

            A single state observation :math:`s`.

        return_logp : bool, optional

            Whether to return the log-propensity associated with the sampled output value.

        Returns
        -------
        value : float or list thereof

            A single value associated with the state observation :math:`s`.

        logp : non-positive float or list thereof, optional

            The log-propensity associated with the sampled output value. This is only returned if we
            set ``return_logp=True``. Depending on whether :code:`a` is provided, this is either a
            single float or a list of :math:`n` floats, one for each discrete action.

        """
        return super().__call__(s, return_logp=return_logp)

    def mean(self, s):
        r"""

        Get the mean value.

        Parameters
        ----------
        s : state observation

            A single state observation :math:`s`.

        Returns
        -------
        value : float

            A single value associated with the state observation :math:`s`.

        """
        return super().mean(s)

    def mode(self, s):
        r"""

        Get the most probable value.

        Parameters
        ----------
        s : state observation

            A single state observation :math:`s`.

        Returns
        -------
        value : float

            A single value associated with the state observation :math:`s`.

        """
        return super().mode(s)

    def dist_params(self, s):
        r"""

        Get the parameters of the underlying (conditional) probability distribution.

        Parameters
        ----------
        s : state observation

            A single state observation :math:`s`.

        Returns
        -------
        dist_params : dict or list of dicts

            Depending on whether :code:`a` is provided, this either returns a single dist-params
            dict or a list of :math:`n` such dicts, one for each discrete action.

        """
        return super().dist_params(s)

    @staticmethod
    def _get_proba_dist(value_range, value_transform, num_bins):
        if value_transform is not None:
            f, _ = value_transform
            value_range = f(value_range[0]), f(value_range[1])
        reward_space = Box(*value_range, shape=())
        return DiscretizedIntervalDist(reward_space, num_bins)

    @staticmethod
    def _check_value_range(value_range):
        if not (isinstance(value_range, (tuple, list))
                and len(value_range) == 2
                and isinstance(value_range[0], (int, float))
                and isinstance(value_range[1], (int, float))
                and value_range[0] < value_range[1]):
            raise TypeError("value_range is not a valid pair tuple of floats: (low, high)")
        return float(value_range[0]), float(value_range[1])


import ply.lex as lex
import re
import codecs

#TOKENS
tokens = [
  'ID', 'NUMERO', 'PLUS', 'MINUS', 'POR', 'DIVIDE',
  'MODULO','NEGLOGICA', 'CORCHDER', 'CORCHIZQ','PARENTDER','PARENTIZQ',
  'YAND','OOR','ASIGNAR','MAYORQUE','MENORQUE','ACCESO',
  'MENORIGUAL','MAYORIGUAL','COMPIGUAL','COMPDIFERENTE','FINALIZADOR','LLAVEDER',
  'CADENA','BIN','COMILLASIMPLE','COMA',
  'LLAVEIZQ', 'COMMENT', 'NUMEROC', 'COMILLADOBLE'
]

#PALABRAS RESERVADAS POR MINIJAVA
reservadas = {
	'class':'CLASS',
	'extends': 'EXTENDS',
	'void': 'VOID',
	'int': 'INT',
	'boolean':'BOOLEAN',
	'string': 'STRING',
	'return': 'RETURN',
	'if': 'IF',
	'else': 'ELSE',
	'while': 'WHILE',
	'break': 'BREAK',
	'continue': 'CONTINUE',
	'this':'THIS',
	'new':'NEW',
	'length':'LENGTH',
	'true':'TRUE',
	'false':'FALSE',
	'null':'NULL'
}

tokens += reservadas.values()

#TOKENS UNITARIOS
t_ignore = '[ \t\n]'
t_PLUS = r'\+'
t_MINUS = r'\-'
t_POR = r'\*'
t_DIVIDE = r'\/'
t_MODULO = r'\%'
t_NEGLOGICA = r'\!'
t_CORCHDER = r'\]'
t_CORCHIZQ = r'\['
t_PARENTDER = r'\)'
t_PARENTIZQ = r'\('
t_YAND = r'\&\&'
t_OOR = r'\|\|'
t_ASIGNAR = r'\='
t_MAYORQUE = r'\>'
t_MENORQUE = r'\<'
t_ACCESO = r'\.'
t_MENORIGUAL = r'\<\='
t_MAYORIGUAL = r'\>\='
t_COMPIGUAL = r'\=\='
t_COMPDIFERENTE = r'\!\='
t_FINALIZADOR = r'\;'
t_LLAVEDER = r'\}'
t_LLAVEIZQ = r'\{'
t_COMILLASIMPLE = r'\''
t_COMA = r'\,'
t_COMILLADOBLE = r'\"'

#CIENTIFICO
def t_NUMEROC(t):
	r'(\-)?\d+(\.\d+)?[eE](\-)?\d+'
	t.value = float(t.value)
	return t

#INTS
def t_NUMERO(t):
	r'(\-)?\d+'
	t.value = int(t.value)
	if (int(t.value) < 2147483647 and int(t.value) > -2147483648):
		return t
	else:
		t.type="error"
		print(t.value + " esta por fuera del rango del tipo int, en la linea ",  t.lexer.lineno)

#BINARIOS
def t_BIN(t):
	r'b\'[01]+\''
	t.value = t.value[2:]
	t.value = t.value[:-1]
	try:
		t.value = int(t.value, 2)
	except:
		t.value = 0
	return t

#STRINGS
def t_CADENA(t):
	r'".*"'
	return t

#IDENTIFICADORES
##SEPARAR NUMEROS DE ID
def t_ID(t):
	r'[a-zA-Z\_]([a-zA-ZáéíóúÁÉÍÓÚñÑ0-9\_]*[a-zA-ZáéíóúÁÉÍÓÚñÑ\_])?'
	t.value = Reemplazar(t.value)
	t.type = reservadas.get(t.value, 'ID')
	return t

#REEMPLAZAR CARACTERES ESPECIALES POR _
def Reemplazar(palabra):
	identifier = ''
	for i in palabra:
		if (re.search(r'[áéíóúÁÉÍÓÚñÑ]' , i)):
			identifier += '_'
		else:
			identifier += i
	return identifier

#COMENTARIOS /* */
##COMENTARIOS DE LA FORMA /* SIN CERRAR SE DEBERIAN CONSIDERAR ERROR
def t_COMMENT(t):
	r'((\/\/[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ\@\(\)\[\]\{\}\,\;\:\_\.\-\t\ ]*)|(\/\*[a-zA-Z0-9áéíóúÁÉÍÓÚñÑ\@\(\)\[\]\{\}\,\;\:\_\.\-\t\n\ ]*\*\/))'
	for i in t.value:
		if(re.search(r'\n', i)):
			t.lexer.lineno += 1
	return t

#NUEVA LINEA
def t_newline(t):
	r'([\r])+'
	t.lexer.lineno += len(t.value)

#DETECCION DE ERRORES
def t_error(t):
	linea=t.lexer.lineno
	t.value = Reemplazar(t.value)
	print("%s caracter incorrecto en la linea %d" % (t.value[0], linea))
	t.lexer.skip(1)

#INGRESO DE ARCHIVO MINIJAVA
"""
test1 = "test.mj"
test2 = "test2.mj"
test3 = "test3.mj"

opc = int(input("Ingrese el numero de test a realizar: \t"))

if opc == 1:
	directorio = test1;
elif opc == 2:
	directorio = test2;
elif opc == 3:
	directorio = test3;
else:
	directorio = test1;

#directorio = "test.mj"
fp = codecs.open(directorio,"r","utf-8")
data = fp.read()
fp.close() """

analizador = lex.lex()

"""
data = '''

'''
"""

#ENTRADA DE TEXTO AL LEXER
"""analizador.input(data)

while True:
	tok = analizador.token()
	if not tok:
		break;
	print(tok) """


import time

start=time.time()

S=0
l=[1,1,2,6,24,120,720,5040,40320,362880]
for x in range(10,2540161):
    sx=str(x)
    p=0
    for y in sx:
        p+=l[int(y)]
    if p==x:
        S+=x

elapsed=(time.time()-start)
print ("found %s in %s seconds" % (S,elapsed))


#!/usr/bin/env python
import sys
from SokobanSolver import *
from SokobanField import *
from Tile import *

class SimpleSok(SokobanSolver):

	def createOverlay(self):
		self.overlay = Field()
		self.overlay.tileSize = (40, 40)
		self.roomTunnelOverlay()

	def start(self):
		pygame.init()
		self.canvas = pygame.display.set_mode(self.field.getDimensions())
		pygame.display.set_caption(self.__class__.__name__)
		self.onStart()
		self.show()

	def move(self, pos, direction):
		self.agent = pos
		SokobanSolver.move(self, direction)

if __name__ == '__main__':
	if len(sys.argv) == 2:
		game = SimpleSok()
		game.loadLevel(sys.argv[1])
		game.createOverlay()
		game.start()

		game.move((1,1), DOWN)
	else:
		error('Synopsis: ./SimpleSok.py LEVEL_FILE')


#encoding: utf-8
from OpenOrange import *

ParentPriceDeal = SuperClass('PriceDeal', "Master", __file__)
class PriceDeal(ParentPriceDeal):
    buffer = RecordBuffer("PriceDeal")

    def defaults(self):
        self.InclVAT = 1
        from Currency import Currency
        self.Currency = Currency.default()
        self.Type = 0

    def check(self):
        from PriceList import PriceList
        for field in ("Name","Currency"):       # importante siempre precisa moneda !
            if not self.fields(field).getValue():
               return self.FieldErrorResponse("NONBLANKERR",field)
        result = ParentPriceDeal.check(self)
        if not result: return result
        for PDr in self.PriceDealRows:
            pl = PriceList()
            pl = pl.bring(PDr.PriceList)
            if pl:
                if pl.InclVAT != self.InclVAT:
                    result = ErrorResponse("Calculo de IVA de Lista de Precio debe ser igual al Acuerdo de Precios. %s" %PDr.PriceList)
        return result

    @classmethod
    def getInclVAT(classobj, pdcode, transdate=today()):
        pricedeal = PriceDeal.bring(pdcode)
        if pricedeal:
            return pricedeal.InclVAT
        else:
            from SalesSettings import SalesSettings
            ss = SalesSettings.bring()
            return ss.DefaultInclVAT

    @classmethod
    def default(objclass):
        from User import User
        from Office import Office
        off = User.getOffice(currentUser())
        office = Office.bring(off)
        return office.PriceDeal

    def getPriceList(self, transDate):
        res = None
        from PriceList import PriceList
        for plrow in self.PriceDealRows:
            #alert((plrow.fields("FromDate").isNone(),plrow.fields("ToDate").isNone()))
            if (not plrow.fields("FromDate").isNone() and not plrow.fields("ToDate").isNone()):
                #alert((transDate >= plrow.FromDate,transDate <= plrow.ToDate))
                if (transDate >= plrow.FromDate and  transDate <= plrow.ToDate):
                    #alert("s")
                    res = PriceList.bring(plrow.PriceList)
            if (plrow.fields("FromDate").isNone() and plrow.fields("ToDate").isNone()):
                if (plrow.PriceList):
                    res = PriceList.bring(plrow.PriceList)
        #Esto no está bien, se está devolviendo la misma lista de precios siempre, aunque tenga fechas.
        #if (not res and self.PriceDealRows.count()):
        #    res = PriceList.bring(self.PriceDealRows[0].PriceList)
        return res

    def getPrice(self,artcode, transDate,currency,qty):
        if (currency != self.Currency):
            self.appendMessage("La moneda del Acuerdo de Precios \"%s\" no coincide con la solicitada \"%s\"" % (self.Currency,currency))
            return ErrorResponse("La moneda del Acuerdo de Precios \"%s\" no coincide con la solicitada \"%s\"" % (self.Currency,currency))
        if (self.Type == 0 or not self.Type):
            pricelist = self.getPriceList(transDate)
            if pricelist and artcode:
                res = pricelist.getPrice(artcode, qty)
                return res
            return None
        elif (self.Type==1):
            return self.getLatestPrice(artcode,transDate)
        elif (self.Type==2):
            return eval(self.Formula,{})
        return None

    def getLatestPrice(self, artcode, transdate):
        query = Query()
        query.sql =  "SELECT {TransDate},{Price} "
        query.sql += "FROM [DatePrice] "
        query.sql += "WHERE ({ArtCode} = s|%s|)\n " % artcode
        query.sql += "AND ({TransDate} <= d|%s|)\n " % transdate
        query.sql += "AND ({PriceDeal} = s|%s|)\n " % self.Code
        query.sql += "ORDER BY {TransDate} DESC "
        query.setLimit(1)
        if (query.open()):
           if len(query):
              return query[0].Price
        return 0.0

    def getLatestPrices(self, transdate,pricedeal):
        itemlist = {}
        query = Query()
        query.sql =  "SELECT [dp].{ArtCode},[dp].{TransDate},[dp].{Price} "
        query.sql += "FROM [DatePrice] [dp], "
        query.sql += " (SELECT {ArtCode},max({TransDate}) as {TransDate} FROM [DatePrice] "
        query.sql += " WHERE {TransDate} <= d|%s|  " % transdate
        query.sql += " GROUP BY {ArtCode}) [mp] \n"
        query.sql += "WHERE ([dp].{ArtCode} = [mp].{ArtCode} AND [dp].{TransDate} = [mp].{TransDate})\n "
        query.sql += " AND PriceDeal = s|%s| " % pricedeal
        if (query.open()):
           for rec in query:
              itemlist[rec.ArtCode] = rec.Price
        return itemlist

    def hasItem(self, artcode, transdate):
        if self.Type == 1:
            lastprice = self.getLatestPrice(artcode, transdate)
            if lastprice:
                return True
        else:
            pricelist = self.getPriceList(transdate)
            if pricelist:
                return pricelist.hasItem(artcode)
        return False

    def getSubRanges(self,fromDate,toDate):
        result = []
        lastDate = fromDate
        minDate = toDate
        enter = False
        for plrow in self.PriceDealRows:
          if (plrow.FromDate != None and plrow.ToDate != None):
              if (lastDate >= plrow.FromDate) and  (lastDate <= plrow.ToDate):
                  result.append( [True,lastDate,min(toDate,plrow.ToDate)] )
                  lastDate = addDays(min(toDate,plrow.ToDate),1)
              else: minDate = min(plrow.FromDate,minDate)
        if len(result)==0:
            #fromDate is < than all ranges
            if minDate == toDate:
                return [[False,fromDate,toDate]]
            return [[False,fromDate,minDate]] + self.getSubRanges(addDays(minDate,1),toDate)
        if lastDate <= toDate: result.append( [False,lastDate,toDate] )
        return result

    @classmethod
    def getRankings(objclass,closedf=True):
        rankings = {}
        query = Query()
        query.sql =  "SELECT {Code},{YieldRanking} "
        query.sql += "FROM [PriceDeal] "
        if closedf: query.sql += "WHERE?AND ({Closed} IS NULL OR {Closed} = 0)\n"
        if (query.open()):
           for rec in query:
              rankings[rec.Code] = rec.YieldRanking
        return rankings


data1 = "DataSet.txt"

def readData(data1):
	x = []
	with open(data1) as data :
	    for line in data :
		    x = line.split()
	return x

data = readData(data1)
number = ["1","2","3","4","5","6","7","8","9","0"]
box = []
new = []
newest = []
#problem 1: append strings that contain numbers to a list
for word in data:
	for letter in word:
		if letter in number:
			box.append(word)
			break
#problem 2: reverse the list and put the number back to the data in reverse order
box.reverse()
i = 0
for word in data:
	for letter in word:
		if letter in number:
			new.append(box[i])
			i += 1
			break
		else:
			new.append(word)
			break
#problem 3: uppercase the first letter in each sentence
for i in range(len(new)):
	word = data[i]
	wordprev = data[i-1]
	if (wordprev[len(wordprev)-1] == '.') :
		word = word[0].upper() + word[1:]
	newest.append(word)
#not nacessary, write a new file that contains modified data
txt = ' '.join(newest)
f = open("ModifiedDataSet.txt","w+")
f.write(txt)
f.close


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

import os, sys

path = os.path.abspath(os.path.dirname(sys.argv[0]))
path_global_dir = os.path.dirname(path)

# 1/ Set functions directory on path

#path_dir = os.path.join(path_global_dir, 'functions')
#sys.path.append(path_dir)
#ls_subdir_names = [f for f in os.listdir(path_dir) if not os.path.isfile(os.path.join(path_dir, f))]
#for subdir_name in ls_subdir_names:
#  sys.path.append(os.path.join(path_dir, subdir_name))

# 2/ Set path_data to find demo data or original data

# path_data defaults to data provided on github
path_data = os.path.join(path_global_dir, 'data')
# another location can be provided though
ls_possible_path_data = [r'W:\Bureau\Etienne_work\Data',
                         r'C:\Users\etna\Desktop\Etienne_work\Data']
for my_path in ls_possible_path_data:
  if os.path.exists(my_path):
    path_data = my_path
    break


glb="sagar global"
class sag:
    classvar="Class variable"

    def __init__(self,name,empID):
        self.name=name
        self.empID=empID

    def opening_account(self,branch):
        print("The branch is {} and account is for {} and ID geertaed is {}".format(branch,self.name,self.empID))
        print(sag.classvar)  # class variable claaling
        print(globals()['glb']) #Global variables calling
        #x = math.sqrt(9)
        #print(x)

Obj=sag("Sagar",12345)
Obj.opening_account("Rajahmundry")