How to do a "while quantity is greater than zero loop" - loops

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.

Related

How to display array values in Shopify Script Editor?

With the holidays coming up, my team is working on developing a script for our Shopify store that prevents our customers from using discount codes if they have one of the following in their cart : Donations, Items already on sale, and items that qualify for a F30 335i giveaway. Here is the code I currently have :
##disable discount codes##
error_message = 'Cannot use Discount. Reason(s) : '
marzano_donation_id = 6723597598805
marzano_donation = false
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
puts product.id
if Input.cart.discount_code != nil
# only runs if customer has discount code
if product.id == marzano_donation_id
# marzano_donation = true
marzano_error = "Marzano's Donation in cart, "
error_message.concat(marzano_error)
# Input.cart.discount_code.reject({message: "1"})
end
end
end
list_of_invalid_vendors = []
vendor_message = "Invalid vendors in cart : #{list_of_invalid_vendors}"
contains_vendor = false
vendor_list = ["Evolution Racewerks", "Kies Giveaway Items", "Precision Raceworks"]
Input.cart.line_items.each do |line_item|
vendor = line_item.variant.product.vendor
if vendor_list.include? vendor
list_of_invalid_vendors.append(vendor)
if Input.cart.discount_code != nil
error_message.concat(vendor_message)
puts list_of_invalid_vendors
puts vendor_message
end
puts list_of_invalid_vendors
end
end
puts contains_vendor
contains_giveaway = false
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
next unless product.tags.include?('Kies Giveaway Items')
# Input.cart.discount_code.reject({message: "3"})
# contains_giveaway = true
giveaway_error = " Cannot use discount code on Kies Giveaway Items, "
error_message.concat(giveaway_error)
end
puts contains_giveaway
puts "123"
if Input.cart.discount_code != nil
Input.cart.discount_code.reject({message: "#{error_message}"})
end
Output.cart = Input.cart
Currently with this output, I can get the error message I want -- but only when it is a string.
The last piece to my puzzle is needed to be able to display the invalid vendors that the customer has in their cart, shown here :
list_of_invalid_vendors = []
vendor_message = "Invalid vendors in cart : #{list_of_invalid_vendors}"
contains_vendor = false
vendor_list = ["Evolution Racewerks", "Kies Giveaway Items", "Precision Raceworks"]
Input.cart.line_items.each do |line_item|
vendor = line_item.variant.product.vendor
if vendor_list.include? vendor
list_of_invalid_vendors.append(vendor)
if Input.cart.discount_code != nil
error_message.concat(vendor_message)
puts list_of_invalid_vendors
puts vendor_message
end
puts list_of_invalid_vendors
end
end
What I would like to have is code that outputs : "Cannot use discount, Invalid vendors in cart : Evolution racewerks, Precision Raceworks"
But instead what I keep on getting is :
Cannot use Discount. Reason(s) : Invalid vendors in cart : []
So to clarify -- my initial issue was that the output I was receiving was the following : Cannot use Discount. Reason(s) : Invalid vendors in cart : [] -- when in reality what I needed to be displayed in the cart was : "Invalid vendors in cart : Evolution racewerks, Precision raceworks..." What I also wanted to avoid was the content of the array being displayed, as in -- Invalid vendors in cart : ["evolution racewerks', ...] -- SO upon further research, what I discovered was that my issue was in this line here :
vendor_message = "Invalid vendors in cart : #{list_of_invalid_vendors}"
Im not entirely sure why this wouldn't work, but when I printed out "list_of_invalid_vendors", it didn't return null, but when I printed out vendor_message, it did.
So for me to be able to take an array, append values to it, and create a clean looking sentence that was easy to read for my user, i wrote the following :
invalid_vendors = invalid_vendors.join(', ')
vendor_message = "Black Friday Vendors in Cart : #{invalid_vendors}, "
error_message.concat(vendor_message)

How to have discord.py bot look for a message from a specific user recently?

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:
...

Retry loop until condition met

I am trying to navigate my mouse on object but I want to create a condition that will check if "surowiec" is still on the screen, if not I want to skip loop and go to another one. After it finish the second one get back to first and repeat.
[error] script [ Documents ] stopped with error in line 12 [error] FindFailed ( can not find surowiec.png in R[0,0 1920x1080]#S(0) )
w_lewo = Location(345,400)
w_prawo = Location(1570,400)
w_gore = Location(345,400)
w_dol = Location(345,400)
surowiec = "surowiec.png"
while surowiec:
if surowiec == surowiec:
exists("surowiec.png")
if exists != None:
click("surowiec.png")
wait(3)
exists("surowiec.png")
elif exists == None:
surowiec = None
click(w_prawo)
wait(8)
surowiec = surowiec
How about a small example:
while True:
if exists(surowiec):
print('A')
click(surowiec)
else:
print('B')
break
A while loop that is True will always run, until it it meets a break to exit the loop. Also have a look at the functions that are available in Sikuli, it can somethimes be hard to find them, that they are available. So here are a few nice ones:
Link: Link 1 and Pushing keys and Regions
The commands that I found myself very usefull are is exists and if not exists, and find that will allow to locate an image on the screen. Then you don't have to find an image over and over again if it stays on the same location. image1 = find(surowiec)

How to build an array comprised of two others using only particular elements of each?

I writing a little program to generate some bogus top-ten sales numbers for book sales. I'm trying to do this in as compact a fashion as possible and do it without using MySQL or another DB.
I have written out what I want to happen. I've created a bogus catalog array and a bogus sales array corresponding sales to the index of the catalog entries. That part all works great.
I want to create a third array that includes all the titles from the catalog array with the sales numbers from the sales array, like a join in a DB, but without any DB. I can't figure out how to do that part of it though. I think once I have it in there I can sort it the way I want it, but making that third array is killing. I cannot figure out what I'm doing wrong or how to do it right.
So given the following code:
require 'random_word'
class BestOnline
def initialize
#catalog = Array.new
#sales = Array.new
#topten = Array.new
inventory = rand(50) + 10
days = rand(1..50)
now = Time.now
yesterday = now - 86400
saleshistory = now - (days * 86400)
(1..inventory).each do
#catalog << {
:title => "#{RandomWord.adjs.next.capitalize} #{RandomWord.nouns.next.capitalize}",
:price => rand(5.99..29.99).round(2)}
end
(0..days).each do
#sales << {
:id => rand(0..#catalog.count),
:salescount => rand(0..24),
:date => rand(saleshistory..now) }
end
end
def bestsellers
#sales.each do
# THIS DOESNT WORK AND I'M STUCK AS HOW TO FIX IT.
# #topten << {
# :title => #catalog[:id],
# :salescount => #sales[:salescount]
# }
end
puts #topten.group_by{ |tt| tt[:salescount]}.sort_by{ |k,v| -k}.first(10)
end
end
BestOnline.new.bestsellers
How can I create a third array that contains the titles and number of sales and output the result of the top-ten books sold?
Try this out:
def bestsellers
#sales.each do |sale|
#topten << {
title: #catalog[sale[:id]][:title],
salescount: sale[:salescount] }
end
#topten.sort! { |x, y| y[:salescount] <=> x[:salescount] }
puts #topten.first(10)
end
I suggest you write:
def bestsellers(sales)
sales.max_by(10) { |h| h[:salescount][:salescount]] }
end
puts bestsellers(sales)
Enumerable#max_by was permitted to have an argument in Ruby v2.2.
There are several problems with the way you've structured your code. Now that you have running code (by incorporating #fbonds66's answer), I suggest you post it at SO's sister-site Code Review. The purpose of CR is to suggest improvements to working code. If you read through some of the questions and answers there I think you will be impressed.
I was doing the dereferencing wrong trying to build the 3rd array of the 1st two:
#sales.each do |sale|
#topten << {
:title => #catalog[sale[:id]][:title],
:salescount => sale[:salescount]
}
end
I needed to work on the hash returned from .each as |sale| and use correct syntax to get what I was after from the other arrays.

Matlab string manipulation

I need help with matlab using 'strtok' to find an ID in a text file and then read in or manipulate the rest of the row that is contained where that ID is. I also need this function to find (using strtok preferably) all occurrences of that same ID and group them in some way so that I can find averages. On to the sample code:
ID list being input:
(This is the KOIName variable)
010447529
010468501
010481335
010529637
010603247......etc.
File with data format:
(This is the StarData variable)
ID>>>>Values
002141865 3.867144e-03 742.000000 0.001121 16.155089 6.297494 0.001677
002141865 5.429278e-03 1940.000000 0.000477 16.583748 11.945627 0.001622
002141865 4.360715e-03 1897.000000 0.000667 16.863406 13.438383 0.001460
002141865 3.972467e-03 2127.000000 0.000459 16.103060 21.966853 0.001196
002141865 8.542932e-03 2094.000000 0.000421 17.452007 18.067214 0.002490
Do not be mislead by the examples I posted, that first number is repeated for about 15 lines then the ID changes and that goes for an entire set of different ID's, then they are repeated as a whole group again, think [1,2,3],[1,2,3], the main difference is the values trailing the ID which I need to average out in matlab.
My current code is:
function Avg_Koi
N = evalin('base', 'KOIName');
file_1 = evalin('base', 'StarData');
global result;
for i=1:size(N)
[id, values] = strtok(file_1);
result = result(id);
result = result(values)
end
end
Thanks for any assistance.
You let us guess a lot, so I guess you want something like this:
load StarData.txt
IDs = { 010447529;
010468501;
010481335;
010529637;
010603247;
002141865}
L = numel(IDs);
values = cell(L,1);
% Iteration through all arrays and creating an cell array with matrices for every ID
for ii=1:L;
ID = IDs{ii};
ID_first = find(StarData(:,1) == ID,1,'first');
ID_last = find(StarData(:,1) == ID,1,'last');
values{ii} = StarData( ID_first:ID_last , 2:end );
end
When you now access the index ii=6 adressing the ID = 002141865
MatrixOfCertainID6 = values{6};
you get:
0.0038671440 742 0.001121 16.155089 6.2974940 0.001677
0.0054292780 1940 0.000477 16.583748 11.945627 0.001622
0.0043607150 1897 0.000667 16.863406 13.438383 0.001460
0.0039724670 2127 0.000459 16.103060 21.966853 0.001196
0.0085429320 2094 0.000421 17.452007 18.067214 0.002490
... for further calculations.

Resources