NDB -- How to know if an entity has been contained under a root Key - google-app-engine

I want to add player's data into NDB. However before I add them, I have to check whether the data exists in datastore or not. I can't find the obvious answer in official docs. Can anyone give me a simple code and explanation about this problem? Here is part of my code.
self.player = Player(parent=ndb.Key("Players", "PlayersKeys"), name = self.request.get("Name"), playerid = self.request.get("ID"))
self.player.put()
Update-------------------
By using query, if it contains the data, then qry.get() would not be None.
Here is my solution:
qry = Player.query(Player.userid == self.request.get("ID"))
if qry.get() == None:
# put the data to datastore
self.player = Player(parent=ndb.Key("Players", "PlayersKeys"), name = self.request.get("Name"), userid = playerid)
self.player.put()
else:
# Do nothing

The answer is Player.get_or_insert
player_key = Player.query(Player.userid == self.request.get("ID")).get(keys_only=True)
player = Player.get_or_insert(player_key, **data)

You have to know the id of the entity, which is playerid in your case, and the key of the parent.
Therefore
myPlayer = Player.get_by_id(int(playerid),parent=parentKey)
if myPlayer:
#The player already exists... do something
pass
else:
#The player does not exist (yet) you can create it
pass
UPDATE
try
playerCount= Player.query(Player.userid ==self.request.get("ID")).count(keys_only=True)
if PlayerCount>0:
#the player already exists
pass
else:
#the player does not exist
pass
This shouldn't increase the number of read operations

Related

Save the for-loop index for certain values to be used later

I'm trying to create two spreadsheets: one tracks student attendance at school, the other tracks their attendance at Track practice. The goal is to write a function, that I can set up as a button, that I can click that will automatically send emails to several people if the student is present at school but is absent for sports without getting excused.
Right now, the whole thing is working pretty well, but I have one issue. I have a column that will read "Good" or "Bad" depending on whether the student meets the above condition. The function turns these into an array. I would like to use the index of the "Bad"'s to find the necessary email addresses, which are stored at the same index point in another array that I make from the spreadsheet. I'm not sure how to save this index point and use it to reference the email addresses. Code below.
function sendEmailsMonday() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TrackAttendance");
var dataRange = sheet.getRange("D2:D30");
var data = dataRange.getValues();// Gets array of "Good" and "Bad"
for (i in data) {
if(i = "Bad") {
var place = data.indexOf(i);
var dataRange2 = sheet.getRange("M2:M30");// Gets array of email addresses
var data2 = dataRange2.getValues();
var emailAddress = data2[place];
var message = "This is an automated email informing you that your child/advisee ____ was present at school today, but missed Track without being excused. Feel free to email Mr. # with any questions.";
var subject = "___ missed Track Practice";
MailApp.sendEmail(emailAddress, subject, message);
return;
}
}
}
So, the issue comes in with the index lines. If I get rid of
var place = data.indexOf(i);
and replace
var emailAddress = data[place];
with
var emailAddress = data[28];
or any other number, it will grab the email address and send it. But then it has nothing to do with the values in the other column.
Seems like this should be an easy fix but I'm bad at this.
Very late responding now. I think you are almost there.
Your IF statement should read:
if(i == "Bad") {
And then replace 'place' with i:
var emailAddress = data2[i];
It should work as expected now.

Reading shop list from txt file in Python

I'm really fresh to Python and need help reading information from txt file. I have a large C++ app need to duplicate it in Python. Sadly I have no idea where to start. I've been reading and watching some tutorials, but little help from them and I'm running out of time.
So my task is:
I have a shopping list with:
-Name of the item, price and age.
I also need to create two searches.
Search whether the item is in the shop (comparing strings).
if name of the item is == to the input name.
Search by age. Once the program finds the items, then it needs to print the list according to the price - from the lowest price to the highest.
For example you input age 15 - 30, the program prints out appropriate
items and sorts them by the price.
Any help would be nice. At least from where I could start.
Thank you.
EDITED
So far, I have this code:
class data:
price = 0
agefrom = 0
ageto = 0
name = ''
# File reading
def reading():
with open('toys.txt') as fd:
toyslist = []
lines = fd.readlines()
for line in lines:
information = line.split()
print(information)
"""information2 = {
'price': int(information[1])
'ageftom': int(information[2])
'ageto': int(information[3])
#'name': information[4]
}"""
information2 = data()
information2.price = int(information[0])
information2.agefrom = int(information[1])
information2.ageto = int(information[2])
information2.name = information[3]
toyslist.append(information2)
return toyslist
information = reading()
I HAVE A PROBLEM WITH THIS PART. I want to compare the user's input with the item information in the txt file.
n_search = raw_input(" Please enter the toy you're looking for: ")
def name_search(information):
for data in information:
if data.name == n_search:
print ("We have this toy.")
else:
print ("Sorry, but we don't have this toy.")
If you want to fins something in a list it's generally as straightforward as:
if "apple" in ["tuna", "pencil", "apple"]
However, in your case, the list to search is a list of lists so you need to "project" it somehow. List comprehension is often the easiest to reason about, a sort of for loop in a for loop.
if "apple" in [name for name,price,age in [["tuna",230.0,3],["apple",0.50,1],["pencil",1.50,2]]]
From here you want to start looking at filters whereby you provide a function that determines whether an entry is matched or not. you can roll your own in a for loop or use something more functional like 'itertools'.
Sorting on a list is also easy, just use 'sorted(my_list)' supplying a comparator function if you need it.
Examples as per your comment...
class ShoppingListItem:
def __init__(self,name,price,age):
self.name=name
self.price=price
self.age=age
or
from collections import namedtuple
sli = namedtuple("ShoppingListItem",['name','age','price'])

How to increment a variable in Gatlling Loop

I am trying to write a Gatling script where I read a starting number from a CSV file and loop through, say 10 times. In each iteration, I want to increment the value of the parameter.
It looks like some Scala or Java math is needed but could not find information on how to do it or how and where to combine Gatling EL with Scala or Java.
Appreciate any help or direction.
var numloop = new java.util.concurrent.atomic.AtomicInteger(0)
val scn = scenario("Scenario Name")
.asLongAs(_=> numloop.getAndIncrement() <3, exitASAP = false){
feed(csv("ids.csv")) //read ${ID} from the file
.exec(http("request")
.get("""http://finance.yahoo.com/q?s=${ID}""")
.headers(headers_1))
.pause(284 milliseconds)
//How to increment ID for the next iteration and pass in the .get method?
}
You copy-pasted this code from Gatling's Google Group but this use case was very specific.
Did you first properly read the documentation regarding loops? What's your use case and how doesn't it fit with basic loops?
Edit: So the question is: how do I get a unique id per loop iteration and per virtual user?
You can compute one for the loop index and a virtual user id. Session already has a unique ID but it's a String UUID, so it's not very convenient for what you want to do.
// first, let's build a Feeder that set an numeric id:
val userIdFeeder = Iterator.from(0).map(i => Map("userId" -> i))
val iterations = 1000
// set this userId to every virtual user
feed(userIdFeeder)
// loop and define the loop index
.repeat(iterations, "index") {
// set an new attribute named "id"
exec{ session =>
val userId = session("userId").as[Int]
val index = session("index").as[Int]
val id = iterations * userId + index
session.set("id", id)
}
// use id attribute, for example with EL ${id}
}
Here is my answer to this:
Problem Statement: I had to repeat the gatling execution for configured set of times, and my step name has to be dynamic.
object UrlVerifier {
val count = new java.util.concurrent.atomic.AtomicInteger(0)
val baseUrl = Params.applicationBaseUrl
val accessUrl = repeat(Params.noOfPagesToBeVisited,"index") {
exec(session=> {
val randomUrls: List[String] = UrlFeeder.getUrlsToBeTested()
session.set("index", count.getAndIncrement).set("pageToTest", randomUrls(session("index").as[Int]))
}
).
exec(http("Accessing Page ${pageToTest}")
.get(baseUrl+"${pageToTest}")
.check(status.is(200))).pause(Params.timeToPauseInSeconds)
}
So basically UrlFeeder give me list of String (urls to be tested) and in the exec, we are using count (AtomicInteger), and using this we are populating a variable named 'index' whose value will start from 0 and will be getAndIncremented in each iteration. This 'index' variable is the one which will be used within repeat() loop as we are specifying the name of counterVariable to be used as 'index'
Hope it helps others as well.

Lua - How to check if list contains element

I need some help with my lua script for a game. I need to check if my inventory in the game contains any id from a list.
Here's a piece of my list:
local Game_Items = {
{id = 7436, name = "angelic axe", value = 5000},
{id = 3567, name = "blue robe", value = 10000},
{id = 3418, name = "bonelord shield", value = 1200},
{id = 3079, name = "boots of haste", value = 30000},
{id = 7412, name = "butcher's axe", value = 18000},
{id = 3381, name = "crown armor", value = 12000}
}
The following code might look a bit weird since you don't know what it's for, but it's basically this: the list above is a list of items in my game, and inside the game theres an inventory where you can keep items and stuff. Now I want to check if my inventory contains any of those IDs.
I tried adding 2 of the id's manually and it worked, but my list of items contains over 500 items in total and I don't want to write them all out. Is there a way to put the whole list and check if it's in there somehow?
if not table.contains({ 3035, 3043, Game_Items[id] }, tempItemCounter.id) then
This is what I tried so far. Those two first id's work 3035 and 3043, then I tried all my whole list and only check the Ids. but I dont know how to do that. That code does not work. Could anyone just help me include the whole list of id's in the table.contains ?
Basically wanna include my whole list in that line, without typing out all IDs manually.
Shouldn't Game_Items[id] work? Doesn't that mean all the "id" inside "Game_Items"?
Thanks!
No it doesn't mean that. If foo is a table, then foo[id] looks for a field in foo that is called whatever id refers to, such as a string (so if id is 1 you will get foo[1], if id is "bar" you will get foo.bar, etc).
You can't do it in one line, but you can create a function that will allow you to write your if condition. I'm not sure what tempItemCounter is but assuming that your inventory is a map of keys to entries of the form
inventory = {
[1234] = {....},
[1235] = {....},
...
}
where each integer key is unique, and assuming you want true only if all items are in inventory, then you could do this:
function isAllInInventory(items, inventory)
for i,item in ipairs(items) do
if inventory[item.id] == nil
return false
end
end
return true
end
if isAllInInventory(Game_Items, inventory) then
...
end

user_id is not unique

i have a this thing in my views,py
def status_change(request):
if request.method == "POST":
rform = registerForm(data = request.POST)
if rform.is_valid():
register = rform.save(commit=False)
register.user = request.user
register.save()
return render_to_response('home.html')
else:
rform = registerForm()
return render_to_response('status_change.html',{'rform':rform})
when i tried to save the fields for the second time in the model it says
"column user_id is not unique"
actually i want to update it
i tried the rform.save(force_update = True)
but it didnt work
how to solve this thing.
Every time when you save form, django creates new object.
If you need to change(not create new) some object, you need first get object and then create form with instance of this object:
myobject = ...objects.get(....)
mform = MyForm(instance=myobject)
problem is solved
def status_change(request):
instance = get_object_or_404(register,pk=request.user.id)
#rest of the code here

Resources