Class Methods not linking to Tkinter GUI - class

it seems my Tkinter GUI is fine however when loaded the buttons which should activate the class methods do nadda.
I was originally trying to initiate a class instance within the main:
if_name_== "main":
ed.EditorUI()
Where 'self' is used below 'ed' was in its place.. it said ed was undefined which prompted me to try this way.
As you can probably tell its been a few years since I've coded.
Your help is much appreciated!
import CU_picture
import filters
import Tkinter
root = Tk()
root.title('Photo Editor Version 1.10')
#root.iconbitmap(bitmap = '12.ico')
#img = PhotoImage(file='12.ico')
#root.tk.call('wm', 'iconphoto', root._w, img)
#Adding File Menu
menubar = Tkinter.Menu(root)
filemenu = Tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
#Display above menus
root.config(menu=menubar)
class EditorUI(object):
def __init__(self):
self.name = "EditorUI"
self.pic = 0
self.pix = CU_picture.Picture()
self.filters = "No Current Filters Applied"
self.special = "cake"
def get_specific_color(color):
if color == "red":
return CU_picture.Color(255, 0, 0)
elif color == "aqua":
return CU_picture.Color(0, 255, 255)
elif color == "fuschia":
return CU_picture.Color(255, 0, 255)
elif color == "lime":
return CU_picture.Color(0, 255, 0)
elif color == "yellow":
return CU_picture.Color(255, 255, 0)
def load():
self.pix = get_picture()
self.pix.show()
self.pic = 1
error.set("Pic Loaded: "+self.filters)
outtext.set("New Picture - Not Saved.")
self.filters = "No Current Filters Applied"
self.special = "cake"
para.set("")
def save():
if self.pic == 0:
error.set("No Pic Loaded")
else:
name = intext.get() + ".jpg"
self.pix.write_to(name)
outtext.set("Saved To Given Filename.")
para.set("")
def negative():
if self.pic == 0:
error.set("No Pic Loaded")
else:
n = filters.NegativeFilter()
n.apply(ed.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Negative-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Negative-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def grayscale():
if self.pic == 0:
error.set("No Pic Loaded")
else:
g = filters.GrayScaleFilter()
g.apply(self.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Grayscale-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Grayscale-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def posterize():
if self.pic == 0:
error.set("No Pic Loaded")
else:
p = filters.PosterizeFilter()
p.apply(self.pix)
self.pix.show()
para.set("")
if self.filters == "No Current Filters Applied":
self.filters = "Posterize-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Posterize-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def highlight():
if self.pic == 0:
error.set("No Pic Loaded")
else:
if intext.get() == "":
para.set("Input Highlight distance/Colour and try again(one at a time).")
elif self.special == "cake" and intext.get() != "":
self.special = intext.get()
outtext.set("Highlight distance: " + self.special)
para.set("Input Highlight colour(red, blue, aqua, fuschia, lime, yellow) for the final step.")
elif self.special != "cake" and intext.get() != "":
color = get_specific_color(intext.get())
h = filters.HighlightFilter()
h.set_distance(float(self.special))
h.set_color(color)
outtext.set("Highlight colour: " + intext.get())
h.apply(self.pix)
self.pix.show()
if self.filters == "No Current Filters Applied":
self.filters = "Highlight-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Highlight-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def edge():
if self.pic == 0:
error.set("No Pic Loaded")
else:
para.set("Threshold?")
if intext.get() == "":
para.set("Input Threshold value and try again.")
else:
para.set("Threshold: " + intext.get())
e = filters.EdgeFilter()
e.set_threshold(float(intext.get()))
e.apply(self.pix)
self.pix.show()
if self.filters == "No Current Filters Applied":
self.filters = "Edge-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
else:
self.filters = self.filters + ", Edge-F"
error.set("Pic Loaded + Current Filters: "+self.filters)
def get_picture():
"""
Interactively select a picture file and return it.
"""
# Pop up a dialogue box to select a file
file = CU_picture.pick_a_file()
# Open the file containing the picture and load it
pict = CU_picture.load_picture(file)
return pict
if __name__ == "__main__":
EditorUI()
intext = Tkinter.StringVar()
outtext = Tkinter.StringVar()
error = Tkinter.StringVar()
para = Tkinter.StringVar()
inp = Tkinter.Entry(root, textvariable=intext)
out = Tkinter.Label(root, textvariable=outtext)
ER = Tkinter.Label(root, textvariable=error)
P = Tkinter.Label(root, textvariable=para)
load = Tkinter.Button(root, text="Load", height=2, width=20, command=load)
save = Tkinter.Button(root, text="Save", height=2, width=20, command=save)
negative = Tkinter.Button(root, text="Negative-F", height=1, width=20, command=negative)
grayscale = Tkinter.Button(root, text="Grayscale-F", height=1, width=20, command=grayscale)
posterize = Tkinter.Button(root, text="Posterize-F", height=1, width=20, command=posterize)
highlight = Tkinter.Button(root, text="Highlight-F", height=1, width=20, command=highlight)
edge = Tkinter.Button(root, text="Edge-F", height=1, width=20, command=edge)
inp.grid(row=1, column=7)
ER.grid(row=0, column= 0, columnspan=5, rowspan=2)
out.grid(row=1, column= 0, columnspan=5, rowspan=2)
P.grid(row=2, column= 0, columnspan=5, rowspan=2)
load.grid(row=0, column=6)
save.grid(row=0, column=7)
negative.grid(row=1, column=6)
grayscale.grid(row=3, column=7)
posterize.grid(row=3, column=6)
highlight.grid(row=2, column=6)
edge.grid(row=2, column=7)
root.mainloop()

One of the main problems that I see (other than what #A.Rodas mentioned above) that would prevent the buttons from doing anything is that your button commands are not actually targeting the class methods. They're looking for root-level callables named "load", "save", etc. Because these don't exist, you should be getting errors, and yet you say the interface works fine aside from the buttons not cooperating, which doesn't make sense to me.
To call the class methods, you must create an instance of the class. First fix the self issue mentioned by #A.Rodas above, then replace the __main__ check with this:
editor = EditorUI()
Then modify the button commands to call the methods on the editor instance:
load = Tkinter.Button(root, text="Load", height=2, width=20, command=editor.load)
save = Tkinter.Button(root, text="Save", height=2, width=20, command=editor.save)
negative = Tkinter.Button(root, text="Negative-F", height=1, width=20, command=editor.negative)
grayscale = Tkinter.Button(root, text="Grayscale-F", height=1, width=20, command=editor.grayscale)
posterize = Tkinter.Button(root, text="Posterize-F", height=1, width=20, command=editor.posterize)
highlight = Tkinter.Button(root, text="Highlight-F", height=1, width=20, command=editor.highlight)
edge = Tkinter.Button(root, text="Edge-F", height=1, width=20, command=editor.edge)
You may also consider moving all the interface creation stuff inside the EditorUI class, unless you have some other reason for keeping it separate.

Related

bypass 'google before you continue' pop-up

My code:
import pandas
import requests
from bs4 import BeautifulSoup
from pywebio.input import *
from pywebio.output import *
from time import sleep
from pywebio import start_server
print("News web application successfully started!")
def app():
request = requests.get("https://news.google.com/topics/CAAqRggKIkBDQklTS2pvUVkyOTJhV1JmZEdWNGRGOXhkV1Z5ZVlJQkZRb0lMMjB2TURKcU56RVNDUzl0THpBeFkzQjVlU2dBUAE/sections/CAQqSggAKkYICiJAQ0JJU0tqb1FZMjkyYVdSZmRHVjRkRjl4ZFdWeWVZSUJGUW9JTDIwdk1ESnFOekVTQ1M5dEx6QXhZM0I1ZVNnQVAB?hl=en-US&gl=US&ceid=US%3Aen")
content = BeautifulSoup(request.content, 'html.parser')
find = content.find('div', class_='ajwQHc BL5WZb')
#open('test.html', 'w').write(findstr.find)
h3 = find.find_all('h3')
time = find.find_all('time')
link = find.find_all('article')#.find_all('a').get('href').replace('.', '')
result = []
#print('https://news.google.com' + link)
#put_html('<table border="1" width="100%" cellpadding="5">')
source = find.find_all('a', {'data-n-tid' : '9'})
time = find.find_all('time')
textoutput = []
textoutput1 = []
textoutput2 = []
takeoutput3 = []
#writer = open('news.csv', 'w')
#writer1 = csv.writer(writer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for text in h3:
a1 = text.text
textoutput.append(a1)
for text2 in source:
a3 = text2.text
textoutput1.append(a3)
for text1 in time:
a5 = text1.text
textoutput2.append(a5)
#for result in link:
# alinks = result.find_all('a')
# alinks1 = []
# for alinks1 in alinks:
# alinks2 = alinks1.get('href')
# alinksreplace = str(alinks2)
# alinksreplace1 = alinksreplace.replace(".", "")
# alinksreplace2 = alinksreplace1.replace("None", "")
#
# if (alinksreplace2 != ''):
# if "publications" not in alinksreplace2:
# a = "https://news.google.com" + alinksreplace2
# takeoutput3.append(a)
pandas.set_option('display.max_colwidth', None)
frame = {'Title':textoutput, 'Time':textoutput2, 'Source' : textoutput1}
frame1 = pandas.DataFrame(frame)
#frame2 = {'Link' : takeoutput3}
#frame3 = pandas.DataFrame(frame2)
frametostring = frame1.to_string(index=False)
#frametostring1 = frame3.to_string(index=False)
#print(frametostring)
put_code(frametostring)
#put_code(frametostring1)
#writer1.writerow([textoutput, textoutput1, textoutput2])
start_server(app, 82)
it worked fine but today Google update something and now it don't start. And it's because Google add before you continue pop-up. How I can bypass this so my script continue to work?
If it was Selenium I've just clicked the button but here I don't know what to do
Thanks you helping!

Traceback after looping through all available news article

I am making a python CLI utility that will answer questions like "15 + 15" or "How many letters are in the alphabet".
I then decided to add the ability to search up the latest news using the newspaper module.
All of it works except when the for loop finishes, after printing a string literal, it gives me a error that I do not know what the heck it means.
Can someone decipher the error for me and if possible, help me fix the error? Thanks.
import requests
import wolframalpha
import wikipedia
import time
import sys
from threading import Thread
from newspaper import Article
import bs4
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
version = 2.1
build = '19w12a6'
ready = 0
loadingAnimationStop = 0
appId = 'CENSORED STUFF BECAUSE I DON\'T WANT ANYONE TO TOUCH MY KEY'
client = wolframalpha.Client(appId)
exitNow = 0
def loadingAnimation():
while exitNow == 0:
print("Loading: |", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
print("Loading: /", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
print("Loading: -", end='\r')
time.sleep(0.2)
while ready == 1:
time.sleep(0)
sys.stdout.write("Loading: \ \r")
time.sleep(0.2)
while ready == 1:
time.sleep(0)
hui = Thread(target = loadingAnimation, args=())
hui.start()
def search_wiki(keyword=''):
searchResults = wikipedia.search(keyword)
if not searchResults:
print("No result from Wikipedia")
return
try:
page = wikipedia.page(searchResults[0])
except wikipedia.DisambiguationError:
page = wikipedia.page(err.options[0])
wikiTitle = str(page.title.encode('utf-8'))
wikiSummary = str(page.summary.encode('utf-8'))
print(' ', end='\r')
print(wikiTitle)
print(wikiSummary)
def search(text=''):
res = client.query(text)
if res['#success'] == 'false':
ready = 1
time.sleep(1)
print('Query cannot be resolved')
else:
result = ''
pod0 = res['pod'][0]
pod1 = res['pod'][1]
if (('definition' in pod1['#title'].lower()) or ('result' in pod1['#title'].lower()) or (pod1.get('#primary','false') == 'True')):
result = resolveListOrDict(pod1['subpod'])
ready = 1
time.sleep(0.75)
print(' ', end='\r')
print(result)
question = resolveListOrDict(pod0['subpod'])
question = removeBrackets(question)
#primaryImage(question)
else:
question = resolveListOrDict(pod0['subpod'])
question = removeBrackets(question)
search_wiki(question)
def removeBrackets(variable):
return variable.split('(')[0]
def resolveListOrDict(variable):
if isinstance(variable, list):
return variable[0]['plaintext']
else:
return variable['plaintext']
#def primaryImage(title=''):
# url = 'http://en.wikipedia.org/w/api.php'
# data = {'action':'query', 'prop':'pageimages','format':'json','piprop':'original','titles':title}
# try:
# res = requests.get(url, params=data)
# key = res.json()['query']['pages'].keys()[0]
# imageUrl = res.json()['query']['pages'][key]['original']['source']
# print(imageUrl)
# except Exception:
# print('Exception while finding image:= '+str(err))
page = requests.get('https://www.wolframalpha.com/')
s = page.status_code
if (s != 200):
ready = 1
time.sleep(1)
print('It looks like https://www.wolframalpha.com/ is not online.')
print('Please check your connection to the internet and https://www.wolframalpha.com/')
print('Stopping Python Information Engine')
while True:
time.sleep(1)
page = requests.get('https://www.wikipedia.org/')
s = page.status_code
if (s != 200):
ready = 1
time.sleep(1)
print('It looks like https://www.wikipedia.org/ is not online.')
print('Please check your connection to the internet and https://www.wikipedia.org/')
print('Stopping Python Information Engine')
while True:
time.sleep(1)
ready = 1
while exitNow == 0:
print('================================================================================================')
print('Python Information Engine CLI Version', end=' ')
print(version)
print('Create by Unsigned_Py')
print('================================================================================================')
ready = 1
time.sleep(1)
print(' ', end='\r')
print(' ', end='\r')
q = input('Search: ')
print('================================================================================================')
if (q == 'Credits()'):
print('Credits')
print('================================================================================================')
print('PIE is made by Unsigned_Py')
print('Unsigned_Py on the Python fourms: https://python-forum.io/User-Unsigned-Py')
print('Contact Unsigned_Py: Ckyiu#outlook.com')
if (q == 'Latest News'):
print('DISCLAIMER: The Python Information Engine News port is still in DEVELOPMENT!')
print('Getting latest news links from Google News...')
ready = 0
news_url = "https://news.google.com/news/rss"
Client = urlopen(news_url)
xml_page = Client.read()
Client.close()
soup_page = soup(xml_page,"xml")
news_list = soup_page.findAll("item")
ready = 1
print('================================================================================================')
article_number = 1
for news in news_list:
print(article_number, end=': ')
print(news.title.text)
print(news.pubDate.text)
if (input('Read (Y or N)? ') == 'y'):
ready = 0
url = news.link.text
article = Article(url)
article.download()
article.parse()
article.nlp()
ready = 1
print('================================================================================================')
print(article.summary)
print('================================================================================================')
article_number = article_number + 1
print("That's all for today!")
if (q == 'Version()'):
print('Python Information Engine CLI Version', end=' ')
print(version)
print('Running Build', end=' ')
print(build)
print('Upon finding a bug, please report to Unsigned_Py and I will try to fix it!')
print('Looking for Python Information Engine CLI Version 1.0 - 1.9?')
print("It's called Wolfram|Alpha and Wikipedia Engine Search!")
if (q != 'Exit()'):
if (q != 'Credits()'):
if (q != 'News'):
if (q != 'Version()'):
ready = 0
search(q)
else:
exitNow = 1
print('Thank you for using Python Information Engine')
print('================================================================================================')
time.sleep(2)
ready = 0
Here's the error:
Traceback (most recent call last):
File "C:\Users\ckyiu\OneDrive\Desktop\Python Information Engine 2.1.py", line 210, in <module>
search(q)
File "C:\Users\ckyiu\OneDrive\Desktop\Python Information Engine 2.1.py", line 62, in search
res = client.query(text)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 56, in query
return Result(resp)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 178, in __init__
super(Result, self).__init__(doc)
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 62, in __init__
self._handle_error()
File "C:\Users\ckyiu\AppData\Local\Programs\Python\Python37-32\lib\site-packages\wolframalpha\__init__.py", line 69, in _handle_error
raise Exception(template.format(**self))
Exception: Error 0: Unknown error
Well I got it to work now, for some reason I put: if (q != 'News'): I wanted if (q != 'Latest News'):.
Then python threw me a error for that. I got it to work at least now.

how to access variable from another class in python

I would like to access variable lotId & qty_selected in class 'InputDialog' and to be use in class 'Mainwindow'. I did tried to find a solution in net but unable to solve it until now. can anyone show how to make it?
Here is my current code:
from __future__ import division
from skimage.measure import compare_ssim as ssim
import matplotlib.pyplot as plt
import numpy as np
import sys
import os, glob
import cv2
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import *
from inputdialog import Ui_inputDialog
from mainwindow import Ui_mainWindow
from tkinter import messagebox
class MainWindow(QtGui.QMainWindow, Ui_mainWindow):
def __init__(self, class_input):
QtGui.QMainWindow.__init__(self)
Ui_mainWindow.__init__(self)
Ui_inputDialog.__init__(self)
self.setupUi(self)
self.capture_button.clicked.connect(self.captureImage)
self.display_button.clicked.connect(self.displayImage)
self.deviceBox.activated.connect(self.selectDeviceCombo)
self.startInspectionBtn.clicked.connect(self.enterLotID)
self.display_button.clicked.connect(self.displayResults)
#self.viewResultBtn.clicked.connect(self.viewResults)
self.window2 = None
def enterLotID(self): # Dialog box will ask user to enter lot ID and wafer qty
if self.window2 is None:
self.window2 = InputDialog(self)
self.window2.isModal()
self.window2.show()
# Program need to be loop through a image file in directory
def displayImage(self, ):
os.chdir('c:\\Users\\mohd_faizal4\\Desktop\\Python\\Testing' + '\\' + lotId )
for lotId in glob.glob('*.jpeg'):
print(lotId)
sample_label = 'c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 6.jpg' # Sample image must read from current folder lot ID running the inspection
self.sample_label.setScaledContents(True)
self.sample_label.setPixmap(QtGui.QPixmap(sample_label))
def selectDeviceCombo(self):
self.var_Selected = self.deviceBox.currentText()
#print('The user selected value now is:')
print('Device = ' + self.var_Selected)
if self.var_Selected.lower() == 'xf35':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 4.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
elif self.var_Selected.lower() == 'xf38':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 5.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
elif self.var_Selected.lower() == 'x38c':
print("Great! Device Id is - " + self.var_Selected + '!')
source_label ='c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 7.jpg'
self.source_label.setScaledContents(True)
self.source_label.setPixmap(QtGui.QPixmap(source_label))
else:
print("Pls select device id. It's compulsory field!")
def captureImage(self): # Capture image and display on 'Sample' column under Inspection
cam = cv2.VideoCapture(0)
i = 1
while i < int(input(qty_selected)):
ret, frame = cam.read()
cv2.imshow('Please review an image', frame)
if not ret:
break
k = cv2.waitKey(0)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
if k % 256 == 32:
# SPACE pressed
img_name = "_{}.jpeg".format(i)
#print (img_name)
cv2.imwrite(img_name, frame)
#cv2.imwrite(os.path.join(dirname, img_name), frame)
print("{}".format(img_name))
i += 1
cam.release()
cv2.destroyAllWindows()
def displayResults(self): #Display image of wafer at 'Result' tab. Simultaneously with 'Inspect'
label_vid01 = 'c:/Users/mohd_faizal4/Desktop/Python/Image/Picture 7.jpg'
self.label_vid01.setScaledContents(True)
self.label_vid01.setPixmap(QtGui.QPixmap(label_vid01))
# A new class for user input dialog to enter lot information
class InputDialog (QtGui.QDialog, Ui_inputDialog):
def __init__(self, parent):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.okButton.clicked.connect(self.addLotId)
self.okButton.clicked.connect(self.selectWaferQty)
def addLotId(self):
lotId = str(self.strLotId.toPlainText())
self.strLotId.setText(lotId)
print(lotId)
path = 'c:\\Users\\mohd_faizal4\\Desktop\\Python\\Testing' + '\\' + lotId
if not os.path.exists(path):
os.makedirs(path)
else:
messagebox.showwarning('Error','Please enter required information')
QtGui.QMessageBox.show(self)
# User require to select wafer quantity upon enter the lot ID
def selectWaferQty(self):
qty_selected = self.waferQty.currentText()
#print ('The user selected value now is:')
print ('Wafer Qty = ' + qty_selected)
#if self.qty_selected() == '1':
# print('Great! Wafer Qty is - ' + self.qty_selected + '!')
#else:
# print ('Pls select wafer quantity!')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
Window = MainWindow()
Window.show()
sys.exit()
Under the class InputDialog, change lotId and qty_selected to self.lotId and self.qty_selected, respectively. And to access it inside your WindowMain class, try self.window2.lotId and self.window2.qty_selected.

for each group by date in coffeescript

which pulls data from and reformats it.
Promise = require "bluebird"
request = Promise.promisify require "request"
moment = require "moment"
cdn = require('config').server.cloudFrontDomain
toTitleCase = require "titlecase"
exports.getStocks = (path) ->
return new Promise (resolve, reject) ->
request path
.then (body) ->
germanStock = []
germanStocks = JSON.parse body.body
germanStocks.forEach (stock) ->
obj = {}
this.parsePart = (remaining) ->
value = remaining.value
dashIndex = value.lastIndexOf '-'
if dashIndex != -1
remaining.value = value.substring 0, dashIndex - 1
return value.substring(dashIndex + 1).trim()
else
return ''
remaining =
value: stock.name
size = parsePart remaining
colour = parsePart remaining
name = remaining.value
sku = stock.sku
styleId = sku.split(/-/)[0]
colorcode = /^(.*)-(.*)([0-9])$/.exec(sku)?[2]
bgStyle = "url(//#{cdn}/assets/product_shots/thumbs/#{styleId}-#{colorcode}.jpg)"
obj.id = sku
obj.name = name
obj.colorUrl = bgStyle
obj.colour = toTitleCase(colour.toLowerCase())
obj.size = size
obj.stock = stock.stock
obj.inProduction = ''
obj.office = 'DE'
stock.preorders.forEach (i, idx) ->
date = moment(i.date).format('DD-MM-YYYY')
if idx != stock.preorders.length - 1
obj.inProduction = obj.inProduction.concat i.amount + ' due on ' + date + ', '
else
obj.inProduction = obj.inProduction.concat i.amount + ' due on ' + date
germanStock.push obj
resolve germanStock
.catch (err) ->
reject err
where my data is like:
{
"id":1,
"stamp":"2014-09-25T12:55:30Z",
"name":" MENS T-SHIRT - BRIGHT BLUE - XS",
"sku":"SS01-BB0",
"stock":81,
"active":true,
"preorders":[
{
"id":92549,
"amount":160,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92549,
"amount":200,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92549,
"amount":1000,
"date":"2016-06-21T22:00:00Z"
}
],
"discountMatrix":0.0,
"stockNormalized":81,
"preOrdersSum":1360
},
{
"id":2,
"stamp":"2014-09-25T12:55:30Z",
"name":" MENS T-SHIRT - BRIGHT BLUE - S",
"sku":"SS01-BB1",
"stock":339,
"active":true,
"preorders":[
{
"id":92551,
"amount":240,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92438,
"amount":160,
"date":"22016-06-19T22:00:00Z"
}
],
"discountMatrix":0.0,
"stockNormalized":339,
"preOrdersSum":400
},
what is the correct way to group each preorders quantity that is on the same date, so that instead of getting:
160 due on 19-06-2016, 200 due on 19-06-2016, 1000 due on 21-06-2016
i get 360 due on 19-06-2016, 1000 due on 21-06-2016
any advice much appreciated.
You could just use an object with the date as key and the total amount for the date as value.
For each preorder, add it's amount at it's date index in this object. At the end of the iteration print the content of the object:
moment = require "moment"
data = [
{
id:1
stamp: "2014-09-25T12:55:30Z"
name: " MENS T-SHIRT - BRIGHT BLUE - XS"
sku: "SS01-BB0"
stock:81
active:true
preorders:[
{
id:92549
amount:160
date: "2016-06-19T22:00:00Z"
}
{
id:92549
amount:200
date: "2016-06-19T22:00:00Z"
}
{
id:92549
amount:1000
date: "2016-06-21T22:00:00Z"
}
]
discountMatrix:0.0
stockNormalized:81
preOrdersSum:1360
}
]
obj = {}
obj.inProduction = ""
amountByDate = {}
# for each document in your data
for doc in data
# for each preorder in your document
for preorder in doc.preorders
# add it's amount in the index equals to it's date
if amountByDate[preorder.date]
amountByDate[preorder.date] += preorder.amount
else
# or create the index with the value if it doesn't exist
amountByDate[preorder.date] = preorder.amount
for date, amount of amountByDate
if obj.inProduction != ""
obj.inProduction = obj.inProduction.concat ", #{amount} due on #{moment(date).format('DD-MM-YYYY')}"
else
obj.inProduction = obj.inProduction.concat "#{amount} due on #{moment(date).format('DD-MM-YYYY')}"
console.log obj.inProduction
Result:
360 due on 20-06-2016, 1000 due on 22-06-2016

NameError: global name 'Carnage' is not defined

I know it was asked a million times before, but I need a little help getting this working, as the code is not mine.
so like that i update a code hope it will make some undarstands of it
# coding=utf-8
import urllib, re, sys, threading, cookielib, urllib2
from BeautifulSoup import BeautifulSoup
### Головная функция
def main():
agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
aCarnage.login()
me = aCarnage.inf(aCarnage.user)
# Если ранен - выйти
if me['inj']:
aCarnage.logout()
exit(1)
aCarnage.urlopen('main.pl')
# Подождать пока здоровье восстановится
while(me['hp_wait']):
time.sleep(me['hp_wait'])
me = aCarnage.inf(aCarnage.user)
# Найти подходящую заявку
aCarnage.find()
me = aCarnage.inf(aCarnage.user)
# Если заявка состоялась - в бой!
if me['battle']: aCarnage.fight()
# После боя - выход из игры
aCarnage.logout()
class Opener:
def __init__(self, host, encoding, agent):
self.host = host
self.encoding = encoding
self.agent = agent
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
def urlopen(self, goto, data = None):
f = self.opener.open(urllib2.Request(
"http://%s/%s" % (self.host, goto),
self.urlencode(data),
{"User-agent" : self.agent}
))
result = f.read()
self.soup = BeautifulSoup(result)
def urlencode(self, data):
if data is None: return None
for key in data:
data[key] = data[key].encode(self.encoding, 'ignore')
return urllib.urlencode(data)
class CarnageBot(Opener):
### Конструктор принимает логин, пароль, кодировку (cp1251) и идентификатор браузера
def __init__(self, user, password, host, encoding, agent):
self.user = user
self.password = password
Opener.__init__(self, host, encoding, agent)
### Получить информацию об игроке - например о самом себе
def inf(self, user):
self.urlopen('inf.pl?' + self.urlencode({'user': user}))
# Кол-во жизни
onmouseover = self.soup.find('img', onmouseover = re.compile(unicode('Уровень жизни:', 'utf8')))
m = re.search('([0-9]+).([0-9]+)', onmouseover['onmouseover'])
hp = int(m.group(1))
hp_max = int(m.group(2))
hp_wait = (100 - (hp * 100) / hp_max) * 18
# Уровень
td = self.soup.find('td', text = re.compile(unicode('Уровень:', 'utf8')))
level = int(td.next.string)
# Ранен или нет
inj = 0
if self.soup.find(src = re.compile(unicode('travma.gif', 'utf8'))): inj = 1
# В бою или нет
battle = 0
if self.soup.find(text = re.compile(unicode('Персонаж находится в бою', 'utf8'))): battle = 1
hero = {'level': level, 'hp': hp, 'hp_max': hp_max, 'hp_wait': hp_wait, 'inj': inj, 'battle': battle}
return hero
### Войти в игру
def login(self):
data = {'action': 'enter', 'user_carnage': self.user, 'pass_carnage': self.password}
self.urlopen('enter.pl', data)
self.urlopen('main.pl')
### Выйти из игры
def logout(self):
self.urlopen('main.pl?action=exit')
### В бой!!!
def fight(self):
self.urlopen('battle.pl')
while True:
# Добить по таймауту
if self.soup.find(text = re.compile(unicode('Противник потерял сознание', 'utf8'))):
self.urlopen('battle.pl?cmd=timeout&status=win')
break
if self.soup.find(text = re.compile(unicode('Бой закончен.', 'utf8'))):
break
reg = re.compile(unicode('Для вас бой закончен. Ждите окончания боя.', 'utf8'))
if self.soup.find(text = reg):
break
cmd = self.soup.find('input', {'name' : 'cmd', 'type' : 'hidden'})
to = self.soup.find('input', {'name' : 'to', 'type' : 'hidden'})
# Есть ли по кому бить?!
if cmd and to:
a = random.randint(1, 4)
b0 = random.randint(1, 4)
b1 = random.randint(1, 4)
while b1 == b0: b1 = random.randint(1, 4)
pos = 2
arg = (cmd['value'], to['value'], pos, a, a, b0, b0, b1, b1)
self.urlopen('battle.pl?cmd=%s&to=%s&pos=%s&A%s=%s&D%s=%s&D%s=%s' % arg)
else:
self.urlopen('battle.pl')
time.sleep(random.randint(5, 30))
### Найти заявку - подающий заявку должен быть на 1 уровень ниже нашего
def find(self):
me = self.inf(self.user)
while True:
v = ''
self.urlopen('zayavka.pl?cmd=haot.show')
reg = re.compile(unicode('Текущие заявки на бой', 'utf8'))
script = self.soup.find('fieldset', text = reg).findNext('script')
m = re.findall('.*', script.string)
for value in m:
if value.find('group.gif') < 0: continue
if value.find('(%i-%i)' % (me['level'] - 2, me['level'])) < 0: continue
t = re.search(',([0-9]{1,2}),u', value)
if not t: continue
t = int(t.group(1))
v = re.search('tr\(([0-9]+)', value).group(1)
print 'Found battle t=%i v=%s' % (t, v)
break
if v: break
time.sleep(80)
nd = self.soup.find('input', {'name' : 'nd', 'type' : 'hidden'})
self.urlopen('zayavka.pl?cmd=haot.accept&nd=%s&battle_id=%s' % (nd['value'], v))
time.sleep(t + 30)
if __name__ == '__main__': main()
The error is:
NameError: global name 'Carnage' is not defined
The cause of your error is that Carnage has not been defined. Maybe you forgot to import a library which provides Carnage?
Also, your code as posted is incorrectly indented, which is a syntax error.
Update: Apparently you took this code from http://github.com/Ejz/Common/tree/master/carnage-bot . Reading that source, it looks like the line
aCarnage = Carnage('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Should be
aCarnage = CarnageBot('YourNick', 'YourPass', 'arkaim.carnage.ru', 'cp1251', agent)
Because the methods called on aCarnage are defined further down the file for class CarnageBot.