# Path: openfonacide/forms.py
# class ReporteForm(ModelForm):
#     class Meta:
#         model = Reportes
#         fields = (
#             'id_prioridad', 'tipo', 'codigo_establecimiento', 'codigo_institucion', 'nombre_institucion', 'periodo',
#             'cedula', 'nombre', 'apellido', 'email', 'telefono', 'motivo', 'observacion'
#         )
# 
# Path: openfonacide/utils.py
# def dictfetch(cursor, N, offset=None):
#     """Returns all rows from a cursor as a dict"""
#     desc = cursor.description
#     rows = []
# 
#     try:
#         N = int(N)
#     except:
#         N = None
#     if not N:
#         rows = cursor.fetchall()
#     else:
#         try:
#             offset = int(offset)
#         except:
#             pass
#         if offset and type(offset) == int:
#             N = offset + N
#         else:
#             offset = 0
#         rows = cursor.fetchall()[offset:N]
#     return [
#         dict(zip([col[0] for col in desc], row))
#         for row in rows
#         ]
# 
# def escapelike(query):
#     result = adapt(query).__str__()
#     return result[1:len(result) - 1]
# 
# Path: openfonacide/jsonh.py
# def dump(obj, fp, *args, **kwargs):
# def dumps(obj, *args, **kwargs):
# def load(fp, *args, **kwargs):
# def loads(str, *args, **kwargs):
# def pack(dict_list):
# def unpack(hlist):


import json
import openfonacide.settings as settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.core.urlresolvers import reverse
from django.core.mail import EmailMessage, EmailMultiAlternatives
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from django.db import transaction
from django.shortcuts import render_to_response
from django.shortcuts import redirect
from django.template import RequestContext, Context
from django.template.loader import get_template
from django.utils.datastructures import MultiValueDictKeyError
from django.views.generic import View, TemplateView
from rest_framework.decorators import detail_route
from rest_framework import filters
from rest_framework.generics import ListAPIView, ListCreateAPIView, get_object_or_404
from django.http import Http404, JsonResponse
from rest_framework import viewsets
from rest_framework import pagination
from rest_framework.response import Response
from rest_framework import permissions, authentication
from datetime import datetime
from django.contrib.auth.models import User
from models import *
from openfonacide.forms import ReporteForm
from openfonacide.utils import dictfetch, escapelike
from openfonacide.serializers import *
from openfonacide import jsonh as JSONH
        codigo_establecimiento = kwargs.get('codigo_establecimiento')
        query = request.GET.get('q')
        periodo = request.GET.get('periodo')
        offset = request.GET.get('offset')
        cantidad = request.GET.get('cantidad')
        tipos = ['nombre', 'codigo', 'direccion', 'distrito', 'barrio']
        tipo = request.GET.get('tipo')
        if tipo not in tipos:
            tipo = None
        if not periodo:
            periodo = '2014'
        if codigo_establecimiento:
            institucion = InstitucionSerializer(
                Institucion.objects.filter(codigo_establecimiento=codigo_establecimiento, periodo=periodo), many=True)
        else:
            if query is not None:
                instituciones = {
                    "results": {},
                    "query": query,
                    "tipo": tipo,
                    "periodo": periodo,
                    "base_url": reverse('index')
                }
                base_query = 'SELECT * FROM openfonacide_institucion inst ' \
                             'JOIN openfonacide_establecimiento est on ' \
                             '(est.anio=inst.periodo AND est.codigo_establecimiento=inst.codigo_establecimiento)'
                cursor = connection.cursor()
                if tipo is None or tipo == 'codigo':
                    cursor.execute(
                        base_query +

# Path: openfonacide/forms.py
# class ReporteForm(ModelForm):
#     class Meta:
#         model = Reportes
#         fields = (
#             'id_prioridad', 'tipo', 'codigo_establecimiento', 'codigo_institucion', 'nombre_institucion', 'periodo',
#             'cedula', 'nombre', 'apellido', 'email', 'telefono', 'motivo', 'observacion'
#         )
# 
# Path: openfonacide/utils.py
# def dictfetch(cursor, N, offset=None):
#     """Returns all rows from a cursor as a dict"""
#     desc = cursor.description
#     rows = []
# 
#     try:
#         N = int(N)
#     except:
#         N = None
#     if not N:
#         rows = cursor.fetchall()
#     else:
#         try:
#             offset = int(offset)
#         except:
#             pass
#         if offset and type(offset) == int:
#             N = offset + N
#         else:
#             offset = 0
#         rows = cursor.fetchall()[offset:N]
#     return [
#         dict(zip([col[0] for col in desc], row))
#         for row in rows
#         ]
# 
# def escapelike(query):
#     result = adapt(query).__str__()
#     return result[1:len(result) - 1]
# 
# Path: openfonacide/jsonh.py
# def dump(obj, fp, *args, **kwargs):
# def dumps(obj, *args, **kwargs):
# def load(fp, *args, **kwargs):
# def loads(str, *args, **kwargs):
# def pack(dict_list):
# def unpack(hlist):


# Path: openfonacide/views.py
import json
import openfonacide.settings as settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.core.urlresolvers import reverse
from django.core.mail import EmailMessage, EmailMultiAlternatives
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from django.db import transaction
from django.shortcuts import render_to_response
from django.shortcuts import redirect
from django.template import RequestContext, Context
from django.template.loader import get_template
from django.utils.datastructures import MultiValueDictKeyError
from django.views.generic import View, TemplateView
from rest_framework.decorators import detail_route
from rest_framework import filters
from rest_framework.generics import ListAPIView, ListCreateAPIView, get_object_or_404
from django.http import Http404, JsonResponse
from rest_framework import viewsets
from rest_framework import pagination
from rest_framework.response import Response
from rest_framework import permissions, authentication
from datetime import datetime
from django.contrib.auth.models import User
from models import *
from openfonacide.forms import ReporteForm
from openfonacide.utils import dictfetch, escapelike
from openfonacide.serializers import *
from openfonacide import jsonh as JSONH

        codigo_establecimiento = kwargs.get('codigo_establecimiento')
        query = request.GET.get('q')
        periodo = request.GET.get('periodo')
        offset = request.GET.get('offset')
        cantidad = request.GET.get('cantidad')
        tipos = ['nombre', 'codigo', 'direccion', 'distrito', 'barrio']
        tipo = request.GET.get('tipo')
        if tipo not in tipos:
            tipo = None
        if not periodo:
            periodo = '2014'
        if codigo_establecimiento:
            institucion = InstitucionSerializer(
                Institucion.objects.filter(codigo_establecimiento=codigo_establecimiento, periodo=periodo), many=True)
        else:
            if query is not None:
                instituciones = {
                    "results": {},
                    "query": query,
                    "tipo": tipo,
                    "periodo": periodo,
                    "base_url": reverse('index')
                }
                base_query = 'SELECT * FROM openfonacide_institucion inst ' \
                             'JOIN openfonacide_establecimiento est on ' \
                             '(est.anio=inst.periodo AND est.codigo_establecimiento=inst.codigo_establecimiento)'
                cursor = connection.cursor()
                if tipo is None or tipo == 'codigo':
                    cursor.execute(
                        base_query +

                        " WHERE inst.codigo_institucion = '" + escapelike(