Python: how to solve ImportError - python

I have the following class in a file named SymbolManager.py:
from qgis.core import *
class SimbolManager:
def __init__(self):
self.initSymbols()
def initSymbols(self):
self.symbolMap = {}
props = {'color': '0,0,200'}
self.symbolMap['SimpleVertex'] = QgsMarkerSymbolV2.createSimple(props)
props = {'width': '1', 'color': '0,0,255'}
self.symbolMap['SimpleLine'] = QgsLineSymbolV2.createSimple(props)
def getSymbolRenderer(self, name):
symb = self.symbolMap[name]
if symb is not None:
return QgsSingleSymbolRendererV2(symb)
return None
From a file in the same dir I'm trying to import SymbolManager this way:
from PyQt4 import QtCore, QtGui
from Ui_OsmNavigator import Ui_OsmNavigator
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import DbConnection
from SymbolManager import SymbolManager // HERE IS THE PROBLEM
When I run the script, from inside QGIS it gives me the following error:
line 28, in
from SymbolManager import SymbolManager ImportError: cannot import name SymbolManager
What am I doing wrong?

Because your class isn't called SymbolManager?
class SimbolManager:
^^^^^^

Related

Combo box value list not updating

I made an application which includes a graphics file Part1.ui and a python file
Part1.ui includes 2 combo boxes which are named cmb_District and cmb_Tehsil
I Added a list in cmb_District and i want to make comparison in cmb_District.currentText()
If currentText() is Lahore then i want to add items in cmb_Tehsil but nothing happen.
import sys
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
import csv
import pandas as pd
def Import2dFile(filename):
array = []
with open(filename) as f:
mylist = list(f)
for line in mylist:
array.append(line)
return array
class Mainwindow(QMainWindow):
def __init__(self):
super(Mainwindow,self).__init__()
loadUi("Part1.ui",self)
#These 2 lines are used to put funnctions on close and minimize buttons.
#self.MinimizeButton.clicked.connect(lambda: self.showMinimized())
#self.CrossButton.clicked.connect(lambda: self.close())
districts = ["Attock","Bahawalnagar","Bahawalpur","Bhakkar","Chakwal","Chiniot","Dera Ghazi Khan","Faislabad","Gujranwala","Gujrat","Hafizabad","Jehlam","Jhang","Kasur","Khanewal","khusab","Lahore","Layyah","Lodhran","Mandi Bahauddin","Mian Wali","Multan","Muzaffarabad","NankanaSab","Narowal","Okara","Pakpattan","Raheem Yar Khan","Rajanpur","Rawalpindi","Sahiwal","Sarghoda","Sheikhupura","Sialkot","Toba Tek Singh","Vehari"]
print(len(districts))
tehsils = Import2dFile("Tehsils.txt")
print(tehsils)
self.cmb_District.addItems(districts)
if self.cmb_District.currentText() == "Lahore":
print("ls")
print(str(self.cmb_District.currentText()))
self.cmb_Tehsil.addItems(tehsils)
app = QApplication(sys.argv)
window = Mainwindow()
window.show()
sys.exit(app.exec_())
When I use !="Lahore" condition instead of =="Lahore" It works fine.I am new in PyQt please tell me what i did wrong

What should I do to import those modules correctly?

I want to run this code in jupyter notebook but it gives me that error :
ImportError: cannot import name 'document' from 'browser' (C:\Users\pc\anaconda3\lib\site-packages\browser_init_.py)
What should I do ?
from browser import document, window
def sketch(p):
def setup():
p.createCanvas(500, 500)
p.stroke(p.color("blue"))
p.line(10, 10, 100, 100)
def draw():
pass
p.setup = setup
p.draw = draw
myP5 = window.p5.new(sketch)

Python weird NameError

I have a NameError that I cannot seem to be able to find the reason for. The error trace ends like this.
Traceback (most recent call last):
File ".../new_main.py", line 61, in <module>
if __name__ == "__main__": main()
File ".../new_main.py", line 39, in main
mp = build()
File ".../common.py", line 54, in build
m = r.build_from_config(map_config, character_config)
File ".../config_reader.py", line 148, in build_from_config
item["squares"]
File ".../new_map.py", line 49, in build_map
self.view = MapView(self)
File ".../new_map.py", line 135, in __init__
self.screen = reset_screen()
NameError: name 'reset_screen' is not defined
The class MapView() is in the file new_map.py and that file has this line in the imports:
from common import *
And the file common.py has the following function in it.
def reset_screen():
# check if display has been initialized
if not pygame.display.get_init():
pygame.init()
# set screen
#flags = pygame.FULLSCREEN | pygame.DOUBLEBUF
screen = pygame.display.set_mode( options.window_size )
# fill with black
screen.fill(BLACK)
return screen
What am I missing?
E: here are my imports for each file.
new_main.py:
from common import *
from new_map import Map, MapView
import pygame, sys
common.py:
import pygame
import options
from config_reader import ConfigReader
from constants import *
from coordinates import Coordinates
config_reader.py:
from action import Action
from new_map import Map
from object_type import ObjectType
from squaretype import SquareType
from new_character import Character
from coordinates import Coordinates
import direction
new_map.py:
from square import Square
from common import *
from constants import *
from coordinates import Coordinates
from map_object import MapObject
from object_type import ObjectType
from new_character import Character
from turn import TurnController
import pygame, os
Looking at your trace i can also just figure that in your common.py your are including new_map.py which causes the import in new_map to fail. If i do that to my test files, i get the same error:
my main - which imports both but still won't cause circular reference:
if __name__ == "__main__":
from common import * # <-- this is ok
from new_map import * # <-- this is no problem
do_something()
test()
my commons:
from new_map import * # <--- this will cause the problem
def reset_screen():
return 1
def do_something():
return test()
my new_map:
from common import * # <--- this will fail then
def test():
return reset_screen()
So you will have to split you common.py to the parts using new_map and the other that don't, and in new_map then import the version that holds the functions without new_map inclusion.
common_map.py
from new_map import *
def do_something()
return test()
common_nomap.py
def reset_screen()
return 1
new_map.py:
from common_nomap import *
def test()
return reset_screen()
main.py
if __name__ == "__main__":
from common_map import * # <-- this is ok
from new_map import * # <-- this is no problem
do_something()
test()
2 possible scenarios I can think of:
Circular deps: it looks like common.py activates the function in new_map.py (via config_reader.py), which might cause new_map.py not to import common.py
Is there a common package you might be importing instead of common.py?

NameError: global name 'indicator' is not defined using Pyalgotrade in Python

I trying to write a Ultimate Oscillator in python using the list function in Pyalgotrade library.
My code is below:
from pyalgotrade.tools import yahoofinance
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import stoch
from pyalgotrade import dataseries
from pyalgotrade.technical import ma
from pyalgotrade import technical
from pyalgotrade.technical import highlow
from pyalgotrade import bar
from pyalgotrade import talibext
import numpy
import talib
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):
strategy.BacktestingStrategy.__init__(self, feed)
self.__instrument = instrument
barDs = self.getFeed().getDataSeries("002389.SZ")
self.__ultosc = indicator.ULTOSC(barDs, 36)
bar = bars[self.__instrument]
self.info("%0.2f, %0.2f" % (bar.getClose(), self.__ultosc[-1]))
# Downdload then Load the yahoo feed from the CSV file
yahoofinance.download_daily_bars('002389.SZ', 2013, '002389.csv')
feed = yahoofeed.Feed()
feed.addBarsFromCSV("002389.SZ", "002389.csv")
# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed, "002389.SZ")
myStrategy.run()
And I got the error like this:
File "/Users/johnhenry/Desktop/untitled.py", line 23, in onBars
self.__ultosc = indicator.ULTOSC(barDs, 36)
NameError: global name 'indicator' is not defined
The function can be found at http://gbeced.github.io/pyalgotrade/docs/v0.15/html/talib.html
Ultimate Oscillator:
pyalgotrade.talibext.indicator.ULTOSC(barDs, count, timeperiod1=-2147483648, timeperiod2=-2147483648, timeperiod3=-2147483648)
You're not importing indicator, nor are you referencing it via the module it's defined in. Change this:
self.__ultosc = indicator.ULTOSC(barDs, 36)
Into:
self.__ultosc = talibext.indicator.ULTOSC(barDs, 36)
And it should be fine.

Cocos2d: AttributeError: 'Director' object has no attribute '_window_virtual_width'

We are using the cocos2d framework to create a game. We're completely new to this framework, so we cannot get the director object to work as we are expecting. Here is our code skeleton:
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter():
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def main():
scene = TestScene()
director.init(world_width, world_height, do_not_scale=True)
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
So for some reason the director doesn't have all the attributes we want.
Our stack trace is:
Traceback (most recent call last):
File "map.py", line 49, in <module>
main()
File "map.py", line 39, in main
scene = TestScene()
File "map.py", line 29, in __init__
super(TestScene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/scene.py", line 95, in __init__
super(Scene,self).__init__()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/cocosnode.py", line 114, in __init__
self.camera = Camera()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 56, in __init__
self.restore()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/camera.py", line 76, in restore
width, height = director.get_window_size()
File "/usr/local/lib/python2.7/dist-packages/cocos2d-0.5.5-py2.7.egg/cocos/director.py", line 522, in get_window_size
return ( self._window_virtual_width, self._window_virtual_height)
AttributeError: 'Director' object has no attribute '_window_virtual_width'
You need to initialise the director before you instantiate your first scene. The director is the global object that initialises your screen, sets up the Cocos2D framework, etc.
I found a few other errors:
You need to change ColorLayer to be fully qualified, e.g. cocos.layer.ColorLayer.
on_enter needs to have self as the first argument.
You need to define f_refresh_marks in your TestScene class.
Here's a working copy of the code. (Working, in the sense that it does not throw errors, not that it does any sort of scrolling.)
from cocos.director import director
from cocos.layer import base_layers
import sys
import math
import os
import pyglet
import cocos
world_width = 1000
world_height = 1000
class NetworkMap(cocos.layer.ScrollableLayer):
def __init__(self, world_width, world_height):
self.world_width = world_width
self.world_height = world_height
super(NetworkMap, self).__init__()
bg = cocos.layer.ColorLayer(170,170,0,255,width=500,height=500)
self.px_width = world_width
self.px_height = world_height
self.add(bg,z=0)
class TestScene(cocos.scene.Scene):
def __init__(self):
super(TestScene,self).__init__()
def on_enter(self):
director.push_handlers(self.on_cocos_resize)
super(TestScene, self).on_enter()
def on_cocos_resize(self, usable_width, usable_height):
self.f_refresh_marks()
def f_refresh_marks(self):
pass
def main():
director.init(world_width, world_height, do_not_scale=True)
scene = TestScene()
world_map = NetworkMap(world_width, world_height)
scroller = cocos.layer.ScrollingManager()
scroller.add(world_map)
scene.add(scroller)
director.run(scene)
if __name__ == '__main__': main()
I had the same issue (with a very similar stack trace) and it was because I was trying to create a layer before calling director.init(). Moving director.init() to earlier in the code fixed it for me.

Categories