当前位置: 首页>>代码示例>>Python>>正文


Python utils.to_json函数代码示例

本文整理汇总了Python中utils.to_json函数的典型用法代码示例。如果您正苦于以下问题:Python to_json函数的具体用法?Python to_json怎么用?Python to_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了to_json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

def main(_):
    pp.pprint(flags.FLAGS.__flags)

    if not os.path.exists(FLAGS.checkpoint_dir):
        os.makedirs(FLAGS.checkpoint_dir)
    if not os.path.exists(FLAGS.sample_dir):
        os.makedirs(FLAGS.sample_dir)

    with tf.Session() as sess:
        if FLAGS.dataset == 'mnist':
            dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size, y_dim=10,
                    dataset_name=FLAGS.dataset, is_crop=FLAGS.is_crop, checkpoint_dir=FLAGS.checkpoint_dir)
        else:
            dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size,
                    dataset_name=FLAGS.dataset, is_crop=FLAGS.is_crop, checkpoint_dir=FLAGS.checkpoint_dir)

        if FLAGS.is_train:
            dcgan.train(FLAGS)
        else:
            dcgan.load(FLAGS.checkpoint_dir)

        to_json("./web/js/gen_layers.js", dcgan.h0_w, dcgan.h1_w, dcgan.h2_w, dcgan.h3_w, dcgan.h4_w)

        z_sample = np.random.uniform(-1, 1, size=(FLAGS.batch_size, dcgan.z_dim))

        samples = sess.run(dcgan.sampler, feed_dict={dcgan.z: z_sample})
        save_images(samples, [8, 8], './samples/test_%s.png' % strftime("%Y-%m-%d %H:%M:%S", gmtime()))
开发者ID:leconteur,项目名称:DCGAN-tensorflow,代码行数:27,代码来源:main.py

示例2: main

def main(_):
    pp.pprint(flags.FLAGS.__flags)

    if not os.path.exists(FLAGS.checkpoint_dir):
        os.makedirs(FLAGS.checkpoint_dir)
    if not os.path.exists(FLAGS.sample_dir):
        os.makedirs(FLAGS.sample_dir)

    with tf.Session() as sess:
        if FLAGS.dataset == 'mnist':
            dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size, y_dim=10,
                    dataset_name=FLAGS.dataset, is_crop=FLAGS.is_crop, checkpoint_dir=FLAGS.checkpoint_dir)
        else:
            dcgan = DCGAN(sess, image_size=FLAGS.image_size, batch_size=FLAGS.batch_size,
                    dataset_name=FLAGS.dataset, is_crop=FLAGS.is_crop, checkpoint_dir=FLAGS.checkpoint_dir)

        if FLAGS.is_train:
            dcgan.train(FLAGS)
        else:
            dcgan.load(FLAGS.checkpoint_dir)

        to_json("./web/js/layers.js", [dcgan.h0_w, dcgan.h0_b, dcgan.g_bn0],
                                      [dcgan.h1_w, dcgan.h1_b, dcgan.g_bn1],
                                      [dcgan.h2_w, dcgan.h2_b, dcgan.g_bn2],
                                      [dcgan.h3_w, dcgan.h3_b, dcgan.g_bn3],
                                      [dcgan.h4_w, dcgan.h4_b, None])

        # Below is codes for visualization
        OPTION = 2
        visualize(sess, dcgan, FLAGS, OPTION)
开发者ID:AmitShah,项目名称:DCGAN-tensorflow,代码行数:30,代码来源:main.py

示例3: _send_api_command

    def _send_api_command(self, request):
        """
        Send an API command to Galah.

        :param request: A properly formed JSON object to send Galah.
        :returns: A ``requests.Response`` object.

        """

        request = copy.copy(request)

         # Extract any files
        file_args = {}
        for i in (k for k, v in request.items() if isinstance(v, file)):
            file_args[str(i)] = request.pop(i)

        try:
            requester = self._requester()

            if not file_args:
                return requester.post(
                    urlparse.urljoin(config.CONFIG["host"], "/api/call"),
                    data = utils.to_json(request),
                    headers = {"Content-Type": "application/json"},
                    verify = _get_verify()
                )
            else:
                return requester.post(
                    urlparse.urljoin(config.CONFIG["host"], "/api/call"),
                    data = {"request": utils.to_json(request)},
                    files = file_args,
                    verify = _get_verify()
                )
        except requests.exceptions.SSLError as e:
            logger.critical(
                "There was a problem with communicating via SSL: %s.",
                str(e),
                exc_info = True
            )

            sys.exit(1)
        except requests.exceptions.ConnectionError:
            logger.critical(
                "Galah did not respond at %s.",
                urlparse.urljoin(config.CONFIG["host"], "/api/call"),
                exc_info = True
            )

            sys.exit(1)
开发者ID:bmars003,项目名称:galah-apiclient,代码行数:49,代码来源:communicate.py

示例4: get

 def get(self, slug):
     match = ndb.Key('Match', slug).get()
     if not match:
         self.response.status_int = 404
         return
     self.response.headers['Content-Type'] = 'application/json'
     self.response.write(utils.to_json(match.to_dict()))
开发者ID:armonge,项目名称:geek_feed,代码行数:7,代码来源:geek_feed.py

示例5: on_logged_in

 def on_logged_in(self, userid, gadget, wavelet):
     waveid = wavelet.wave_id
     if not models.Login.exists(waveid, userid):
         # Wait, this user has no login.  Bail out.
         gadget.set_status(Gadget.LOGIN)
         return
     blogger = utils.Blogger.open(wavelet.wave_id, userid)
     if not blogger:
         # There was some error.  Bail out.
         gadget.set_status(Gadget.LOGIN)
         return
     blogs = blogger.get_blogs()
     if len(blogs) == 0:
         # User has no blogs.  Bail out for now.
         gadget.set_status(Gadget.LOGIN)
         return
     blog = blogs[0]["id"]
     connection = models.Connection.get(waveid)
     if connection:
         connection.owner = userid
         connection.blog = blog
         connection.post = None
     else:
         connection = models.Connection(waveid=waveid, owner=userid, blog=blog)
     connection.put()
     gadget.set_owner(userid)
     gadget.set_status(Gadget.CONNECTED)
     gadget.set("blogs", utils.to_json(blogs))
     gadget.set_blog(blog)
开发者ID:hitrust,项目名称:google-wave-resources,代码行数:29,代码来源:robot.py

示例6: get_auth_url

 def get_auth_url(self):
   waveid = self.request.get('waveid')
   userid = self.request.get('userid')
   if (not waveid) or (not userid):
     return
   return to_json({
     'url': Blogger.get_auth_url(waveid, userid, _UPGRADE_URL)
   })
开发者ID:hitrust,项目名称:google-wave-resources,代码行数:8,代码来源:server.py

示例7: check_user_auth

 def check_user_auth(self):
   waveid = self.request.get('waveid')
   userid = self.request.get('userid')
   if (not waveid) or (not userid):
     return
   return to_json({
     'isSignedIn': models.Login.exists(waveid, userid)
   })
开发者ID:hitrust,项目名称:google-wave-resources,代码行数:8,代码来源:server.py

示例8: one_election_drive_tally

def one_election_drive_tally(request, election):
  """
  JavaScript-based driver for the entire tallying process, now done in JavaScript.
  """
  if election.tally_type != "homomorphic":
    return HttpResponseRedirect(reverse(one_election_view,args=[election.election_id]))
  
  election_pk = election.public_key
  election_pk_json = utils.to_json(election_pk.toJSONDict())
  
  election_sk = election.private_key
  if election_sk:
    election_sk_json = utils.to_json(election_sk.toJSONDict())
  else:
    election_sk_json = None
  
  return render_template(request, 'drive_tally', {'election': election, 'election_pk_json' : election_pk_json, 'election_sk_json' : election_sk_json})
开发者ID:benadida,项目名称:helios,代码行数:17,代码来源:views.py

示例9: convert_to_json

 def convert_to_json(self, *args, **kwargs):
   return_val = func(self, *args, **kwargs)
   try:
     return render_json(utils.to_json(return_val))
   except Exception, e:
     import logging
     logging.error("problem with serialization: " + str(return_val) + " / " + str(e))
     raise e
开发者ID:grnet,项目名称:zeus,代码行数:8,代码来源:view_utils.py

示例10: social_cart

def social_cart(request):
    data = SocialCartResource().to_dict(obj=request.user, request=request)
    return render(request, 'cart/social_cart.j.html', {
        'cart_json': to_json(data),
        'is_empty': not data['buys'] and \
                    not data['pending_shipping_requests'] and \
                    not data['pickup_requests'] and \
                    not data['shipping_requests']
    })
开发者ID:softak,项目名称:webfaction_demo,代码行数:9,代码来源:views.py

示例11: one_election_keyshares_tally_manage

def one_election_keyshares_tally_manage(request, election):
  election_pk_json = utils.to_json(election.public_key.toJSONDict())
  keyshares = election.get_keyshares()
  
  ready_p = True
  for keyshare in keyshares:
    ready_p = ready_p and (keyshare.decryption_factors != None)
  
  return render_template(request,"keyshares_tally_manage", {'election': election, 'election_pk_json': election_pk_json, 'ready_p' : ready_p})
开发者ID:benadida,项目名称:helios,代码行数:9,代码来源:views.py

示例12: post

    def post(self):
        request = to_json(self.request.body)

        # Verify the token on the Google servers
        url = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={}".format(request.get('token'))
        result = urlfetch.fetch(url=url,
            method=urlfetch.GET,
        )

        if result.status_code == 200:
            content = to_json(result.content)
        #     Need to check the 'aud' property once we have a user to actually test this stuff with.
        #     For now we'll just assume everything worked and return a formatted new user

            user = User.query(User.email==content.get('email')).get()

            if user is None:
                # Need to create a new user
                user = User()
                user.email = content.get('email')
                user.put()

                self.response.status_int = 200
                self.response.headers['Access-Control-Allow-Origin'] = "http://www.myvoyagr.co"
                self.response.write(user.format())
            else:
                # Get all the trips associated with the user and add it to the response
                trips = {}
                trip_qry = Trip.query(ancestor=user.key).fetch()
                for trip in trip_qry:
                    trips[trip.name] = trip.key.id()
                self.response.status_int = 200
                self.response.headers['Access-Control-Allow-Origin'] = "http://www.myvoyagr.co"
                self.response.write({'user': user.format(), 'trips' : trips})
                return

        else:
            self.response.status_int = 400
            self.response.headers['Access-Control-Allow-Origin'] = "http://www.myvoyagr.co"
            self.response.write({'error': 'There was an error authenticating the user'})
            return
开发者ID:rickeywang,项目名称:hack2015,代码行数:41,代码来源:user.py

示例13: post_status

def post_status(room_id):
    # print request.get_json()
    update_status = request.get_json()
    # update statuses
    status = statuses.get(room_id)

    # update given fields
    if update_status.get("status"):
        status.status = update_status.get("status")
        status.timestamp = utils.get_currrent_time_str()
        if update_status.get("status") == "FIRE":
            print "fire alert!"
            emailer.send_email(
                "[email protected], [email protected], [email protected], [email protected], [email protected]",
                "FIRE Alert! [%s]" % room_id, "Status Details: \n" + utils.to_json(status))
            # send_message("9492664065", "There is FIRE at room [%s]!" % (room_id))
    if update_status.get("occupancy"):
        status.occupancy = update_status.get("occupancy")
    # if update_status.get("carbon_detected"):
    if "carbon_detected" in update_status:
        status.carbon_detected = update_status.get("carbon_detected")

    return utils.to_json({"Update": True})
开发者ID:eugenechung81,项目名称:fire-alarm-iot,代码行数:23,代码来源:server.py

示例14: serialize

    def serialize(self, obj, **kw):
        """
        Function for serializing object => string.
        This can be overwritten for custom 
        uses.

        The default is to do nothing ('serializer'=None)
        If the connection is intialized with 'serializer' set to 
        'json.gz', 'json', 'gz', or 'zip', we'll do the 
        transformations.
        """
        serializer = kw.get('serializer',  self._serializer)

        if serializer == "json.gz":
            return utils.to_gz(utils.to_json(obj))
        
        elif serializer == "json":
            return utils.to_json(obj)

        elif serializer == "gz":
            assert(isinstance(obj, basestring))
            return utils.to_gz(obj)

        elif serializer == "zip":
            assert(isinstance(obj, basestring))
            return utils.to_zip(obj)

        elif serializer == "pickle":
            return utils.to_pickle(obj)

        elif serializer is not None:

            raise NotImplementedError(
                'Only json, gz, json.gz, zip, and pickle'
                'are supported as serializers.')

        return obj
开发者ID:harshalgalgale,项目名称:s3plz,代码行数:37,代码来源:__init__.py

示例15: post

    def post(self, slug):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return

        values = json.loads(self.request.body)
        event = models.Event(parent=ndb.Key('Match', slug))
        event.body = values.get('body')
        event.meta = values.get('meta')
        event.user = user
        event.put()

        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(utils.to_json(event.to_dict()))
开发者ID:armonge,项目名称:geek_feed,代码行数:15,代码来源:geek_feed.py


注:本文中的utils.to_json函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。