Update:
The only answer yet given is not helping me. The code works as desired on my local system but does not work in the deployed Python app. This is a series problem for me. Please give this question a serious second look.
Here is some simplified code to show what is happening. When the simplified code is put into the interactive console for the SDK, it always prints out Hello, schott.brian, but in the deployed app its like it prints out no match. What's up with that?
user = "schott.brian"
name = "schott.brian"
if user and user == name:
print "Hello, " + user
else:
print "no match"
Here is my code. Notice the second if checks if user and (user == person.user):
user = users.get_current_user()
ID_id = self.request.get("ID", None)
ID_id = ''.join(ID_id.split())
key = db.Key.from_path("PQ", ID_id)
person = PQ.get(key)
if person: #person's ID DOES exist already
logging.info("6 person %s" % person.user )
logging.info("6 key %s" % key )
logging.info("6 ID_id %s" % ID_id )
logging.info("6 user %s" % user )
if user and (user == person.user):
# never get here on gae, but works on sdk
else:
# always gets to here by mistake on gae, but works on SDKs
logging.info("7 user %s" % user )
logging.info("7 person %s" % person.user )
Here are the logs for that code on gae and even though user exists and
(user == person.user), that if clause is NOT succeeding. Can you tell me why? Does one of the two really include gmail.com and the other does not?
2012-07-17 15:39:19.993 6 person schott.brian
I 2012-07-17 15:39:19.993 6 key ag1zfnBhcnRpY2lwb2xschMLEgJQUSILY29kZUJTY2hvdHQM
I 2012-07-17 15:39:19.993 6 ID_id codeBSchott
I 2012-07-17 15:39:19.993 6 user schott.brian
I 2012-07-17 15:39:19.993 7 user schott.brian
I 2012-07-17 15:39:19.994 7 person schott.brian
user.get_current_user() returns an object. Printing the user casts it to a string, so maybe you want to do something like:
if user and (str(user) == str(person.user)):
but you're actually better off comparing user ids, rather than string representations of user objects.
Related
I have a bot in writing in python and I want to incorporate a number game into the bot. The game code is below. (nl is a variable to say os.linesep)
secret_number = random.randint(0, 100)
guess_count = 0
guess_limit = 5
print(f'Welcome to the number guessing game! The range is 0 - 100 and you have 5 attempts to guess the correct number.')
while guess_count < guess_limit:
guess = int(input('Guess: '))
guess_count += 1
if guess > secret_number:
print('Too High.', nl, f"You have {guess_limit - guess_count} attempts remaining.")
elif guess < secret_number:
print('Too Low.', nl, f"You have {guess_limit - guess_count} attempts remaining.")
elif guess == secret_number:
print("That's correct, you won.")
break
else:
print("Sorry, you failed.")
print(f'The correct number was {secret_number}.')
So I want to be able to use that in the discord messaging system. My issue is that I need the bot to scan the most recent messages for a number from that specific user that initiated the game. How could I do so?
To simplify my question how can I say this:
if message from same message.author = int():
guess = that^
The solution here would be to wait_for another message from that user. You can do this with:
msg = await client.wait_for('message', check=message.author == PREVIOUS_SAVED_MSG_AUTHOR_AS_VARIABLE, timeout=TIMEOUT)
# You don't really need a timeout but you can add one if you want
# (then you'd need a except asyncio.TimeoutError)
if msg.content == int():
guess = msg
else:
...
I'd like to write a function that checks if user's login and hashed password exists in database. Let's assume DB is very simple:
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
User
login String
passHash Hash
UniqueL login
deriving Eq Show
Where Hash is an alias type Hash = PasswordHash PBKDF2 from https://hackage.haskell.org/package/password-2.0.1.1/docs/Data-Password-PBKDF2.html.
Also, for simplicity let's assume that both login and password are passed to my function as String.
There's a function in the module called checkPassword (https://hackage.haskell.org/package/password-2.0.1.1/docs/Data-Password-PBKDF2.html#g:3) that checks if a password produces the required hash. However, I don't know how can I use it in esqualeto where_ clause.
I came up with something like this:
type DB m a = ReaderT SqlBackend m a
checkCredentials ::(MonadIO m, MonadLogger m) => (String, String) -> DB m Bool
checkCredentials (login, password) = do
let hashFunc = (checkPassword $ mkPassword (pack password))
res <-
select $
from $ \user -> do
-- This won't wwork
where_ (user ^. UserLogin ==. val login &&. hashFunc (user ^. UserPassHash) ==. val PasswordCheckSuccess)
return user
return (negate $ null res)
but the part hashFunc (user ^. UserPassHash) obviously won't work. I guess I need to enter with my hashFunc into a monad (or two), but I have no idea how to do this.
I noticed that UserPassHash is of type EntityField User Hash. I wonder how can I turn it into EntityField User PasswordCheck.
Im am using a family account (premium) and this code returns a'Premium required' error. My code is as follows:
device_id = '0d1841b0976bae2a3a310dd74c0f3df354899bc8'
def playSpotify():
client_credentials_manager = SpotifyClientCredentials(client_id='<REDACTED>', client_secret='<REDACTED>')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
playlists = sp.user_playlists('gh8gflxedxmp4tv2he2gp92ev')
#while playlists:
#for i, playlist in enumerate(playlists['items']):
#print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['uri'], playlist['name']))
#if playlists['next']:
#playlists = sp.next(playlists)
#else:
#playlists = None
#sp.shuffle(true, device_id=device_id)
#sp.repeat(true, device_id=device_id)
sp.start_playback(device_id=device_id, context_uri='spotify:playlist:4ndG2qFEFt1YYcHYt3krjv')
When using SpotifyClientCredentials the token that is generated doesn't belong to any user but to an app, hence the error message.
What you need to do is use SpotifyOAuth instead. So to initialize spotipy, just do:
sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
This will open a browser tab and require you to sign in to your account.
Please help I was trying to call watson assistant endpoint
https://gateway.watsonplatform.net/assistant/api/v1/workspaces/myworkspace/logs?version=2018-09-20 to get all the list of events
and filter by date range using this params
var param =
{ workspace_id: '{myworkspace}',
page_limit: 100000,
filter: 'response_timestamp%3C2018-17-12,response_timestamp%3E2019-01-01'}
apparently I got any empty response below.
{
"logs": [],
"pagination": {}
}
Couple of things to check.
1. You have 2018-17-12 which is a metric date. This translates to "12th day of the 17th month of 2018".
2. Assuming the date should be a valid one, your search says "Documents that are Before 17th Dec 2018 and after 1st Jan 2019". Which would return no documents.
3. Logs are only generated when you call the message() method through the API. So check your logging page in the tooling to see if you even have logs.
4. If you have a lite account logs are only stored for 7 days and then deleted. To keep logs longer you need to upgrade to a standard account.
Although not directly related to your issue, be aware that page_limit has an upper hard coded limit (IIRC 200-300?). So you may ask for 100,000 records, but it won't give it to you.
This is sample python code (unsupported) that is using pagination to read the logs:
from watson_developer_cloud import AssistantV1
username = '...'
password = '...'
workspace_id = '....'
url = '...'
version = '2018-09-20'
c = AssistantV1(url=url, version=version, username=username, password=password)
totalpages = 999
pagelimit = 200
logs = []
page_count = 1
cursor = None
count = 0
x = { 'pagination': 'DUMMY' }
while x['pagination']:
if page_count > totalpages:
break
print('Reading page {}. '.format(page_count), end='')
x = c.list_logs(workspace_id=workspace_id,cursor=cursor,page_limit=pagelimit)
if x is None: break
print('Status: {}'.format(x.get_status_code()))
x = x.get_result()
logs.append(x['logs'])
count = count + len(x['logs'])
page_count = page_count + 1
if 'pagination' in x and 'next_url' in x['pagination']:
p = x['pagination']['next_url']
u = urlparse(p)
query = parse_qs(u.query)
cursor = query['cursor'][0]
Your logs object should contain the logs.
I believe the limit is 500, and then we return a pagination URL so you can get the next 500. I dont think this is the issue but once you start getting logs back its good to know
So I am using a gift certificate module with satchmo store and in order to send multiple gift certificate codes equal to the number of items purchased I need to add a loop doing
"while quantity is greater than zero loop"
Here is the code, the loop is being added to right before "price=order_item.unit_price"
def order_success(self, order,
order_item):
log.debug("Order success called, creating gift certs on order:
%s", order)
message = ""
email = ""
for detl in order_item.orderitemdetail_set.all():
if detl.name == "email":
email = detl.value
elif detl.name == "message":
message = detl.value
price=order_item.unit_price
log.debug("Creating gc for %s", price)
gc = GiftCertificate(
order = order,
start_balance= price,
purchased_by = order.contact,
valid=True,
message=message,
recipient_email=email
)
gc.save()
I am not sure I understand the question, but maybe something like
for ix in range(0, order_item.quantity):
... do stuff
might do the trick. You don't have to use the ix anywhere inside the loop, it is just (arguably) the standard way to do something n times in Python.