Append does not work in For Loop - python

first_sale_all_menu = []
for one_product_category in Product_Category.objects.all().filter(slug__in=('3-pack-items-c', '3-pack-items-b', '3-pack-items', '3-pack-items-d')):
link_to_mamapedia_cat = link_to_home_page + one_product_category.get_absolute_url()
mamapedia_category_name = one_product_category.name
if (one_product_category.image_for_top_menu != None):
header_image = link_to_home_page + one_product_category.main_picture.url # TODO use thumbnail
else:
header_image = ''
first_sale_all_menu.append({
'menu_children_url' : link_to_mamapedia_cat,
'menu_children_title' : mamapedia_category_name,
'menu_product_image_src' : header_image
})
Somehow that append() method does not work, it is still empty list for first_sale_all_menu.
Just to make sure, even this does not work:
first_sale_all_menu = []
for one_product_category in Product_Category.objects.all().filter(slug__in=('3-pack-items-c', '3-pack-items-b', '3-pack-items', '3-pack-items-d')):
link_to_mamapedia_cat = link_to_home_page + one_product_category.get_absolute_url()
mamapedia_category_name = one_product_category.name
if (one_product_category.image_for_top_menu != None):
header_image = link_to_home_page + one_product_category.main_picture.url # TODO use thumbnail
else:
header_image = ''
first_sale_all_menu.append({
'menu_children_url': 'link_to_mamapedia_cat',
'menu_children_title': 'mamapedia_category_name',
'menu_product_image_src': 'header_image'
})
But this works:
first_sale_all_menu = []
first_sale_all_menu.append({
'menu_children_url': 'link_to_mamapedia_cat',
'menu_children_title': 'mamapedia_category_name',
'menu_product_image_src': 'header_image'
})
I don't know why, but append() does not work inside my for loop. And yes, link_to_mamapedia_cat, mamapedia_category_name, header_image all have String values.
Ok i got the problem, turns out the query never got executed, wrong Model. Haha.

The point is, very simple, your loop hasn't been executed. You can add an output to check.
first_sale_all_menu = []
for one_product_category in Product_Category.objects.all().filter(slug__in=('3-pack-items-c', '3-pack-items-b', '3-pack-items', '3-pack-items-d')):
print(1)
link_to_mamapedia_cat = link_to_home_page + one_product_category.get_absolute_url()
mamapedia_category_name = one_product_category.name
if (one_product_category.image_for_top_menu != None):
header_image = link_to_home_page + one_product_category.main_picture.url # TODO use thumbnail
else:
header_image = ''
first_sale_all_menu.append({
'menu_children_url' : link_to_mamapedia_cat,
'menu_children_title' : mamapedia_category_name,
'menu_product_image_src' : header_image
})

Related

I can't make reference to the checkbutton variable 2 times, in the second it says the name is not defined

Can anyone tell me why I can only refer to the Checkbutton variable once? the important part of code is bold.
The first time that I use the variable it run, but the second, the same variable dont work. I think I tried very much but dont work!
def botao_executar():
botão_executar = comand of Button
if (pag1 <= numero_quadros):
img1 = cv.imread('imagemfinal.jpg')
novo_y_1 = int(num_novos_y*1)
crop_image_1 = img1[0:novo_y_1]
status = cv.imwrite('Desktop\ORC/crop_image1.png', crop_image_1)
q = 590
a = (q+220)
z = (q-590)
p = (q+250)
#Dimensoes_1
crop_image_1_1_dimensoes = crop_image_1[q+60:a-20, z:p]
status_dimensoes = cv.imwrite('Desktop\ORC/crop_image1.1_dimensoes.png', crop_image_1_1_dimensoes)
img_1_1_dimensoes = PIL.Image.open('Desktop\ORC/crop_image1.1_dimensoes.png')
pytesseract.pytesseract.tesseract_cmd =r'C:\Users\joaoccfaria\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'
result_1_1_dimensoes = pytesseract.image_to_string(img_1_1_dimensoes, config='--psm 6 digits')
with open('abc.txt',mode ='w') as file:
file.write(result_1_1_dimensoes)
if v_dimensoes.get()> 0:
v_dimensoes.get= variable of checkbutton here it works!
print('dimensoes_1 = '+ result_1_1_dimensoes + ';')
sheet.write('A1', result_1_1_dimensoes)
else:
pass
pag2 = 2
if (pag2 <= numero_quadros):
img2 = cv.imread('imagemfinal.jpg')
novo_y_1 = int(num_novos_y*1)
crop_image_2 = img2[novo_y_1:novo_y_1*2]
status = cv.imwrite('Desktop\ORC/crop_image2.png', crop_image_2)
q = 590
a = (q+220)
z = (q-590)
p = (q+250)
#Dimensoes_2
crop_image_2_1_dimensoes = crop_image_2[q+60:a-20, z:p]
status_dimensoes = cv.imwrite('Desktop\ORC/crop_image2.1_dimensoes.png', crop_image_2_1_dimensoes)
img_2_1_dimensoes = PIL.Image.open('Desktop\ORC/crop_image2.1_dimensoes.png')
pytesseract.pytesseract.tesseract_cmd =r'C:\Users\joaoccfaria\AppData\Local\Programs\Tesseract-OCR\tesseract.exe'
result_2_1_dimensoes = pytesseract.image_to_string(img_2_1_dimensoes, config='--psm 6 digits')
with open('abc.txt',mode ='w') as file:
file.write(result_2_1_dimensoes)
if v_dimensoes.get()> 0:
here the same variable, but says that the name is not defined
print('dimensoes_2 = '+ result_2_1_dimensoes + ';')
sheet.write('A21', result_2_1_dimensoes)
else:
pass
Thanks in advance, any suggestion. Compliments.

Template to parse json.loads message

I have so much similar codes in my script
sinkId = json_string_into_dict["wirepas"]["packetReceivedEvent"]["header"]["sinkId"]
eventId = json_string_into_dict["wirepas"]["packetReceivedEvent"]["header"]["eventId"]
sourceAddress = json_string_into_dict["wirepas"]["packetReceivedEvent"]["sourceAddress"]
destinationAddress = json_string_into_dict["wirepas"]["packetReceivedEvent"]["destinationAddress"]
sourceEndpoint = json_string_into_dict["wirepas"]["packetReceivedEvent"]["sourceEndpoint"]
How can I define template to void duplicate part of code?
I want to do it something like it
PARSING_TEMPLATE = json_string_into_dict["wirepas"]["packetReceivedEvent"]["header"]
PARSING_TEMPLATE + ["sinkId"]
PARSING_TEMPLATE + ["eventId"]
PARSING_TEMPLATE + ["sourceAddress"]
PARSING_TEMPLATE + ["destinationAddress"]
PARSING_TEMPLATE + ["sourceEndpoint"]
You might as well just reference down to the "packetReceivedEvent" key:
packetReceivedEvent = json_string_into_dict["wirepas"]["packetReceivedEvent"]
sinkId = packetReceivedEvent["header"]["sinkId"]
eventId = packetReceivedEvent["header"]["eventId"]
sourceAddress = packetReceivedEvent["sourceAddress"]
destinationAddress = packetReceivedEvent["destinationAddress"]
sourceEndpoint = packetReceivedEvent["sourceEndpoint"]

How to add auto unfollow module to the fallowing code?

This is a python code and list users that I only follow them. I would like to use the same list by adding a module for auto unfollowing:
.
.
.
def get_unfollowers(browser):
"""
Opens the profile, obtains the follower and following list
Returns the names of the users who are in the following list, but not in the follower list
"""
to_profile = browser.find_element_by_xpath("//a[contains(#href, '/{}')]".format(username))
to_profile.click()
sleep(3)
to_following = browser.find_element_by_xpath("//a[contains(#href, '/following')]")
to_following.click()
following_list = get_name(browser)
to_followers = browser.find_element_by_xpath("//a[contains(#href, '/followers')]")
to_followers.click()
followers_list = get_name(browser)
not_following_back = [user for user in following_list if user not in followers_list]
print(not_following_back) # prints a list with every name separated by a comma
def get_name(browser):
sleep(2)
scroll_box = browser.find_element_by_class_name('isgrP')
p_height, height = 0, 1
while p_height != height:
p_height = height
sleep(2)
height = browser.execute_script(
"arguments[0].scrollTo(0, arguments[0].scrollHeight); return arguments[0].scrollHeight;", scroll_box)
total_list = scroll_box.find_elements_by_tag_name('li')
names = [name.text for name in total_list if name.text != '']
close_dub = browser.find_element_by_xpath("/html/body/div[4]/div/div/div[1]/div/div[2]/button")
close_dub.click()
return names
get_unfollowers(browser)
This is the code that I wrote and worked to unfollow list I want
def do_unfolow(list):
for x in list:
print(x)
browser.get('https://www.instagram.com/'+x)
# tempy2 = browser.find_element_by_css_selector(".vBF20._1OSdk")
#if not tempy2:
tempy2 = browser.find_element_by_css_selector(".glyphsSpriteFriend_Follow")
#tempy2 = browser.find_element_by_css_selector("Igw0E.rBNOH.YBx95._4EzTm")
tempy2.click()
tempy2 = browser.find_element_by_xpath("//button[contains(text(), 'Unfollow')]")
tempy2.click()
sleep(10)

Appending a python dict from a while loop gives unexpected results

The max number of records in my input json is 100 however there is a paging-next link that provides the next 100 records. Below is what I have but it returns a dict with only 100 entries- I know there are more- How should I modify this function to get all the records?
def process_comment_json(comment_json):
post_comment_dict = dict()
next_links = list()
if 'comments' in comment_json.keys():
try:
for y in comment_json['comments']['data']:
post_id = comment_json['id']
commentor_name = y['from']['name']
commentor_id = y['from']['id']
created_time = y['created_time']
message = remove_non_ascii(y['message'])
sentiment = return_sentiment_score(message)
post_comment_dict[commentor_id] = {'commentor_name':commentor_name,\
'created_time':created_time, 'message':message,\
'sentiment':sentiment}
except:
print("malformed data, skipping this comment in round1")
if 'next' in comment_json['comments']['paging']:
print('found_next appending')
next_links.append(comment_json['comments']['paging']['next'])
else:
return post_comment_dict
while next_links:
print("processing next_links")
print("current len of post_comment_dict is:", len(post_comment_dict))
for next_link in next_links:
t = requests.get(next_link)
nl_json = t.json()
next_links.pop()
if "data" in list(nl_json.keys()):
for record in nl_json['data']:
try:
for y in comment_json['comments']['data']:
post_id = comment_json['id']
commentor_name = y['from']['name']
commentor_id = y['from']['id']
created_time = y['created_time']
message = remove_non_ascii(y['message'])
sentiment = return_sentiment_score(message)
post_comment_dict[commentor_id] = {'commentor_name':commentor_name,\
'created_time':created_time, 'message':message,\
'sentiment':sentiment}
except:
print("malformed data, skipping this comment from the next_links list")
if 'next' in comment_json['comments']['paging']:
print('found_next appending')
next_links.append(comment_json['comments']['paging']['next'])
else:
return post_comment_dict

Raname script for Python in Maya

I have this script and I want to parent the controls together and rename the icons. Right now it names the groups, but doesn't name the controls or parents them. Can anyone help me?
def priming(*args):
jointChain = pm.ls(sl = True, dag = True)
jointChain.pop(-1)
ori = raw_input()
systemName = raw_input()
suffix = "prime"
prime1Name = "{0}_{1}_00_{2}1".format(ori, systemName, suffix)
prime2Name = "{0}_{1}_00_{2}2".format(ori, systemName, suffix)
pm.select(cl = True)
for jointName in jointChain:
primeIcon = pm.circle(nr = [1, 0, 0])
groupOne = pm.group(em = True, n = prime1Name)
groupTwo = pm.group(em = True, n = prime2Name)
pm.parent(groupTwo, groupOne)
pm.parent(primeIcon, groupTwo)
tempConstraint = pm.parentConstraint(jointName, groupOne, mo = False)
pm.delete(tempConstraint)
pm.makeIdentity(primeIcon, a = True, t = 1, r = 1, s = 1)
tempConstraintTwo = pm.orientConstraint(primeIcon, jointName, mo = True)
Here is a modified version of your code. This one parents the groups and the controllers and also names them based on a naming scheme (that you can tweak if needed):
def priming(*args):
jointChain = pm.ls(sl=True, dag=True)
print jointChain
jointChain.pop(-1)
print jointChain
ori = raw_input()
systemName = raw_input()
suffix = "prime"
prime1Name = "{0}_{1}_00_{2}1".format(ori, systemName, suffix)
prime2Name = "{0}_{1}_00_{2}2".format(ori, systemName, suffix)
iconNameBase = "your_icon" # Your icon naming scheme here
pm.select(cl=True)
last_created_icon = None
name_index = 1
for jointName in jointChain:
# Modify your iconName with every iteration here
# Sample scheme: your_icon_1, your_icon_2 etc.
iconName = "%s_%i" % (iconNameBase, name_index)
name_index += 1
primeIcon = pm.circle(nr=[1, 0, 0], n=iconName)
groupOne = pm.group(em=True, n=prime1Name)
groupTwo = pm.group(em=True, n=prime2Name)
pm.parent(groupTwo, groupOne)
pm.parent(primeIcon, groupTwo)
tempConstraint = pm.parentConstraint(jointName, groupOne, mo=False)
pm.delete(tempConstraint)
pm.makeIdentity(primeIcon, a=True, t=True, r=True, s=True)
tempConstraintTwo = pm.orientConstraint(primeIcon, jointName, mo=True)
if last_created_icon:
pm.parent(groupOne, last_created_icon)
last_created_icon = primeIcon

Categories