本文整理汇总了Python中utils.to_json函数的典型用法代码示例。如果您正苦于以下问题:Python to_json函数的具体用法?Python to_json怎么用?Python to_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_json函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: log
def log(self, action, data):
parent = self.get_version() or None
#mongo.db.history.remove(); parent = None
prev = self.replay()
data = self.get_delta(prev, data)
if not data:
return
delta = {
'uri': self.target,
'action': action,
'data': data,
'parent': ObjectId(parent) if parent else None,
'utc': dt.utcnow()
}
mongo.db.history.insert( delta )
redis.set("history:version:%s" % self.target, str( delta['_id'] ))
print delta
redis.publish('history', to_json(delta))
开发者ID:DeadWisdom,项目名称:splendor,代码行数:18,代码来源:collection.py
示例17: _setup_complete_election
def _setup_complete_election(self, election_params={}):
"do the setup part of a whole election"
# a bogus call to set up the session
self.client.get("/")
# REPLACE with params?
self.setup_login()
# create the election
full_election_params = {
"short_name" : "test-complete",
"name" : "Test Complete",
"description" : "A complete election test",
"election_type" : "referendum",
"use_voter_aliases": "0",
"use_advanced_audit_features": "1",
"private_p" : "0"}
# override with the given
full_election_params.update(election_params)
response = self.client.post("/helios/elections/new", full_election_params)
# we are redirected to the election, let's extract the ID out of the URL
election_id = re.search('/elections/([^/]+)/', str(response['Location'])).group(1)
# helios is automatically added as a trustee
# check that helios is indeed a trustee
response = self.client.get("/helios/elections/%s/trustees/view" % election_id)
self.assertContains(response, "Trustee #1")
# add a few voters, via file upload
FILE = "helios/fixtures/voter-file.csv"
voters_file = open(FILE)
response = self.client.post("/helios/elections/%s/voters/upload" % election_id, {'voters_file': voters_file})
voters_file.close()
self.assertContains(response, "first few rows of this file")
# now we confirm the upload
response = self.client.post("/helios/elections/%s/voters/upload" % election_id, {'confirm_p': "1"})
self.assertRedirects(response, "/helios/elections/%s/voters/list" % election_id)
# and we want to check that there are now voters
response = self.client.get("/helios/elections/%s/voters/" % election_id)
NUM_VOTERS = 4
self.assertEquals(len(utils.from_json(response.content)), NUM_VOTERS)
# let's get a single voter
single_voter = models.Election.objects.get(uuid = election_id).voter_set.all()[0]
response = self.client.get("/helios/elections/%s/voters/%s" % (election_id, single_voter.uuid))
self.assertContains(response, '"uuid": "%s"' % single_voter.uuid)
response = self.client.get("/helios/elections/%s/voters/foobar" % election_id)
self.assertEquals(response.status_code, 404)
# add questions
response = self.client.post("/helios/elections/%s/save_questions" % election_id, {
'questions_json': utils.to_json([{"answer_urls": [None,None], "answers": ["Alice", "Bob"], "choice_type": "approval", "max": 1, "min": 0, "question": "Who should be president?", "result_type": "absolute", "short_name": "Who should be president?", "tally_type": "homomorphic"}]),
'csrf_token': self.client.session['csrf_token']})
self.assertContains(response, "SUCCESS")
# freeze election
response = self.client.post("/helios/elections/%s/freeze" % election_id, {
"csrf_token" : self.client.session['csrf_token']})
self.assertRedirects(response, "/helios/elections/%s/view" % election_id)
# email the voters
num_messages_before = len(mail.outbox)
response = self.client.post("/helios/elections/%s/voters/email" % election_id, {
"csrf_token" : self.client.session['csrf_token'],
"subject" : "your password",
"body" : "time to vote",
"suppress_election_links" : "0",
"send_to" : "all"
})
self.assertRedirects(response, "/helios/elections/%s/view" % election_id)
num_messages_after = len(mail.outbox)
self.assertEquals(num_messages_after - num_messages_before, NUM_VOTERS)
email_message = mail.outbox[num_messages_before]
assert "your password" in email_message.subject, "bad subject in email"
# get the username and password
username = re.search('voter ID: (.*)', email_message.body).group(1)
password = re.search('password: (.*)', email_message.body).group(1)
# now log out as administrator
self.clear_login()
self.assertEquals(self.client.session.has_key('user'), False)
# return the voter username and password to vote
return election_id, username, password
开发者ID:abompard,项目名称:helios-server,代码行数:95,代码来源:tests.py
示例18: send
def send(self, data):
channel.send_message(self.token, utils.to_json(data))
开发者ID:armonge,项目名称:geek_feed,代码行数:2,代码来源:models.py
示例19: hash
def hash(self):
s = utils.to_json(self.toJSONDict())
return utils.hash_b64(s)
开发者ID:glondu,项目名称:helios-server,代码行数:3,代码来源:electionalgs.py
示例20: toJSON
def toJSON(self):
return utils.to_json(self.toJSONDict())
开发者ID:glondu,项目名称:helios-server,代码行数:2,代码来源:electionalgs.py
注:本文中的utils.to_json函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论