Pyomo SolverFactory Couenne - TypeError (solver version) - typeerror

SolverFactory('couenne') .solve(M) fails to extract solver version information and throws TypeError
solver = pyo.SolverFactory('couenne')
solution = solver.solve(model)
THROWS ERROR:
File ~\AppData\Roaming\Python\Python39\site-packages\pyomo\opt\base\solvers.py:46, in _extract_version(x, length)
Attempts to extract solver version information from a string.
TypeError: expected string or bytes-like object
couenne.exe & libipoptfort.dll files downloaded from https://ampl.com/products/solvers/open-source/
and copied to \Anaconda3\Library\bin
*FYI - Same model is solved without problem via NEOS:
solver_manager = pyo.SolverManagerFactory('neos')
solution = solver_manager.solve(model, solver = 'couenne')

Related

Julia using package located in .julia/dev

I am beginner to Julia though I have experience with Python and some other languages. I get that this is probably a very simple/beginner issue, but I fail to understand how it should work in Julia.
I want to create a Julia module. I saw recommendations to create it with PkgTemplates, so that is exactly what I have done. My directory structure is thus:
It is located at the default path proposed by PkgTemplates: /home/username/.julia/dev/Keras2Flux.
I want to develop it with Revise package due to the slow start-up time of the Julia REPL. However, I fail to import my module to the Julia REPL in the terminal.
So, I cd to the directory mentioned above, use julia command and try using Keras2Flux. I get the error:
ERROR: ArgumentError: Package Keras2Flux not found in current path:
I tried both using Keras2Flux and using Keras2Flux.jl, and I also tried to call it from one level above in my directory structure (i.e. /home/username/.julia/dev). All has the same problem.
What is wrong (more importantly, why?) and how to fix it?
Current contents of the module (not really relevant to the question but still):
module Keras2Flux
import JSON
using Flux
export convert
function create_dense(config)
in = config["input_dim"]
out = config["output_dim"]
dense = Dense(in, outŠ¾)
return dense
end
function create_dropout(config)
p = config["p"]
dropout = Dropout(p)
return dropout
end
function create_model(model_config)
layers = []
for layer_config in model_config
if layer_config["class_name"] == "Dense"
layer = create_dense(layer_config["config"])
elseif layer_config["class_name"] == "Dropout"
layer = create_dropout(layer_config["config"])
else
println(layer_config["class_name"])
throw("unimplemented")
end
push!(layers, layer)
end
model = Chain(layers)
end
function convert(filename)
jsontxt = ""
open(filename, "r") do f
jsontxt = read(f, String)
end
model_params = JSON.parse(jsontxt)
if model_params["keras_version"] == "1.1.0"
create_model(model_params["config"])
else
throw("unimplemented")
end
end
end
Here is a full recipe to get you going:
cd("/home/username/.julia/dev")
using Pkg
pkg"generate Keras2Flux"
cd("Keras2Flux")
pkg"activate ."
pkg"add JSON Flux"
# now copy-paste whatever you need to Keras2Flux\src\Keras2Flux.jl
using Revise
using Keras2Flux
# happy development!

nuitka fails to generate executable due to "The filename or extension is too long"

I've been trying to compile/generate a standalone executable (.exe) with nuitka but it fails every time with the message:
Nuitka:INFO:Total memory usage before running scons: 2.72 GB (2920177664 bytes):
scons: *** [main_executable.dist\main_executable.exe] The filename or extension is too long
I'm new to this programming but I think I've tried just about everything. I moved my *.py files to directory C:\main to shorten the path to no avail. I've rename the file to produce "main.exe" from "main_executable" to no avail.
My python is installed in here:
'C:\users\test\Anaconda3...'
I came across this function below to shorten the path but I have no idea how to implement it: (taken from http://code.activestate.com/recipes/286179-getshortpathname/)
Could you kindly help. Thanks.
def getShortPathName(filepath):
"Converts the given path into 8.3 (DOS) form equivalent."
import win32api, os
if filepath[-1] == "\\":
filepath = filepath[:-1]
tokens = os.path.normpath(filepath).split("\\")
if len(tokens) == 1:
return filepath
ShortPath = tokens[0]
for token in tokens[1:]:
PartPath = "\\".join([ShortPath, token])
Found = win32api.FindFiles(PartPath)
if Found == []:
raise WindowsError, 'The system cannot find the path specified: "%s"' % (PartPath)
else:
if Found[0][9] == "":
ShortToken = token
else:
ShortToken = Found[0][9]
ShortPath = ShortPath + "\\" + ShortToken
return ShortPath

Getting an invalid token on an interpolated string sent from python/jinga2 backend

I'm sending a variable called apiID from a tornado/jinja2 python file to my vuejs template like this:
class SmartAPIUIHandler(BaseHandler):
def get(self, yourApiID):
doc_file = "smartapi-ui.html"
dashboard_template = templateEnv.get_template(doc_file)
dashboard_output = dashboard_template.render(apiID = yourApiID )
self.write(dashboard_output)
then in vuejs I'm interpolating the variable with no problem except it gives me an error
it says: Uncaught SyntaxError: Invalid or unexpected token
I checked on the python handler file and apipID is a string, so I don't see the problem. I'm quite new to python so maybe the answer is more obvious to one of you. I appreciate the help!!
Because of dashboard_output = dashboard_template.render(apiID = yourApiID ), you must have, in your template, something around the code:
this.apiID = {{ apiID }};
Due to the value being not a number but a string, add the 's:
this.apiID = '{{ apiID }}';

f.open() issue resulting in Unbound error for f.close()

I don't quite have an answer but I'm narrowing it down. Somehow I'm mixing/confusing types, I believe, between what is provided by commands like 'os.path' and type str().
As I've made the assignment of the logfile(s) globally, even though I can print it in the function, when the variable is used in fout = open(... it's actually a null that's being referenced, i.e. open() doesn't like/can't use the type it finds.
The error:
UnboundLocalError: local variable 'fout' referenced before assignment
I am simply writing a log of dot files (left on USB drives by OSX) for deletion, but the try/except is now falling over. First the original version.
working code:
logFile = "/Users/dee/Desktop/dotFile_names.txt"
try:
fout = open(logFile, 'w')
for line in dotFile_names:
fout.write(line)
except IOError as e:
print ("Error : %s not found." % fout)
finally:
fout.close()
Attempting better practice, I sought to put the log file specs and path as variables so they can be modified if need be - I hope to make it cross platform workable. these variables are at the head of the program, i.e. not in main(), but I pass them in and print() statements have shown me they are successfully being referenced. i.e. I get this printed:
/Users/dee/Desktop/dotFile_names.txt
Despite this the error I get is:
UnboundLocalError: local variable 'fout' referenced before assignment -
error points at the "fout.close()" line
Error producing code
logFilespec = "dotFile_names.txt"
fullLogFileSpec = []
userDesktop = os.path.join(os.path.expanduser('~'), 'Desktop')
fullLogFilespec = os.path.join(userDesktop, logFilespec)
try:
print "opening " + fullLogFilespec
fout = open(fullLogFileSpec, 'w')
for line in dotFile_names:
print "..", # are we executing this line..?
fout.write(line)
except IOError as e:
print ("Error : %s not found." % fout)
finally:
print "\nclosing " + fullLogFilespec
fout.close()
I've found that if I modify this line by converting to a string
fout = open(fullLogFileSpec, 'w')
fout = open(str(fullLogFileSpec), 'w')
the error goes away, BUT NO file is created on the Desktop!
At the very least I guess that I am passing something unrecognisable to fout = open() but it is not being caught by the except. Then when I pass something that does seem to allow fout =open() to work it seems to be a ghost?
So I figure I am lost between a String and whatever kind of reference/pointer os.path.expanduser() gives me.
I'm sure it's insanely simple. Before adding the str() code I also checked all indentation, removing them all and adding back using the editor indent hotkeys, just in case that was affecting things somehow.
OK, it looks like I was wearing my dumb glasses, I think declaring
fullLogFileSpec = []
as a list instead of a string was my error.
Similar as it is, having re-written it without that list declaration this code is working fine:
logfile_directory = os.path.join(os.path.expanduser('~'),'Desktop')
log_bf_file_spec = 'ItemsFoundByFolder_' + Deez_1.current_datetime() + '.txt'
log_by_folder = os.path.join(logfile_directory, log_bf_file_spec)
the function later calls, with no error:
fout_by_folder = open(log_by_folder, 'w')

Building Custom Query Filters Lists in Django

I'm building my filters as a list but having trouble building them with the Q function. It seems to be that doing things manually the filters work but when trying to build up the filters by concatenating strings I get the following issues:
Here is the Query:
MyLocationFilter = BuildQueryORFilter('MyLocationCountryCode', MyLocationCodePref1)
list = AboutMe.objects.order_by('MyLinkedInLastName').filter(reduce(OR, MyLocationFilter))
And here is how I am building those Filters:
def BuildQueryORFilter(fieldname, fieldvalues):
QueryList = []
spltfieldvalues = fieldvalues.split()
for item in spltfieldvalues:
strpitem = item.strip('[],')
queryitem = Q(fieldname+"__contains="+strpitem)
QueryList.append(queryitem)
return QueryList
However the problem seems to be how to get Q(..) in the form of Q(fieldname__contains=gb) rather than Q('fieldname__contains=gb') which seems to be throwing up issues such as:
ValueError
Exception Value:
need more than 1 value to unpack
How should I build the Q queries to avoid this unpacking issue?
Traceback for possible answer (below)
Traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/brett/LinkedIn/phaseone/jelt/views.py" in AboutMeList
259. list = AboutMe.objects.order_by('MyLinkedInLastName').filter(MyLocationFilter)
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py" in filter
624. return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py" in _filter_or_exclude
642. clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in add_q
1250. can_reuse=used_aliases, force_having=force_having)
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py" in add_filter
1056. arg, value = filter_expr
Exception Type: ValueError at /list/
Exception Value: need more than 1 value to unpack
Pass the keyword argument by unpacking a dict.
strpitem = item.strip('[],')
key = fieldname + "__contains"
d = {key: strpitem}
queryitem = Q(**d)