Python - Creating an instance of a module, getting an error - python

I am creating a universal text field that can be used in many python turtle projects. I am trying to create an instance of it but I get this error:
>>> import TextField
>>> tf = TextField('None', False)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
tf = TextField('None', False)
TypeError: 'module' object is not callable
>>>
What in a module causes this type of error? I completely wrote this module and I'm getting an error creating an instance of it :( ... What do I need in this module to make it 'callable'? I have tried adding a def __call__(self): but that doesn't affect the problem at all, nor create any errors.
Here is the beginning of the script where the problem is most likely happening:
# Created by SUPERMECHM500 # repl.it
# Edited by cdlane # stackoverflow.com
class TextField:
TextFieldBorderColor = '#0019fc'
TextFieldBGColor = '#000000'
TextFieldTextColor = '#ffffff'
ShiftedDigits = {
'1':'!',
'2':'#',
'3':'#',
'4':'$',
'5':'%',
'6':'^',
'7':'&',
'8':'*',
'9':'(',
'0':')'
}
def __init__(self, command, CanBeEmpty): # Ex. textField = TextField('Execute()', True)
self.CmdOnEnter = command
self.turtle = Turtle()
self.CanBeEmpty = CanBeEmpty
self.turtle.speed('fastest')
self.inp = []
self.FullOutput = ""
self.TextSeparation = 7
self.s = self.TextSeparation
self.key_shiftL = False
......

The module is not the class. If your class TextField is in a module called TextField, then it is referred to as TextField.TextField.
Or change your import to
from TextField import TextField

Related

instantiate object inside of class

Im trying to understand why I cannot access the methods on an object that is instantiated inside of a class. For example i'm attempting to build a script that utilizes the python-pptx library and I want to wrap the entire slide creation within a class to abstract it and make it a bit more reusable based on my configuration.
class Builder():
def __init__(self, template='template.pptx', output_file='out.pptx'):
self.cust_name = ''
self.author = ''
self.job_title = ''
self.present_date = ''
self.assessment_type = ''
self.template = template
self.agenda = ['Overview','Resources']
self.outfile = output_file
self.prs = Presentation('template.pptx') <--- This is what im referring to.
def addAgendaSlide(self):
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA]) <-- When trying to access this
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[10].text = 'A test Agenda slide'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
for para in self.agenda:
p = agenda_slide.placeholders[15].text_frame.add_paragraph()
p.text = para
Traceback (most recent call last):
File "test.py", line 19, in <module>
test.addAgendaSlide()
File "/dev/pythonpptx/DocMaker/Slides.py", line 89, in addAgendaSlide
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])
AttributeError: 'Presentation' object has no attribute 'add_slide'
If I use the same bits of code outside the class it works fine. I do have other methods in the class that are fine, it seems to be my implementation of the Presentation() bit that is messing me up.
The following works fine:
prs = Presentation('template.pptx')
agenda_slide = prs.slides.add_slide(prs.slide_layouts[AGENDA])
agenda_slide.shapes.title.text = 'Agenda'
agenda_slide.placeholders[15].top = STANDARD_TOP
agenda_slide.placeholders[15].left = STANDARD_LEFT
agenda_slide.placeholders[15].width = 8229600
agenda_slide.placeholders[15].height = 4572000
prs.save('out.pptx')
I think your problem is you are forgetting to add slides as follows:
agenda_slide = self.prs.slides.add_slide(self.prs.slide_layouts[AGENDA])
instead of
agenda_slide = self.prs.add_slide(self.prs.slide_layouts[AGENDA])

zipline run_pipeline and positional arguments

I'm using Zipline-1.1.1, Python3.4.6 to create a dynamic stock selector as follows:
from zipline.pipeline import Pipeline, engine
from zipline.pipeline.factors import AverageDollarVolume, Returns
def make_pipeline():
dollar_volume = AverageDollarVolume(window_length=1)
high_dollar_volume = dollar_volume.percentile_between(N, 100)
recent_returns = Returns(window_length=N, mask=high_dollar_volume)
low_returns = recent_returns.percentile_between(0, n)
high_returns = recent_returns.percentile_between(N, 100)
pipe_columns = {
'low_returns': low_returns,
'high_returns': high_returns,
'recent_returns': recent_returns,
'dollar_volume': dollar_volume
}
pipe_screen = (low_returns | high_returns)
pipe = Pipeline(columns=pipe_columns, screen=pipe_screen)
return pipe
I initialize a pipeline object with:
my_pipe = make_pipeline()
But when I try to populate the Pipeline, it fails with:
result = engine.PipelineEngine.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
Traceback (most recent call last):
File "<input>", line 1, in <module>
result = engine.PipelineEngine.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
TypeError: run_pipeline() missing 1 required positional argument: 'end_date'
I can't figure out what is wrong, any help is much appreciated.
If I understand correctly, you're using this library.
As far as I can see from that code, to be able to use run_pipeline method you have to instantiate on of pipeline engines before, e.g. SimplePipelineEngine. You need that because PipelineEngine is a class, even abstract class, not an object.
So you have to create an object of SimplePipelineEngine class and then call run_pipeline on it. You can do it this way:
your_engine = SimplePipelineEngine(get_loader=your_loader, calendar=your_calendar, asset_finder=your_asset_finder)
your_eninge.run_pipeline(my_pipe, '2017-07-10', '2017-07-11')
Of course you have to create your_loader etc. first.
Here is example of SimplePipelineEngine usage. I hope it will help.

AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'

I am trying to save map and its legends using QGis Map composer. I have already template .
Here is code in python.
layers =iface.legendInterface().layers()
canvas=iface.mapCanvas()
for layer in layers:
# myFile = r"C:\Users\craj\Downloads\GraduatedTheme.qpt"
myFile = r"C:\Users\craj\Downloads\GraduatedTheme.qpt"
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent, False)
newcomp = iface.createNewComposer()
newcomp.composition().loadFromTemplate(myDocument)
newcomp.composition().refreshItems()
for a in iface.mapCanvas().layers():
iface.legendInterface().setLayerVisible(a, False)
iface.legendInterface().setLayerVisible(layer, True)
newcomp.composition().refreshItems()
map_item = newcomp.composition()
map_item.getComposerItemById('map')
map_item.setMapCanvas(canvas)
map_item.zoomToExtent(canvas.extent())
newcomp.composition().refreshItems()
legend_item = newcomp.composition().getComposerItemById('legend')
legend_item.updateLegend()
newcomp.composition().refreshItems()
imagePath ='C:/Users/craj/Downloads/'+layer.name()+'.png'
image = newcomp.composition().printPageAsRaster(0)
image.save(imagePath,'png')
An error has occurred while executing Python code:
AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'
Traceback (most recent call last):
File "C:/Users/craj/.qgis2/python/plugins\JoinAttribute\Join_Attribute.py", line 436, in run
map_item.setMapCanvas(canvas)
AttributeError: 'QgsComposition' object has no attribute 'setMapCanvas'
If you look at the docs there is no setMapCanvas on QgsComposition. This method is in several other classes, such as QgsComposerMap. So based on the code calling getComposerItemById() what you likely need is this:
composition = newcomp.composition()
map_item = composition.getComposerItemById('map')
map_item.setMapCanvas(canvas)

Python Ecotect Geco Scripting "Unscriptable"

import rhinoscriptsyntax as rs
import scriptcontext
import Rhino
if ACTIVE:
for i in range(len(GEO)):
scriptcontext.doc = ghdoc
GEO_id = GEO[i]
doc_object = rs.coercerhinoobject(GEO_id)
attributes = doc_object.Attributes
geometry = doc_object.Geometry
scriptcontext.doc = Rhino.RhinoDoc.ActiveDoc
rhino_obj = scriptcontext.doc.Objects.Add(geometry, attributes)
rs.ObjectColor(rhino_obj, color[i])
mat_id = rs.AddMaterialToObject(rhino_obj)
rs.MaterialColor(mat_id, color[i])
"Runtime error (TypeErrorException): 'Color' object is unsubscriptable
Traceback:
line 23, in script"
I have no idea why the "ObjectColor" is unscriptable, I have matched it with the python API so many times. AM I not seeing something that I should?

Variable not the same type in two different functions

I have two functions which print into an excel file. THe only input is the file name. Here is the code:
#excelpy
import excelpy
#Tinker
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *
Function Mode1
def Mode1(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST1', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m1 = testwbook.save(full_name)
testwbook.close()
return m1
Function Mode2
def Mode2(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST2', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m2 = testwbook.save(full_name)
testwbook.close()
return m2
Main
root = Tk()
d = str(asksaveasfilename(parent=root,filetypes=[('Excel','*.xls')],title="Save report as..."))
d = d + '.xls'
d = d.replace('/','\\')
root.destroy()
Mode1(d)
Mode2(d)
And once in a while I get the following error:
Traceback (most recent call last):
File "T:\TEST\testpy.py", line 2035, in <module>
Mode2(d)
File ""T:\TEST\testpy.py"", line 1381, in Mode2
print type(full_name)
TypeError: 'str' object is not callable
Any idea why is this happening? How can I prevent it?
The only function call in the line you get the error is a call to the built-in function type(), so the only explanation for your error message is that you overwrote the built-in name type by a global name type pointing to a string object. Try adding
print type
before
print type(full_name)
It looks like somewhere you're setting a (global) variable named type to a string, thus overwriting the built-in type function.
Try searching your code for type = to see what turns up.
Understandably, Python would then throw that exception when you tried to call type (strings can't be "called").

Categories

Resources