unhelpful Pyomo error ERROR: Initializer for Set objective_index returned non-iterable object of type SumExpression - pyomo

Here is the offending code, abstracted from the source to protect your sanity . . .
def objective_rule(model):
return sum(model.ccv[c] * model.SELECT[c] for c in model.c)
nc=40
model.c = Set(initialize=[c for c in range(1, nc+1)], ordered=True)
model.SELECT=Var(model.c, initialize=0, domain=NonNegativeReals)
model.ccv= Param(model.c, initialize=ccd, domain=NonNegativeReals)
ccd is a dictionary with the same integer keys as as model.c.
Here are the error allegations made by pyomo.
ERROR: Initializer for Set objective_index returned non-iterable object of
type SumExpression.
ERROR: Constructing component 'objective_index' from data=None failed:
TypeError: 'SumExpression' object is not iterable
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [44], line 1
----> 1 model.objective = Objective(objective_rule, sense = minimize)
3 print("Done setting up the problem.")
...
TypeError: 'SumExpression' object is not iterable
You'll notice that I don't use SumExpression in my code, so an error message that SumExpression is not iterable is not actionable.
The objection function follows the form of many, many other pyomo objective functions that do work fine.
The problem I'm working on is easy to solve in cvxpy, but I'm tasked with getting pyomo to be useful. So far, not so good.
Is there a (nonobvious) error here? Do the error messages contain actionable information? Do I have a broken pyomo installation?

The error is in the construction of your Objective().
pyomo is making the (false) assumption that the first parameter in the function call is an iterable. Most pyomo commands like making variables or constraints with a "rule" assume the first thing(s) in the call are the indexing set(s).
You should identify it by a keyword. Or just put the expression in the function. Either of these should work. (Note the use of 'rule' in the first and 'expr' in the second)
model.objective = Objective(rule=objective_rule) #minimize is default and not needed
or you can ditch the function as it is just a simple expression and put:
model.objective = Objective(expr=sum(model.ccv[c] * model.SELECT[c] for c in model.c))

Related

How to use Django's APIRequestFactory with an array of objects?

I have the following test
def test_bulk_post(my_faker,factory):
snippets = [{'code':'print(True)'},{'code':'print(True)'},{'code':'print(True)'}]
assert factory.post('/snippets/',snippets) == True
I am trying to extend the snippets app in the tutorial to accept multiple code objects in a single post request.
Right now this gives me:
/venv/lib/python3.8/site-packages/django/test/client.py(244)encode_multipart()
*** AttributeError: 'list' object has no attribute 'items'
so its not expecting a list.. But I want to give it one. How do I do that?
factory.post by default expects a key, value pairs that goes with multipart/form-data and not list hence error
You should probably set content_type='application/json' to pass data as JSON body
factory.post('/snippets/',snippets, content_type='application/json )

Getting "AttributeError: 'str' object has no attribute 'regex'" in Django urls.reverse

As in the title, I'm getting
AttributeError: 'str' object has no attribute 'regex'
I've seen many valid answers to this, but none of them applied to my code as they identified issues in the urls.py file. My issue is in the views.py file.
I get the exception when using reverse to generate a redirect URL:
HttpResponseRedirect(reverse('changetracker:detail', args))
When I use 'changetracker:detail' in other functions, I don't get the exception.
I'm answering this to share knowledge as I didn't see this particular root cause identified already.
The problem turned out to be that I should be using a keyword argument 'args=args' to pass in URL arguments, not a positional argument:
HttpResponseRedirect(reverse('changetracker:detail', args=args))
Using the positional argument (position 2) caused reverse to use that argument as the URL list and thus raise the AttributeError.

django-selenium TypeError: 'str' object is not callable

Doing a simple test of a clicking dropdown and seeing if the menu is displayed.
dropdown_user = self.browser.find_element_by_id('dropdown-user')
dropdown_user.click()
expanded = dropdown_user.get_attribute("aria-expanded")
self.assertTrue= (expanded)
settings = self.browser.find_element_by_id('dropdown-user-settings')
self.assertTrue(settings.is_displayed())
Gives me this error when I run the test. I cant figure why settings is a str.
self.assertTrue(settings.is_displayed())
TypeError: 'str' object is not callable
I can't comment (not enough rep) or I would - could you post the whole stack trace? The line self.assertTrue= (expanded) looks like it could feasibly cause an issue.
Edit: I think you're assigning the value of the variable expanded to self.assertTrue, then when you try to call self.assertTrue you're trying to call a string, rather than a function. Remove the line self.assertTrue=(expanded) and replace it with self.assertEqual(expanded, 'true').
Edit 2 to explain in more depth as requested:
The value of expanded is a string - probably 'true', if your dropdown is expanded.
Writing self.assertTrue=(expanded) is the same (in this case) as writing self.assertTrue=expanded. You're assigning the value of the variable expanded (which is a string) to the variable self.assertEqual - it is no longer a function, it's a string!
self.assertTrue(True) # fine
self.assertTrue=('Woops!') # the value of self.assertTrue is now the
# string 'Whoops!'
print(self.assertTrue)
>'Woops!'
self.assertTrue(True) # you're trying to call a string here
> TypeError: 'str' object is not callable
In python, there's nothing to stop you from assigning any type to any variable, because it's dynamically typed.

How to check if the dictionary is empty or not in robot framework using python

I tried to check the given dictionary is empty or not in robot framework but it is giving an error saying syntax error. Here is the following example of how I compared it:
Run Keyword If '${source_list_data}'=='[]' FAIL and the error which i got is:
Evaluating expression ''[{'data':'value'}]'=='[]'' failed: SyntaxError: invalid syntax (, line 1)
Your syntax works for me. Strange it does not work for you.
Here is another way to achieve it using Get Length:
*** Settings ***
Library Collections
*** Test Cases ***
dict_empty
${source_list_data} = create dictionary
${length} = Get Length ${source_list_data}
Run Keyword If ${length} == 0 log to console Empty Dict
To check if dictionary is empty in robot framework, automatic dictionary variable "&{EMPTY}" can be used:
Run Keyword if ${dict} == &{EMPTY} 'Some Action Keyword'

Django KeyError when getting an object with a keyword for a field name

I wish to get an object in the following fashion:
Collection.objects.get(name='name', type='library', owner=owner, parent=parent)
Unfortunately type is a keyword as thus creates the following error:
KeyError at /forms/create_library
type
Is there a way to disambiguate the meaning of the word type to allow me to specify a field of that name?
Not tested:
Collection.objects.filter(
name__exact='name',
type__exact='library',
owner__exact=owner,
parent__exact=parent)
Query docs: http://docs.djangoproject.com/en/dev/topics/db/queries/
Also consider naming your field differently, mainly not with the same name as a builtin.
OK it turns out the problem was elsewhere. I was doing this in a form and thus using the self.cleaned_data dictionary of input values.
I was attempting to retrieve self.cleaned_data['type'] where in my previous simplification I stated the string 'library'. This was not in fact in the cleaned data of the form and thus threw a KeyError.