I have two functions, updates_list updates values to the list altered_source_tables while the other picks the values in that list. The issue is, even though the first function updates the list, the second function use_list still has the list as empty.
altered_source_tables = []
table_name = 'table_1'
def updates_list(table_name, **kwargs):
# CODE
for e in job.errors:
fullstring = e['message']
substring = "No such field"
if search(substring, fullstring):
altered_source_tables.append(table_name)
print("altered_source_tables list ", altered_source_tables) # output from fn call: altered_source_tables = ['table_1']
else:
print('ERROR: {}'.format(e['message']))
def use_list(**kwargs):
print("altered_source_tables list ", altered_source_tables) # output from fn call: altered_source_tables = []
if len(altered_source_tables) > 0:
# Loop through all altered tables
for table_name in altered_source_tables:
# CODE
What I'm I missing?
Related
I have a main function, and helper functions inside the main function that will retrieve values from an excel spreadsheet
Ex.
import openpyxl
def main():
dict = {}
dname = 'Animal list'
animal = {}
while opt in ['0', '1']:
if opt == '0':
print('goodbye')
if opt == '1':
file_open(dname, dict, animal)
return
def file_open(dname, dict, animal):
open_excel(dname)
create_animal_dict(data, dict)
def open_excel(default_name):
filename = dname
try:
workbook = openpyxl.load_workbook(filename)
except:
print("No file")
return
sheet = workbook.active
columns = sheet.max_column
rows= str(sheet.max_row)
max_column_letter = chr(ord("A")+ number_of_columns -1 )
raw= sheet['A1': max_column_letter+number_of_rows]
data= []
for row in raw:
sublist = []
for cell in raw:
sublist.append(cell.value)
data.append(sublist)
return(data) #creates a list of list
The error i get is "builtins.NameError: name 'data' is not defined"
Im having trouble, taking 'data' from open_file(dname) and having it being a parameter for create_animal_dict, I was wondering how to to bring a variable from one helper function to another.
Thanks for any help or tips!
You are not receiving the output from your open_excel function, which then I assume needs to be passed to the create_animal_dict function, e.g.
def file_open(dname, dict, animal):
data = open_excel(dname)
create_animal_dict(mainlist, dict, data)
I assume the error is coming from you calling data from inside create_animal_dict, which this would solve.
But you should also take the output from create_animal_dict and pass it back to main function if you are structuring your program this way.
im trying to use pyviz in a jupyter notebook to create some sort of form for others to populate with data.
this data then is to be saved to a nested list on the click of the save button. then you repeat it for every person.
then i need a button to show the current input of the nested list.
can someone point me in the right direction?so far ive got only the input fields, the list is always empty.
# companies at which people are working
company = ['wal', 'even', 'foot']
class Company(param.Parameterized):
# dropdown of company
company = param.ObjectSelector(objects=company)
# name of person
personname = param.String(doc="name")
# age of person
age = param.Number(0)
# save to list button
save_btn = param.Action(lambda self:self.param.trigger('save_btn'),doc="""Save""")
# show list
show_btn = param.Action(lambda self: self.param.trigger('show_btn'),doc="""Show dicitonary""")
# dict which collects all input
all_persons = []
# return content of dict
#param.depends('show_btn')
def show_list(self):
return self.all_persons
# save form content to dict
#param.depends('save_btn')
def save_to_list(self):
temp_list = []
temp_list.append[self.company]
temp_list.append[self.personname]
temp_list.append[self.age]
run = Company()
pn.Column(run.param.company, run.param.personname, run.param.age,run.param.save_btn,run.param.show_btn, run.show_list)
# desired nested list
# [['wal', "bob", "34"], ["foot", "anna", "56"]]
Your code contains a few typos and loose ends. From top to bottom:
all_persons is defined as empty list, but never connected to the temp list created in the method save_to_list()
#param.depends(...) is missing watch=True, e.g. #param.depends('show_btn', watch=True)
show_list() returns self.all_persons, but this variable is never used anywhere
E.g.:
company = ['A', 'B'] # simplified code
class Company(param.Parameterized):
company = param.ObjectSelector(default=company[0], objects=company)
person_name = param.String(doc="name")
age = param.Number(0)
save_btn = param.Action(lambda self: self.save_to_list() , doc="""Save""") # no need for param.trigger here...
print_btn = param.Action(lambda self: self.print_list() , doc="""Print""") # no need for param.trigger here...
all_persons = [] # starts with an empty list
# no need for param.depends, as the method directly is called via param.Action,
def save_to_list(self):
print('safe to list: {}, {}, {}'.format(self.company, self.person_name, self.age))
temp_list = []
temp_list.append(self.company) # use () for append, not []
temp_list.append(self.person_name)
temp_list.append(self.age)
print('temp_list: {}'.format(temp_list))
self.all_persons.append(temp_list)
# no need for param.depends, as the method is directly called via param.Action,
def print_list(self):
print('all_persons: {}'.format(self.all_persons))
run = Company()
layout = pn.Row(run.param)
layout.app() # to see print statements in a notebook, use the server variant via 'app()'
Hi for a given function I have 2 parameters which are string and an Int but I don't know which comes first. So I have a function "pick_type()" that tries to guess the order of the parameters. So my question is when "pick_type()" incorrectly guesses the order, how do I record this and make sure "pick_type()" never tries that specific order again ?
for iteration in range(0, 10):
args = []
print("\n def test%d(self):" % (iteration))
for input in range(num_arguments):
args += pick_type()
try:
result = target(*args)
code = test_to_string(target, args, result)
except TypeError as error:
code = test_to_string_exc(target, args, error)
for line in code.splitlines():
print(" "+line)
def pick_type():
lista = []
words = ['rhythms', 'rhythms', 'manager', 'training', 'hotel', 'destroy']
word = choice(words)
num = random.randint(-100, 100)
lists = [word,num]
choices = choice(lists)
if choices == word:
lista.append(word)
else:
lista.append(num)
return lista
I would suggest wrapping your method in a class, then you can have a persistent list of bad orders. It's not clear to me what you mean by an "order", but whatever it is, hopefully this pseudo-code helps:
class PickType:
def __init__(self):
self._bad_orders = []
def pick_type(self):
...# insert body here
if order in self._bad_orders:
## pick another order
## test the new order
if <order is bad>:
self._bad_orders.append(order)
## if your test for bad orders is performed outside pick_type(), you just need a method to add to the list of bad_orders
def add_bad_order(self, order):
self._bad_orders.append(order)
This question has been asked before at:
https://stackoverflow.com/questions/26538667/pyqt-populate-qtreeview-from-txt-file-that-contains-file-paths
But didn't seem to get a response.
I have a dataset of file paths that are formatted, like so:
hon_dev/Bob Dylan/Concept
hon_dev/Andromeda/Modeling
hon_dev/Andromeda/Lookdev
hon_dev/Andromeda/Rigging
hon_dev/Andromeda/Animation
hon_dev/Andromeda/FX
hon_dev/fsafasfas/production
hon_dev/Magebane: Acheron of Mana Aeacus/Model
hon_dev/Magebane: Acheron of Mana Aeacus/Concept
hon_dev/Magebane: Acheron of Mana Aeacus/Texture
hon_dev/Skrull/Modeling
hon_dev/Skrull/Lookdev
hon_dev/Skrull/Rigging
hon_dev/Skrull/Animation
hon_dev/Skrull/FX
hon_dev/Bob Mylan/Modeling
hon_dev/Bob Mylan/Lookdev
hon_dev/Bob Mylan/Rigging
hon_dev/Bob Mylan/Animation
hon_dev/Bob Mylan/FX
hon_dev/Handsome Man/Concept
hon_dev/Handsome Man/Modeling
hon_dev/Handsome Man/Lookdev
hon_dev/Handsome Man/Rigging
hon_dev/Handsome Man/Animation
hon_dev/Handsome Man/FX
demo-sync/Drone Craft/Modelling Drone Craft
demo-sync/Drone Craft/Texturing and Shading of Drone Craft
demo-sync/Drone Craft/Rigging Drone Parts
And I'm trying to get them to fill up a QTreeView (PySide). The current code I have is as such, with a simple recursive function:
def doIt(self):
self.model = QtGui.QStandardItemModel()
# self.model.setHorizontalHeaderLabels = ['test']
topLevelParentItem = self.model.invisibleRootItem()
# create all itewms first
# iterate over each string url
for item in data:
splitName = item.split('/')
# first part of string is defo parent item
# check to make sure not to add duplicate
if len(self.model.findItems(splitName[0], flags=QtCore.Qt.MatchFixedString)) == 0:
parItem = QtGui.QStandardItem(splitName[0])
topLevelParentItem.appendRow(parItem)
def addItems(parent, elements):
# check if not reached last item in the list of items to add
if len(elements) != 0:
print "currently eval addItems({0}, {1}".format(parent.text(), elements)
# check if item already exists, if so do not create
# new item and use existing item as parent
if len(self.model.findItems(elements[0], flags=QtCore.Qt.MatchFixedString)) == 0:
print "item being created for {0}".format(elements[0])
item = QtGui.QStandardItem(elements[0])
else:
print "not adding duplicate of: {0}".format(elements[0])
item = self.model.findItems(elements[0], flags=QtCore.Qt.MatchFixedString)[0]
print "the item to act as non-duplicate is: {0}".format(item.text())
child = elements[1:]
print "child is {0}".format(child)
# call recursive function to add
addItems(item, child)
print "parenting: {0} to {1}".format(item.text(), parent.text())
parent.appendRow(item)
addItems(parItem, splitName[1:])
print 'done: ' + item + '\n'
self.inst.col_taskList.setModel(self.model)
However, because I can't find any way to look through a QStandardItem for existing rows, I'm getting this in the UI as a result:
Is there a way to find duplicates rows in a QStandardItem or traverse the QStandardItemModel to find the existing QStandardItem? I've been struggling with this problem for the past 2 days and trying to find an existing example, and I can't really wrap my head around how this could be such a complication...
Any help/advice on this would be appreciated! Thanks!
Hmm, after a bit of faffing about, I've come up with something that works for now, though the file paths must be in order for this to work:
def doIt(self):
print "\n\n\n\n"
self.model = QtGui.QStandardItemModel()
topLevelParentItem = self.model.invisibleRootItem()
# iterate over each string url
for item in data:
splitName = item.split('/')
# first part of string is defo parent item
# check to make sure not to add duplicate
if len(self.model.findItems(splitName[0], flags=QtCore.Qt.MatchFixedString)) == 0:
parItem = QtGui.QStandardItem(splitName[0])
topLevelParentItem.appendRow(parItem)
def addItems(parent, elements):
"""
This method recursively adds items to a QStandardItemModel from a list of paths.
:param parent:
:param elements:
:return:
"""
for element in elements:
# first check if this element already exists in the hierarchy
noOfChildren = parent.rowCount()
# if there are child objects under specified parent
if noOfChildren != 0:
# create dict to store all child objects under parent for testing against
childObjsList = {}
# iterate over indexes and get names of all child objects
for c in range(noOfChildren):
childObj = parent.child(c)
childObjsList[childObj.text()] = childObj
if element in childObjsList.keys():
# only run recursive function if there are still elements to work on
if elements[1:]:
addItems(childObjsList[element], elements[1:])
return
else:
# item does not exist yet, create it and parent
newObj = QtGui.QStandardItem(element)
parent.appendRow(newObj)
# only run recursive function if there are still elements to work on
if elements[1:]:
addItems(newObj, elements[1:])
return
else:
# if there are no existing child objects, it's safe to create the item and parent it
newObj = QtGui.QStandardItem(element)
parent.appendRow(newObj)
# only run recursive function if there are still elements to work on
if elements[1:]:
# now run the recursive function again with the latest object as the parent and
# the rest of the elements as children
addItems(newObj, elements[1:])
return
# call proc to add remaining items after toplevel item to the hierarchy
print "### calling addItems({0}, {1})".format(parItem.text(), splitName[1:])
addItems(parItem, splitName[1:])
print 'done: ' + item + '\n'
self.inst.col_taskList.setModel(self.model)
I have a program where I have defined a function called historyA()
def historyA(self, name, price, category, sub, comment):
sh = login("Budget")
worksheet = sh.get_worksheet(0)
emptyrowresize()
date = getDate()
toAppend = [date, name, category, sub, price, comment]
worksheet.append_row(toAppend)
In this function it is giving the variable worksheet values.
Immediately after that it runs the function emptyrowresize()
def emptyrowresize():
print("\n")
count = 0
cycle = 0
empty = False
for i in range(emptyrowcount()):
for i in range(worksheet.col_count):
if(lastvalue(i+1) == ""):
count += 1
if(count >= worksheet.col_count):
empty = True
if(empty == True):
worksheet.resize(worksheet.row_count-1,worksheet.col_count)
print("Fixing empty row at {0}..." .format(worksheet.row_count+1))
break
emptyrowresize() calls the functions lastvalue() in it
def lastvalue(x, y=0):
cycles = 0
#returns last value in col x with vertical offset y
while(True):
count = worksheet.row_count
val = worksheet.cell(int(count-y), x).value
cycles += 1
if(val == ''):
y = cycles
else:
break
return val
and last value needs the worksheet that was named in historyA() but it keeps giving the error that worksheet is not a defined global variable.
Why is this not working? I have had a problem with this once before but I don't remember how I fixed it without making a separate function for each of the three worksheets I need to work with.
EDIT: I feel like it is worth mentioning that everything passed historyA() is in a separate file that I am importing. I'm not sure if that means anything.