コード例 #1
0
    def get(self, request, nnid):
        """
        Common Network Info Get Method
        ---
        # Class Name : CommonNNInfoList

        # Description:
            Structure : <nninfo> - version - batch version
            Search deinfed list of neural networks
        """
        try:
            condition = {}
            condition['nn_id'] = nnid
            if str(nnid).lower() == 'all':
                condition['nn_id'] = '%'
            elif str(nnid).lower() == 'seq':
                condition['nn_id'] = 'seq'
            return_data = NNCommonManager().get_nn_info(condition)
            logging.info(return_data)
            # Data node name
            graph = NNCommonManager.get_nn_node_name(None, nnid)

            return_param = {}
            return_param['fields'] = return_data
            return_param['graph'] = graph
            return Response(json.dumps(return_param, cls=DjangoJSONEncoder))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_param, cls=DjangoJSONEncoder))
コード例 #2
0
    def get(self, request, nnid):
        """
        Common Network Info Get Method
        ---
        # Class Name : CommonNNInfoList

        # Description:
            Structure : <nninfo> - version - batch version
            Search deinfed list of neural networks
        """
        try:
            condition = {}
            condition['nn_id'] = nnid
            if str(nnid).lower() == 'all':
                condition['nn_id'] = '%'
            elif str(nnid).lower() == 'seq':
                condition['nn_id'] = 'seq'
            return_data = NNCommonManager().get_nn_info(condition)
            logging.info(return_data)
            # Data node name
            graph = NNCommonManager.get_nn_node_name(None, nnid)

            return_param = {}
            return_param['fields'] = return_data
            return_param['graph'] = graph
            return Response(json.dumps(return_param, cls=DjangoJSONEncoder))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_param, cls=DjangoJSONEncoder))
    def handle(self, *args, **options):
        # Note, you shold load the test fixture into your db after a flush
        # It is not performed in this management command for you because
        # we don't want to accidentally delete important data
        json_data = open(os.path.join(os.path.dirname(__file__),
                                      '../../../data/testing_data/endpoint_testing_data.json'))
        endpoints = json.load(json_data)
        json_data.close()

        # We now have our endpoints. For each endpoint, we will perform the request
        # and then update the dictionary. After, we will serialize it to JSON and
        # print it to the screen, suitable for redirection directly back into the
        # endpoint_testing_data.json file
        c = Client()
        for endpoint in endpoints:
            url = endpoint.get('url', None)
            method = endpoint.get('method', None)
            request_object = endpoint.get('request_object', None)
            status_code = endpoint.get('status_code', None)

            response = None
            if method == "POST":
                response = c.post(url, content_type='application/json', data=json.dumps(request_object), format='json')
            elif method == "GET":
                response = c.get(url, format='json')

            if response.status_code is not status_code:
                raise Exception("Status code mismatch!")

            endpoint["response_object"] = response.data

        print(json.dumps(endpoints, indent=4, cls=DjangoJSONEncoder))
コード例 #4
0
    def handle(self, *args, **options):
        # Note, you shold load the test fixture into your db after a flush
        # It is not performed in this management command for you because
        # we don't want to accidentally delete important data
        json_data = open(
            os.path.join(os.path.dirname(__file__), "../../../data/testing_data/endpoint_testing_data.json")
        )
        endpoints = json.load(json_data)
        json_data.close()

        # We now have our endpoints. For each endpoint, we will perform the request
        # and then update the dictionary. After, we will serialize it to JSON and
        # print it to the screen, suitable for redirection directly back into the
        # endpoint_testing_data.json file
        c = Client()
        for endpoint in endpoints:
            url = endpoint.get("url", None)
            method = endpoint.get("method", None)
            request_object = endpoint.get("request_object", None)
            status_code = endpoint.get("status_code", None)

            response = None
            if method == "POST":
                response = c.post(url, content_type="application/json", data=json.dumps(request_object), format="json")
            elif method == "GET":
                response = c.get(url, format="json")

            if response.status_code is not status_code:
                raise Exception("Status code mismatch!")

            endpoint["response_object"] = response.data

        print(json.dumps(endpoints, indent=4, cls=DjangoJSONEncoder))
コード例 #5
0
 def delete(self, request, nnid):
     """
     - desc : delete cnn configuration data
     """
     try:
         input_parm = request.data
         input_parm['nn_id'] = nnid
         return_data = NNCommonManager().delete_nn_info(input_parm)
         return Response(json.dumps(return_data))
     except Exception as e:
         return_data = {"status": "404", "result": str(e)}
         return Response(json.dumps(return_data))
コード例 #6
0
ファイル: project.py プロジェクト: City-of-Helsinki/kaavapino
    def _set_calculated_deadline(self,
                                 deadline,
                                 date,
                                 initial,
                                 user,
                                 preview,
                                 preview_attribute_data={}):
        try:
            if preview:
                try:
                    identifier = deadline.attribute.identifier
                except AttributeError:
                    identifier = None

                project_deadline = preview_attribute_data.get(
                    identifier) or self.deadlines.get(deadline=deadline)
            else:
                project_deadline = self.deadlines.get(deadline=deadline)
        except ProjectDeadline.DoesNotExist:
            return

        if project_deadline and date:
            if preview:
                return date

            project_deadline.date = date
            project_deadline.save()

            if deadline.attribute:
                with transaction.atomic():
                    old_value = json.loads(
                        json.dumps(
                            self.attribute_data.get(
                                deadline.attribute.identifier),
                            default=str,
                        ))
                    new_value = json.loads(json.dumps(date, default=str))

                    self.update_attribute_data( \
                        {deadline.attribute.identifier: date})
                    self.save()
                    if old_value != new_value:
                        action.send(
                            user or self.user,
                            verb=verbs.UPDATED_ATTRIBUTE,
                            action_object=deadline.attribute,
                            target=self,
                            attribute_identifier=deadline.attribute.identifier,
                            old_value=old_value,
                            new_value=new_value,
                        )

            return date
コード例 #7
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def datos_factura(request):
    if request.method == 'POST':
        pk_factura = request.POST['pk_factura']
        q = RubroDocumento.objects.filter(ingreso_doc_id=1)
        for rubro in q:
            print rubro.valor
        print q
        ctx = {}
        return HttpResponse(json.dumps(ctx), content_type="application/json")
    else:
        ctx = {'mensaje':'no se ha consultado ningun dato'}
        return HttpResponse(json.dumps(ctx), content_type="application/json")
コード例 #8
0
ファイル: views.py プロジェクト: ivanmrosa/retorica
    def RecuperarSenha(self):

        username = self.propriedades_requisicao["usuario"]
        usuario = UsuarioDetalhe.objects.filter(username=username)

        if not usuario:
            return json.dumps({"ok": False, "msg": "O usuário informado não existe. Informe um usuário válido."})

        controle = ControleSenha(usuario=usuario)
        controle.RecuperarSenha()

        return json.dumps({"ok": False, "msg": "Sua solicitação foi efetivada. Verifique seu e-mail."})
コード例 #9
0
    def post(self, request, nnid):
        """
        Common Network Info Post Method
        ---
        # Class Name : CommonNNInfoList

        # Description:
            Structure : <nninfo> - version - batch version
            Define new neural network process
        """
        try:

            input_parm = request.data
            max_nnid = NNCommonManager().get_nn_id_max() + 1
            if nnid == "new":
                nnid = "nn" + str(max_nnid).zfill(8)
            else:
                return_data = NNCommonManager().get_nn_id_info(nnid)
                if return_data != []:
                    return Response(
                        json.dumps(nnid + " Network ID already exists"))
            input_parm['nn_id'] = nnid
            if input_parm.get('automl_parms') == None:
                input_parm['automl_parms'] = {}
            if input_parm.get('automl_runtime') == None:
                input_parm['automl_runtime'] = {}
            if input_parm.get('automl_stat') == None:
                input_parm['automl_stat'] = {}

            input_parm_s = {}
            input_parm_s['id'] = max_nnid
            input_parm_s['nn_id'] = nnid
            return_data = NNCommonManager().insert_nn_info(
                input_parm, input_parm_s)
            # Data node name
            graph = NNCommonManager.get_nn_node_name(None, return_data)

            return_param = {}
            return_param['nn_id'] = return_data
            return_param['graph'] = graph

            return Response(json.dumps(return_param))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
        finally:
            graph = NNCommonManager().get_nn_node_name(nnid)
            for net in graph:
                if net['fields']['graph_node'] in [
                        'netconf_data', 'eval_data'
                ]:
                    utils.get_source_path(nnid, None,
                                          net['fields']['graph_node_name'])
コード例 #10
0
ファイル: views.py プロジェクト: tombs/Water-Billing-System
    def get_context_data(self, **kwargs):
        context = super(DashboardView, self).get_context_data(**kwargs)

        period = Config.objects.get(name='active_period').value
        bs = BillingSchedule.objects.get(pk=period)
        business_date = Config.objects.get(name='business_date').value
        business_date = datetime.strptime(business_date,'%Y-%m-%d')
        business_date = business_date.strftime('%b %d, %Y')
        context['period'] = str(bs)
        context['usage'] = bs.reading_start_date.strftime("%b %d, %Y") + " - " + bs.reading_end_date.strftime("%b %d, %Y")
        context['business_date'] = business_date

        uncollected = Address.objects.values('address4').filter(
                id__in=Account.objects.annotate(
                        last_transaction_id=Max('financialtransaction')).values_list(
                            'last_transaction_id'), 
                        account__financialtransaction__balance__gt=0).annotate(
                        unc=Sum('account__financialtransaction__balance')).order_by('address4').all()
        context['uncollected_total'] = sum([i['unc'] for i in uncollected])
        context['uncollected'] = json.dumps(list(uncollected), cls=DjangoJSONEncoder)

        collected = Address.objects.values('address4').filter(
                    account__financialtransaction__type__in=['posted_payment']).annotate(
                    col=Sum('account__financialtransaction__amount')).order_by(
                    'address4').all()

        context['collected_total'] = sum([i['col'] for i in collected])
        context['collected'] = json.dumps(list(collected), cls=DjangoJSONEncoder)
        
       

        aggregate = {}
        flot_stack = {'uncollected':[], 'collected':[]}
        for addy in Address.objects.values_list('address4').annotate().all():
            aggregate[addy[0]] = {"collected": Decimal('0.0'),"uncollected": Decimal('0.0')}

        for col in collected:
            aggregate[col['address4']]['collected'] = col['col']

        for col in uncollected:
            aggregate[col['address4']]['uncollected'] = col['unc']

        
        for k,v in sorted(aggregate.items()):
            flot_stack['uncollected'].append((k,v['uncollected']))
            flot_stack['collected'].append((k,v['collected']))


        context['flot_pie'] = json.dumps(aggregate, cls=DjangoJSONEncoder)
        context['flot_stack'] = json.dumps(flot_stack, cls=DjangoJSONEncoder)
        return context
コード例 #11
0
 def get(self, request, nnid):
     """
     - desc : get cnn configuration data
     """
     try:
         condition = {}
         condition['nn_id'] = nnid
         if str(nnid).lower() == 'all':
             condition['nn_id'] = '%'
         return_data = NNCommonManager().get_nn_info(condition)
         logging.info(return_data)
         return Response(json.dumps(return_data, cls=DjangoJSONEncoder))
     except Exception as e:
         return_data = {"status": "404", "result": str(e)}
         return Response(json.dumps(return_data, cls=DjangoJSONEncoder))
コード例 #12
0
 def post(self, request, nnid):
     """
     - desc : insert cnn configuration data
     """
     try:
         input_parm = request.data
         input_parm['nn_id'] = nnid
         input_parm['automl_parms'] = {}
         input_parm['automl_runtime'] = {}
         input_parm['automl_stat'] = {}
         return_data = NNCommonManager().insert_nn_info(input_parm)
         return Response(json.dumps(return_data))
     except Exception as e:
         return_data = {"status": "404", "result": str(e)}
         return Response(json.dumps(return_data))
コード例 #13
0
 def setUp(self):
     self._admin_user = set_up_admin()
     self._course1, self._course2 = _create_two_courses()
     self._valid_payload = {
         'title': 'NewTitle1',
         'teacher': self._course1.teacher.pk,
         'start_date': json.dumps(date(2017, 10, 1),
                                  cls=DjangoJSONEncoder),
     }
     self._invalid_payload = {
         'title': '',
         'teacher': self._course1.teacher.pk,
         'start_date': json.dumps(date(2018, 10, 1),
                                  cls=DjangoJSONEncoder),
     }
コード例 #14
0
 def post(self, request):
     """
     request to setup all necessary rule tables with default data
     ---
     # Class Name : CommonSetRules
     # Description:
         request to setup all necessary rule tables with default data
     """
     try:
         result = set_all_default_rules()
         return_data = {"status": "200", "result": result}
         return Response(json.dumps(return_data))
     except Exception as e:
         return_data = {"status": "404", "result": str(e)}
         return Response(json.dumps(return_data))
コード例 #15
0
    def post(self, request, nnid):
        """
        Common Network Info Post Method
        ---
        # Class Name : CommonNNInfoList

        # Description:
            Structure : <nninfo> - version - batch version
            Define new neural network process
        """
        try:

            input_parm = request.data
            max_nnid = NNCommonManager().get_nn_id_max() + 1
            if nnid == "new":
                nnid = "nn" + str(max_nnid).zfill(8)
            else:
                return_data = NNCommonManager().get_nn_id_info(nnid)
                if return_data != []:
                    return Response(json.dumps(nnid+" Network ID already exists"))
            input_parm['nn_id'] = nnid
            if input_parm.get('automl_parms') == None:
                input_parm['automl_parms'] = {}
            if input_parm.get('automl_runtime') == None:
                input_parm['automl_runtime'] = {}
            if input_parm.get('automl_stat') == None:
                input_parm['automl_stat'] = {}

            input_parm_s = {}
            input_parm_s['id'] = max_nnid
            input_parm_s['nn_id'] = nnid
            return_data = NNCommonManager().insert_nn_info(input_parm, input_parm_s)
            # Data node name
            graph = NNCommonManager.get_nn_node_name(None, return_data)

            return_param = {}
            return_param['nn_id'] = return_data
            return_param['graph'] = graph

            return Response(json.dumps(return_param))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
        finally:
            graph = NNCommonManager().get_nn_node_name(nnid)
            for net in graph:
                if net['fields']['graph_node'] in ['netconf_data','eval_data']:
                    utils.get_source_path(nnid, None, net['fields']['graph_node_name'])
コード例 #16
0
ファイル: remote_forms.py プロジェクト: neuman/indiepen
def my_ajax_view(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = ProjectForm()


    elif request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = request.POST.get('data', {})
        form = ProjectForm(form_data)
        if form.is_valid():
            form.save()

    field_configuration = {
        'include': ['title','duration'],
    }

    remote_form = RemoteForm(form, **field_configuration)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(
        json.dumps(response_data, cls=DjangoJSONEncoder),
        mimetype="application/json"
    )

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
コード例 #17
0
ファイル: websockets.py プロジェクト: heshiyou/channels
    def receive(self, content, **kwargs):
        """Forward messages to all consumers."""
        # Check the frame looks good
        if isinstance(content, dict) and "stream" in content and "payload" in content:
            # Match it to a channel
            for stream, consumer in self.consumers.items():
                if stream == content['stream']:
                    # Extract payload and add in reply_channel
                    payload = content['payload']
                    if not isinstance(payload, dict):
                        raise ValueError("Multiplexed frame payload is not a dict")
                    # The json consumer expects serialized JSON
                    self.message.content['text'] = json.dumps(payload)
                    # Send demultiplexer to the consumer, to be able to answer
                    kwargs['multiplexer'] = WebsocketMultiplexer(stream, self.message.reply_channel)
                    # Patch send to avoid sending not formated messages from the consumer
                    if hasattr(consumer, "send"):
                        consumer.send = self.send
                    # Dispatch message
                    consumer(self.message, **kwargs)
                    return

            raise ValueError("Invalid multiplexed frame received (stream not mapped)")
        else:
            raise ValueError("Invalid multiplexed **frame received (no channel/payload key)")
コード例 #18
0
    def _do_update(self, course_pk, payload):
        response = client.put(reverse('get_delete_update_course',
                                      kwargs={'pk': course_pk}),
                              data=json.dumps(payload),
                              content_type='application/json')

        return response
コード例 #19
0
    def receive(self, content, **kwargs):
        """Forward messages to all consumers."""
        # Check the frame looks good
        if isinstance(content,
                      dict) and "stream" in content and "payload" in content:
            # Match it to a channel
            for stream, consumer in self.consumers.items():
                if stream == content['stream']:
                    # Extract payload and add in reply_channel
                    payload = content['payload']
                    if not isinstance(payload, dict):
                        raise ValueError(
                            "Multiplexed frame payload is not a dict")
                    # The json consumer expects serialized JSON
                    self.message.content['text'] = json.dumps(payload)
                    # Send demultiplexer to the consumer, to be able to answer
                    kwargs['multiplexer'] = WebsocketMultiplexer(
                        stream, self.message.reply_channel)
                    # Patch send to avoid sending not formated messages from the consumer
                    if hasattr(consumer, "send"):
                        consumer.send = self.send
                    # Dispatch message
                    consumer(self.message, **kwargs)
                    return

            raise ValueError(
                "Invalid multiplexed frame received (stream not mapped)")
        else:
            raise ValueError(
                "Invalid multiplexed **frame received (no channel/payload key)"
            )
コード例 #20
0
    def test_session_expiry_logout_view_during_de_1(self):
        encoded_result_form_data_entry_start_time =\
            json.loads(json.dumps(timezone.now(), cls=DjangoJSONEncoder))
        tally = create_tally()
        tally.users.add(self.user)
        result_form = create_result_form(form_state=FormState.DATA_ENTRY_1,
                                         tally=tally)
        data_entry_url = 'enter-results/%s/' % tally.pk
        request = self.factory.get(data_entry_url)
        request.user = self.user
        # Adding session
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()
        request.session['encoded_result_form_data_entry_start_time'] =\
            encoded_result_form_data_entry_start_time
        request.session['result_form'] =\
            result_form.pk

        response = views.session_expiry_logout_view(request)

        self.assertEqual(response.status_code, 302)
        self.assertEquals(
            request.session['encoded_result_form_data_entry_start_time'],
            encoded_result_form_data_entry_start_time)
        self.assertEquals(
            request.session['result_form'],
            result_form.pk)
コード例 #21
0
    def post(self, request):
        """
        Request to restart all nginx threads
        ---
        # Class Name : CommonServerRestart

        # Description:
            restart nginx threads via rest api
        """
        try:
            os.kill(os.getppid(), signal.SIGHUP)
            return_data = {"status": "200", "result": "restart uwsgi"}
            return Response(json.dumps(return_data))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
コード例 #22
0
def files_ana_page(request):
    files_ana = request.POST.get("files_ana")

    files_ana_arr = []
    files_ana_result = []
    if (files_ana):
        url = sys.path[0] + '/static/pkl/files_ana_V0.1.pkl'.replace('\\', '/')
        my_model = joblib.load(url)
        files_ana_arr.append(" ".join(jieba.cut(files_ana)))

    if (files_ana_arr):
        import json
        print(files_ana_arr)
        print(files_ana_arr)

        files_ana_result = my_model.predict(files_ana_arr)

        print(files_ana_result)
        print(files_ana_result)
        # s_unicode = files_ana_result
        # files_ana_result = s_unicode.encode('unicode-escape').decode('string_escape')
        # print(files_ana_result[0])
        # print(files_ana_result[0])

    # result = {"result": str(files_ana_result).replace('u', '').replace('\'', '').replace('[', '').replace(']', '')}
    return HttpResponse(json.dumps(files_ana_result[0], ensure_ascii=False),
                        content_type="application/json;charset=utf-8")
コード例 #23
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def eliminar_retencion(request):
    if request.method == "POST":
        detalle = DetalleRetencion.objects.get(pk=request.POST['pk_detalle'])
        detalle.delete()
        mensaje="borrado correctamente"
        ctx={"mensaje":mensaje}
        return HttpResponse(json.dumps(ctx), content_type="application/json") 
コード例 #24
0
ファイル: views.py プロジェクト: chidemavian/myproject
def getstuinfoajax(request):
    if "userid" in request.session:
        if request.is_ajax():
            if request.method == 'POST':
                varuser = request.session['userid']
                varerr = ""
                post = request.POST.copy()
                acccode = post['userid']
                # print acccode
                session, klass = acccode.split(':')
                kk = []
                data = Student.objects.filter(admitted_class=klass,
                                              admitted_session=session,
                                              gone=False).order_by('fullname')
                for p in data:
                    jn = p.fullname
                    kk.append(jn)
                return HttpResponse(json.dumps(kk),
                                    mimetype='application/json')
            else:
                gdata = ""
                return render_to_response('index.html', {'gdata': gdata})
        else:

            gdata = ""
            return render_to_response('getlg.htm', {'gdata': gdata})
    else:
        return HttpResponseRedirect('/login/')
コード例 #25
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def guardar_doc_cuenta_por_pagar(request):
    print 'llega a guardar doc cuenta por pagar'
    if request.method=="POST":
        print 'pasa al if de guardar doc cuenta por pagar'
        print request.POST['datos']
        ctx = {}
        return HttpResponse(json.dumps(ctx), content_type="application/json")
コード例 #26
0
    def handle(self, *args, **options):
        start_date = datetime.datetime.strptime(options['start_date'],
                                                "%Y-%m-%d")
        end_date = datetime.datetime.strptime(options['end_date'], "%Y-%m-%d")

        start_date = start_date.replace(hour=0,
                                        minute=0,
                                        second=1,
                                        tzinfo=UTC())
        end_date = end_date.replace(hour=23,
                                    minute=59,
                                    second=59,
                                    tzinfo=UTC())

        # Get the APIRequestLogs for this time span
        analytics = APIRequestLog.objects.filter(requested_at__gte=start_date,
                                                 requested_at__lte=end_date)

        print(analytics.count())

        for log in analytics:
            data = dict(log.__dict__)
            del data[
                "_state"]  # Strip this out as (1) we don't need it and (2) it's not serializable
            print(json.dumps(data, indent=4, cls=DjangoJSONEncoder))
コード例 #27
0
def test_endpoints(endpoint_data, client):
    json_data = open(os.path.join(os.path.dirname(__file__), "../../data/testing_data/endpoint_testing_data.json"))
    endpoints = json.load(json_data)
    json_data.close()
    logger = logging.getLogger("console")

    # TESTING TODO: fix this hand-rolled parametrization?

    for endpoint in endpoints:
        url = endpoint.get("url", None)

        # Skip v1 endpoint that got rewritten
        if url == "/api/v1/awards/autocomplete/":
            continue

        method = endpoint.get("method", None)
        request_object = endpoint.get("request_object", None)
        response_object = endpoint.get("response_object", None)
        status_code = endpoint.get("status_code", None)
        logger.info("Running endpoint test: \n\t" + method + " " + url + "\n\t" + endpoint.get("name", "Unnamed"))

        response = None
        if method == "POST":
            response = client.post(url, content_type="application/json", data=json.dumps(request_object), format="json")
        elif method == "GET":
            response = client.get(url, format="json")

        # Check if the status code is correct
        assert response.status_code == status_code
        # Check if the response object is correct
        # We use a special equivalence check because the response object can
        # be a multi-tiered nest of lists and objects, and can also be OrderedDicts
        # and ResultLists, which don't play nice with the native equality checks
        # TESTING TODO: I bet I can beat this
        assert evaluate_equivalence(response_object, response.data)
コード例 #28
0
def association_ana_page(request):
    ret = upload_file(request)
    if (ret['status'] != True):
        return HttpResponse(json.dumps({"result": '上传文件失败!!'}),
                            content_type="application/json;charset=utf-8")
    dataSet = fp.loadSimpDat(ret['data'])[0]
    minSup = request.POST.get("num")
    freqItems = fp.fpGrowth(dataSet, int(minSup))
    res = []
    for item in freqItems:
        if len(item) != 1:
            res.append(fp.u_to_utf8(item))

    result = {"result": res, "count": fp.loadSimpDat(ret['data'])[1]}
    return HttpResponse(json.dumps(result),
                        content_type="application/json;charset=utf-8")
コード例 #29
0
ファイル: views.py プロジェクト: jeppevb/korsvej13
def booking(request, year, month):
    year = int(year)
    month = int(month)
    retval = []
    bookings = Booking.objects.filter(
        Q(firstday__range=(date(year, month, 1),
                           date(year, month,
                                calendar.monthrange(year, month)[1])))
        | Q(lastday__range=(date(year, month, 1),
                            date(year, month,
                                 calendar.monthrange(year, month)[1]))))
    for n in range(date(year, month, 1).weekday()):
        retval.append({"status": "unday", "day": ""})
    for day in range(1, calendar.monthrange(year, month)[1] + 1):
        mydate = date(year, month, day)
        if bookings.filter(firstday__lte=mydate).filter(
                lastday__gte=mydate).count() > 0:
            retval.append({
                "status": "booked",
                "day": mydate.strftime("%a") + " " + str(day) + "."
            })
        else:
            retval.append({
                "status": "open",
                "day": mydate.strftime("%a") + " " + str(day) + "."
            })
    while len(retval) < 35:
        retval.append({"status": "unday", "day": ""})
    return HttpResponse(json.dumps(retval), mimetype="application/json")
コード例 #30
0
ファイル: models.py プロジェクト: ginfo-cflex/TwoRavens
    def as_dict(self, **kwargs):
        """Return as an OrderedDict"""
        as_json = kwargs.get('as_json', False)
        as_json_pretty = kwargs.get('as_json_pretty', False)

        od = OrderedDict()

        for param in self.FIELDS_TO_SERIALIZE:
            od[param] = self.__dict__.get(param)

        if as_json:
            return json.dumps(od, cls=DjangoJSONEncoder)
        elif as_json_pretty:
            return json.dumps(od, cls=DjangoJSONEncoder, indent=4)

        return od
コード例 #31
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def guardar_asiento_contable_default_view(request):
    print 'llega a guardar'
    if request.method=="POST":
        cantidad=int(request.POST['cantidad'])
        pk_doc = request.POST['pk_doc']
        tipo_documento = TipoDocumento.objects.get(pk=pk_doc)
        AsientoTipoDefault.objects.filter(tipo_documento=tipo_documento).delete()
        for i in range(cantidad):
            pk_cuenta=request.POST['cuentas['+str(i)+'][pk]']
            pk_rubro=request.POST['cuentas['+str(i)+'][rubro]']
            debe_haber=request.POST['cuentas['+str(i)+'][debe_haber]']
            asiento_contab = AsientoTipoDefault()
            asiento_contab.tipo_documento = TipoDocumento.objects.get(pk=pk_doc)
            asiento_contab.cuenta = CuentaContable.objects.get(pk=pk_cuenta)
            asiento_contab.rubro = Rubro.objects.get(pk=pk_rubro)
           
            if debe_haber == 'debe':
                asiento_contab.es_debe = True
                asiento_contab.es_haber = False
            else:
                asiento_contab.es_haber = True
                asiento_contab.es_debe = False
                
            asiento_contab.save()
            print "pk: "+pk_cuenta+" rubro: "+pk_rubro+" debe_haber: "+debe_haber;
    ctx={}
    print 'saliendo de guardar'
    return HttpResponse(json.dumps(ctx), content_type="application/json")
コード例 #32
0
    def post(self, request):
        """
        Request to restart all nginx threads
        ---
        # Class Name : CommonServerRestart

        # Description:
            restart nginx threads via rest api
        """
        try:
            os.kill(os.getppid(), signal.SIGHUP)
            return_data = {"status": "200", "result": "restart uwsgi"}
            return Response(json.dumps(return_data))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
コード例 #33
0
 def setUp(self):
     self.factory = RequestFactory()
     self._create_permission_groups()
     self._create_and_login_user()
     self.tally = create_tally()
     self.tally.users.add(self.user)
     self.encoded_result_form_corrections_start_time =\
         json.loads(json.dumps(timezone.now(), cls=DjangoJSONEncoder))
コード例 #34
0
    def post(self, request):
        """
        Your docs
        ---
        # Class Name (must be separated by `---`)

        # Description:
            - name: name
              description: Foobar long description goes here
        """
        try:
            os.kill(os.getppid(), signal.SIGHUP)
            return_data = {"status": "200", "result": "restart uwsgi"}
            return Response(json.dumps(return_data))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
コード例 #35
0
ファイル: websockets.py プロジェクト: heshiyou/channels
 def encode(cls, stream, payload):
     """
     Encodes stream + payload for outbound sending.
     """
     return {"text": json.dumps({
         "stream": stream,
         "payload": payload,
     }, cls=DjangoJSONEncoder)}
コード例 #36
0
 def encode(cls, stream, payload):
     """
     Encodes stream + payload for outbound sending.
     """
     return {"text": json.dumps({
         "stream": stream,
         "payload": payload,
     }, cls=DjangoJSONEncoder)}
コード例 #37
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def anexo_transaccional_view(request):
    if request.method=='POST':
        mes = request.POST['mes']
        anio = request.POST['anio']
        ctx = obtenerDocumentosConYSinAnexo(mes, anio)
        return HttpResponse(json.dumps(ctx), content_type="application/json")
    else:   
        return render_to_response("contabilidad/anexo_tran.html",context_instance=RequestContext(request))
コード例 #38
0
    def delete(self, request, nnid):
        """
        Your docs
        ---
        # Class Name (must be separated by `---`)

        # Description:
            - name: name
              description: Foobar long description goes here
        """
        try:
            input_parm = request.data
            input_parm['nn_id'] = nnid
            return_data = NNCommonManager().delete_nn_info(input_parm)
            return Response(json.dumps(return_data))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
コード例 #39
0
ファイル: views.py プロジェクト: ivanmrosa/retorica
 def PesquisarUsuario(self):
     return json.dumps(list(UsuarioDetalhe.objects.annotate(
         pais_id=F('cidade__pais__id'),
         estado_id=F('cidade__estado__id'),
         nome_completo=Concat('first_name', V(' '), 'last_name', output_field=CharField())
     ).filter(Q(nome_completo__icontains=self.propriedades_requisicao["nome_completo"]) | Q(
         email=self.propriedades_requisicao['nome_completo'])).values(
         'username', 'telefone', 'foto_usuario', 'id', 'email', 'nome_completo'
     )), cls=DjangoJSONEncoder)
コード例 #40
0
    def setUp(self):
        self._admin_user = set_up_admin()
        teacher = Teacher.objects.create(first_name='First',
                                         last_name='Last',
                                         email_address='email-address')

        self._valid_payload = {
            'title': 'Title1',
            'teacher': teacher.pk,
            'start_date': json.dumps(date(2017, 9, 1),
                                     cls=DjangoJSONEncoder),
        }
        self._invalid_payload = {
            'title': '',
            'teacher': teacher.pk,
            'start_date': json.dumps(date(2017, 9, 1),
                                     cls=DjangoJSONEncoder),
        }
コード例 #41
0
ファイル: views.py プロジェクト: arnists/vaa
def oldanswers(request, election):
    last_answers = dict(getattr(request.user.candidate_set.filter(election__slug=election).first(), "last_answers", None))
    for key in last_answers:
        if "q_" in key:
            number = key[2:]
            last_answers[key] = remap % (number, int(last_answers[key])-1)
    if last_answers:
        return HttpResponse(json.dumps(last_answers.items()), content_type="application/json")
    return HttpResponse("[]", content_type="application/json")
コード例 #42
0
ファイル: views.py プロジェクト: onrik/sm-test
def get_objects_view(request, model_name):
    model = get_object_or_404(Model, name=model_name)
    response = {
        'model': model.as_dict(),
        'fields': [field.as_dict() for field in model.fields.all()],
        'objects': [obj.as_dict() for obj in model.get_objects()],
    }

    return HttpResponse(json.dumps(response), content_type='application/json')
コード例 #43
0
    def delete(self, request, nnid):
        """
        Common Network Info Delete Method
        ---
        # Class Name : CommonNNInfoList

        # Description:
            Structure : <nninfo> - version - batch version
            Delete selected neuralnetwork from list (careful cannot be undo)
            Delete all related info list version, batch, model and etc
        """
        try:
            input_parm = request.data
            input_parm['nn_id'] = nnid
            return_data = NNCommonManager().delete_nn_info(input_parm)
            return Response(json.dumps(return_data))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
コード例 #44
0
    def delete(self, request, nnid):
        """
        Common Network Info Delete Method
        ---
        # Class Name : CommonNNInfoList

        # Description:
            Structure : <nninfo> - version - batch version
            Delete selected neuralnetwork from list (careful cannot be undo)
            Delete all related info list version, batch, model and etc
        """
        try:
            input_parm = request.data
            input_parm['nn_id'] = nnid
            return_data = NNCommonManager().delete_nn_info(input_parm)
            return Response(json.dumps(return_data))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
コード例 #45
0
    def render(self, name, value, attrs=None, renderer=None):
        field = super().render(name, value, attrs, renderer)

        return """%s
    <script type="text/javascript">
        CodeMirror.fromTextArea(
            document.getElementById('%s'), %s
        );
    </script>
    """ % (field, attrs['id'], json.dumps(self.config))
コード例 #46
0
    def get_context_data(self, **kwargs):
        context = super(CenterDetailsView, self).get_context_data(**kwargs)
        context['tally_id'] = self.kwargs.get('tally_id')
        context['form_action'] = ''
        context['header_text'] = _('Intake')
        self.request.session[
            'encoded_result_form_intake_start_time'] =\
            json.loads(json.dumps(timezone.now(), cls=DjangoJSONEncoder))

        return context
コード例 #47
0
    def handle(self, *args, **options):
        project_id = options.get("id")

        if project_id:
            try:
                projects = [Project.objects.get(pk=project_id)]
            except Project.DoesNotExist:
                projects = Project.objects.all()
        else:
            projects = Project.objects.all()

        for project in projects:
            old_deadlines = project.deadlines.all()

            project.update_deadlines()

            updated_deadlines = old_deadlines.union(project.deadlines.all())
            for dl in updated_deadlines:
                try:
                    new_date = project.deadlines.get(deadline=dl.deadline).date
                except ProjectDeadline.DoesNotExist:
                    new_date = None

                try:
                    old_date = old_deadlines.get(deadline=dl.deadline).date
                except ProjectDeadline.DoesNotExist:
                    old_date = None

                old_value = json.loads(json.dumps(old_date, default=str))
                new_value = json.loads(json.dumps(new_date, default=str))

                if old_value != new_value:
                    action.send(
                        project.user,
                        verb=verbs.UPDATED_DEADLINE,
                        action_object=dl.deadline,
                        target=project,
                        deadline_abbreviation=dl.deadline.abbreviation,
                        old_value=old_value,
                        new_value=new_value,
                    )
コード例 #48
0
    def get_context_data(self, **kwargs):
        tally_id = self.kwargs.get('tally_id')

        context = super(CorrectionView, self).get_context_data(**kwargs)
        context['tally_id'] = tally_id
        context['form_action'] = ''
        context['header_text'] = _('Corrections')
        self.request.session[
            'encoded_result_form_corrections_start_time'] =\
            json.loads(json.dumps(timezone.now(), cls=DjangoJSONEncoder))

        return context
コード例 #49
0
ファイル: views.py プロジェクト: Kesel/django
def pedometer(request):
    if request.method == 'POST':
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        way = Way.objects.get(id=1)
        way.duration = body['duration']
        way.steps = body['steps']
        way.save()
        # mydict = {'date': datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%LZ')}
        mydict = {'steps': 1, 'duration': 1}
        nowdatetime = json.dumps(mydict)
        return JsonResponse(mydict)
コード例 #50
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def cargar_rubro_ingreso_view(request):
    #cambiar el pk quemado en codigo
    if request.method=="POST":
        pk=request.POST["pk"]
        rubros=RubroDocumento.objects.filter(ingreso_doc=Documento.objects.get(pk=pk))
        contador=0
        array = []
        for rubro in rubros:
            ctx={"rubroIngresoPk":rubro.pk,"valor":rubro.valor,"nombre":str(rubro.rubro.descripcion)}
            array.append(ctx)
            contador+=1
        ctx = {"rubros":array}
        return HttpResponse(json.dumps(ctx), content_type="application/json")
コード例 #51
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def nueva_retencion_view(request):
    if request.method=="POST":
        retencion = Retencion.objects.get(pk=request.POST['pk_retencion'])
        concep_re = ConceptoRetencion.objects.get(pk=request.POST['concepto_pk'])
        imp_renta = request.POST['monto']
        base_imponible = request.POST['base']
        pk=grabarDetalleRetencion(retencion=retencion, imp_renta=imp_renta, concepto_retencion=concep_re)
        ctx={"mesanje":"se guardo con exito","pk":pk}
        return HttpResponse(json.dumps(ctx), content_type="application/json")
    else:
        form = RetencionForm()
        concepto = ConceptoRetencion.objects.all()
        ctx={"form":form,"concepto":concepto}
        return render_to_response("contabilidad/nueva_retencion.html",ctx,context_instance=RequestContext(request))
コード例 #52
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def editar_anexo_trans_view(request):
    if request.method=="POST":
        form = AnexoTransaccionalForm(request.POST)
        if form.is_valid():
            print form.cleaned_data['sustento_tributario']
            ctx={"mensaje":"correcto"}
            anexo = pk=request.POST['pk_anexo']
            sustento = request.POST['sustento_tributario']
            tipo_comprobante = request.POST['tipo_comprobante']
            try:
                iva_bien = request.POST['retencion_bien']
            except MultiValueDictKeyError:
                iva_bien = 0
                print "no hay retencion de iva bienes"
            try:
                iva_servicio = request.POST['retencion_servicio']
            except MultiValueDictKeyError:
                iva_servicio = 0
                print "no hay retencion de iva servicios"
            try:
                iva_cien = request.POST['retencion_cien']
            except MultiValueDictKeyError:
                iva_cien = 0
                print "no hay retencion de iva cien"
            editarAnexoTransaccional(anexo, sustento, tipo_comprobante, iva_bien, iva_servicio, iva_cien)
            return HttpResponse(json.dumps(ctx), content_type="application/json")
        else:
            mensaje="Llene Correctamente el formulario"
            ctx={"mensaje":mensaje}
            return HttpResponse(json.dumps(ctx), content_type="application/json") 
    else:
        pk=request.GET['anexo']
        print pk
        datos = obtenerDatosAnexoTransaccional(pk)
        form = AnexoTransaccionalForm(datos)
        ctx={"form":form,"codigo_doc":datos['codigo_doc'],"base_iva":datos['base_iva'],"pk_anexo":pk}
        return render_to_response("contabilidad/editar_anexo.html",ctx,context_instance=RequestContext(request))
コード例 #53
0
    def put(self, request, nnid):
        """
        Common Network Info Put Method
        ---
        # Class Name : CommonNNInfoList

        # Description:
            Structure : <nninfo> - version - batch version
            Modifiy already defined neuralnetwork info
        """
        try:
            input_parm = request.data
            input_parm['nn_id'] = nnid
            if input_parm.get('automl_parms') == None:
                input_parm['automl_parms'] = {}
            if input_parm.get('automl_runtime') == None:
                input_parm['automl_runtime'] = {}
            if input_parm.get('automl_stat') == None:
                input_parm['automl_stat'] = {}
            return_data = NNCommonManager().update_nn_info(input_parm)
            return Response(json.dumps(return_data))
        except Exception as e:
            return_data = {"status": "404", "result": str(e)}
            return Response(json.dumps(return_data))
    def handle(self, *args, **options):
        start_date = datetime.datetime.strptime(options['start_date'], "%Y-%m-%d")
        end_date = datetime.datetime.strptime(options['end_date'], "%Y-%m-%d")

        start_date = start_date.replace(hour=0, minute=0, second=1, tzinfo=UTC())
        end_date = end_date.replace(hour=23, minute=59, second=59, tzinfo=UTC())

        # Get the APIRequestLogs for this time span
        analytics = APIRequestLog.objects.filter(requested_at__gte=start_date, requested_at__lte=end_date)

        print(analytics.count())

        for log in analytics:
            data = dict(log.__dict__)
            del data["_state"]  # Strip this out as (1) we don't need it and (2) it's not serializable
            print(json.dumps(data, indent=4, cls=DjangoJSONEncoder))
コード例 #55
0
ファイル: views.py プロジェクト: ivanmrosa/retorica
    def ObterUsuario(self):
        if 'usuario_id' in self.propriedades_requisicao:
            usuario_id = self.propriedades_requisicao["usuario_id"]
        else:
            usuario_id = self.request.user.id

        return json.dumps(list(UsuarioDetalhe.objects.filter(id=usuario_id).annotate(
            pais_id=F('cidade__pais__id'),
            estado_id=F('cidade__estado__id'),
            nome_completo=Concat('first_name', V(' '), 'last_name', output_field=CharField()),
        ).values(
            'username', 'telefone', 'numero_identidade', 'sexo', 'numero_endereco', 'last_login',
            'email_pagseguro', 'endereco', 'last_name', 'foto_usuario', 'id', 'pais_id', 'estado_id',
            'email', 'first_name', 'cep', 'bairro', 'cpf', 'token_pagseguro', 'email_pagseguro', 'cidade_id',
            'nome_completo', 'tipo_usuario'
        )), cls=DjangoJSONEncoder)
コード例 #56
0
ファイル: views.py プロジェクト: jeppevb/korsvej13
def booking(request, year, month):
    year = int(year)
    month = int(month)
    retval = []
    bookings = Booking.objects.filter(Q(firstday__range = (date(year, month, 1), date(year, month, calendar.monthrange(year, month)[1]))) | Q(lastday__range = (date(year, month, 1), date(year, month, calendar.monthrange(year, month)[1]))))
    for n in range(date(year, month, 1).weekday()):
        retval.append({"status":"unday", "day":""})
    for day in range(1,calendar.monthrange(year, month)[1]+1):
        mydate = date(year, month, day)
        if bookings.filter(firstday__lte = mydate).filter(lastday__gte = mydate).count() > 0:
            retval.append({"status":"booked", "day":mydate.strftime("%a") + " " + str(day) + "."})
        else:
            retval.append({"status":"open", "day":mydate.strftime("%a") + " " + str(day) + "."})
    while len(retval) < 35:
        retval.append({"status":"unday", "day":""})
    return HttpResponse(json.dumps(retval), mimetype="application/json")
コード例 #57
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
 def post(self,request):
     if request.POST['vuelta']=="0":
         rubros = Rubro.objects.all()
         data = serializers.serialize("json", rubros)
         print rubros 
         return HttpResponse(data, content_type="application/json")
     else:
         tipo_documento = TipoDocumento.objects.get(pk=request.POST['pk'])
         asientos_default = AsientoTipoDefault.objects.filter(tipo_documento=tipo_documento)
         print "asientos default"
         print asientos_default
         print "asientos def"
         array = []
         for asiento in asientos_default:
             ctx={"codigo":asiento.cuenta.codigo,"pk":asiento.cuenta.pk,"descripcion":asiento.cuenta.nombre,"rubro":asiento.rubro.pk,"debe":asiento.es_debe}
             array.append(ctx)
         return HttpResponse(json.dumps(array), content_type="application/json")
コード例 #58
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
 def post(self,request):
     tipo_documento = TipoDocumento.objects.get(pk=request.POST['pk'])
     asientos_default = AsientoTipoDefault.objects.filter(tipo_documento=tipo_documento)
     print "asientos default"
     print asientos_default
     print "asientos def"
     array = []
     
     ingreso = Documento.objects.get(pk=request.POST['pk_doc'])
     RI = RubroDocumento.objects.filter(ingreso_doc=ingreso)
     
     for asiento in asientos_default:
         for rubro_ing in RI.filter(rubro=asiento.rubro):
             ctx={"codigo":asiento.cuenta.codigo,"pk":asiento.cuenta.pk,"descripcion":asiento.cuenta.nombre,"rubro":rubro_ing.pk,"valor":rubro_ing.valor,"debe":asiento.es_debe}
             array.append(ctx)
     print array
     return HttpResponse(json.dumps(array), content_type="application/json")
コード例 #59
0
ファイル: views.py プロジェクト: rubancar/proyecto_django
def editar_retencion_view(request):
    if request.method=="POST":
        detalle = DetalleRetencion.objects.get(pk=request.POST['pk_detalle'])
        concep_re = ConceptoRetencion.objects.get(pk=request.POST['concepto_pk'])
        imp_renta = request.POST['monto']
        base_imponible = request.POST['base']
        editarDetalleRetencion(detalle=detalle, imp_renta=imp_renta, concepto_retencion=concep_re)
        ctx={"mesanje":"se guardo con exito"}
        return HttpResponse(json.dumps(ctx), content_type="application/json")
    else:
        retencion = DetalleRetencion.objects.get(pk=request.GET['retencion'])
        monto = retencion.valor_retenido
        base = retencion.base_imponible
        concepto = retencion.concepto_retencion.pk
        porcentaje = retencion.concepto_retencion.porcentaje
        form = RetencionForm({"monto":monto,"base":base,"concepto_retencion":concepto,"porcentaje":porcentaje})
        concepto = ConceptoRetencion.objects.all()
        ctx={"form":form,"concepto":concepto}
        return render_to_response("contabilidad/editar_retencion.html",ctx,context_instance=RequestContext(request))