I'm able to get the value using ptr.dereference, however I have no idea how to increment the pointer to get the next value. Assume I'm using a 16bit signed array. How do I get the first 5 values?
class MyArrayPrinter:
"Print a MyArray"
def __init__ (self, val):
self.val = val
def to_string (self):
return "Array of"
def children(self):
ptr = self.val['array']
#yield ('0', ptr.address[1].dereference())
yield ('5', 47)
def display_hint (self):
return 'array'
For this simple array class, taken from your other question:
template<class T>
struct MyArray
{
int pos;
T array[10];
MyArray() : pos(0) {}
void push(T val) {
if (pos >= 10)
return;
array[pos++] = val;
}
};
I would implement the pretty printer like this:
class MyArrayPrinter:
"Print a MyArray"
class _iterator:
def __init__ (self, start, finish):
self.item = start
self.finish = finish
self.count = 0
def __iter__ (self):
return self
def __next__ (self):
count = self.count
self.count = self.count + 1
if self.item == self.finish:
raise StopIteration
elt = self.item.dereference()
self.item = self.item + 1
return ('[%d]' % count, elt)
def next (self):
return self.__next__()
def __init__ (self, val):
self.val = val
def children (self):
start = self.val['array'][0].address
return self._iterator(start, start + self.val['pos'])
def to_string (self):
len = self.val['pos']
return '%s of length %d' % (self.val.type, len)
def display_hint (self):
return 'array'
pp = gdb.printing.RegexpCollectionPrettyPrinter("mine")
pp.add_printer('MyArray', '^MyArray<.*>$', MyArrayPrinter)
gdb.printing.register_pretty_printer(gdb.current_objfile(), pp)
Which would look like this:
(gdb) p arr
$1 = MyArray<MyString> of length 2 = {"My test string", "has two"}
(gdb) p arr2
$2 = MyArray<MoreComplex*> of length 1 = {0x22fe00}
Related
If I wrote:
#ray.remote(num_cpus=9)
class Counter(object):
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
return self.value
def get_counter(self):
return self.value
ray.init(address='ray://host:port', runtime_env=runtime_env)
counter_actor = Counter.remote()
It works fine. num_cpus works. But if I wrote in this way without annotation:
class Counter(object):
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
return self.value
def get_counter(self):
return self.value
ray.init(address='ray://host:port', runtime_env=runtime_env)
'''
first method is wrong
'''
ray_factor = ray.remote(self.cls, num_cpus=9)
'''
second method is also wrong
'''
ray_factor = ray.remote(self.cls)
ray_factor.options(num_cpus=9)
counter_actor = Counter.remote()
how can i make num_cpus work without annotation.
My ray version is 1.10.0
I'm trying to add a window to Qmdi area when user clicks a button inside another widget in Qmdi area.
Codes i have written so far is:
from __future__ import print_function
from PyQt4.QtGui import *
import csv
import subprocess
import sys
from PyQt4 import QtGui
from PyQt4.QtCore import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.lee = QLineEdit()
self.lee.setObjectName("hosta")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("inject")
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.lee)
layout.addWidget(self.pb)
self.setLayout(layout)
self.connect(self.pb, SIGNAL("clicked()"), self.button_click)
self.setWindowTitle("Stuck-at-0")
def button_click(self):
# shost is a QString object
n = int(self.le.text())
line = str(self.lee.text())
print(n, line)
with open('main.txt', 'r') as files:
# read a list of lines into data
data = files.readlines()
# now inject fault in nth level, note that you have to add a newline
print
data[1]
if line in data[0]:
data.insert(n + 1, '0' + ',' + line + '\n')
# and write everything back
with open('main.txt', 'w') as files:
files.writelines(data)
res = subprocess.call(['python stuck.py'], shell=True)
res = subprocess.call(['python comp.py'], shell=True)
class UserWindow(QtGui.QMainWindow):
def __init__(self):
super(UserWindow, self).__init__()
self.ctr_frame = QtGui.QWidget()
self.specTable = QtGui.QTableView()
self.specModel = QtGui.QStandardItemModel(self)
self.specList = self.createSpecTable()
self.initUI()
def specData(self):
with open('tests.csv', 'rb') as csvInput:
for row in csv.reader(csvInput):
if row > 0:
items = [QtGui.QStandardItem(field) for field in row]
self.specModel.appendRow(items)
def createSpecTable(self):
# This is a test header - different from what is needed
specHdr = ['Test', 'Date', 'Time', 'Type']
self.specData()
specM = specTableModel(self.specModel, specHdr, self)
self.specTable.setModel(specM)
self.specTable.setShowGrid(False)
v_head = self.specTable.verticalHeader()
v_head.setVisible(False)
h_head = self.specTable.horizontalHeader()
h_head.setStretchLastSection(True)
self.specTable.sortByColumn(3, Qt.DescendingOrder)
return self.specTable
def initUI(self):
self.specList.setModel(self.specModel)
p_grid = QtGui.QGridLayout()
p_grid.setSpacing(5)
p_grid.addWidget(self.specList, 2, 5, 13, 50)
self.ctr_frame.setLayout(p_grid)
self.setCentralWidget(self.ctr_frame)
self.statusBar()
bar = self.menuBar()
menu_item1 = bar.addMenu("Circuit Details")
fault_inject = bar.addMenu("Fault Injection")
fault_inject_sa = fault_inject.addMenu("Stuck-at Fault")
fault_inject_sa.addAction("Stuck-at-0")
fault_inject_sa.addAction("Stuck-at-1")
fault_inject_bridge = fault_inject.addMenu("Bridging Fault")
fault_inject_bridge.addAction("Bridging-OR")
fault_inject_bridge.addAction("Bridging-AND")
fault_inject_cross = fault_inject.addMenu("Crosspoint Fault")
fault_inject_cross.addAction("Crosspoint-Appearance")
fault_inject_cross.addAction("Crosspoint-Dissappearence")
fault_inject_mgf = fault_inject.addMenu("Missing Gate Fault")
fault_inject_mgf.addAction("Single-MGF")
fault_inject_mgf.addAction("Multiple-MGF")
fault_inject_mgf.addAction("Repeated-MGF")
fault_inject_mgf.addAction("Partial-MGF")
self.setWindowTitle('Truth Table')
fault_inject.triggered[QAction].connect(self.fault_injection)
def fault_injection(self, q):
print("triggered")
if q.text() == "Stuck-at-0":
print(q.text())
exx = Form()
self.mdi.addSubWindow(exx)
exx.show()
if q.text() == "Stuck-at-1":
print(q.text())
if q.text() == "Bridging-OR":
print(q.text())
if q.text() == "Bridging-AND":
print(q.text())
if q.text() == "Crosspoint-Appearance":
print(q.text())
if q.text() == "Crosspoint-Dissappearence":
print(q.text())
if q.text() == "Single-MGF":
print(q.text())
if q.text() == "Multiple-MGF":
print(q.text())
if q.text() == "Repeated-MGF":
print(q.text())
if q.text() == "Partial-MGF":
print(q.text())
class specTableModel(QAbstractTableModel):
def __init__(self, datain, headerData, parent=None, *args):
QAbstractTableModel.__init__(self, parent, *args)
self.arrayData = datain
self.headerData = headerData
def rowCount(self, parent):
return 0
def columnCount(self, parent):
return 0
def data(self, index, role):
if not index.isValid():
return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.arraydata[index.row()][index.column()])
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.headerdata[col]
return None
class MainWindow(QMainWindow):
count = 0
filename = 0
def test_display(self,q):
self.mdi.tileSubWindows()
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
menu_item1 = bar.addMenu("About Tool")
menu_item_tool = menu_item1.addMenu("User Manual")
menu_item_example = menu_item1.addMenu("Example and Demos")
menu_item2 = bar.addMenu("Reversible Computing")
menu_item_rc = menu_item2.addMenu("RC vs Conventional")
menu_item_rcg = menu_item2.addMenu("RC Gates")
menu_item_rcp = menu_item2.addMenu("Properties of RC")
menu_item_rcl = menu_item2.addMenu("RC Gate Libraries")
menu_item = bar.addMenu("Benchmark Circuits")
menu_item_gate = menu_item.addMenu("Functions")
menu_item_realize = menu_item.addMenu("Realization Library")
menu_item_nct = menu_item_realize.addMenu("NCT")
menu_item_gt = menu_item_realize.addMenu("GT")
menu_item_nctf = menu_item_realize.addMenu("NCTF")
menu_item_gf = menu_item_realize.addMenu("GF")
menu_item_4b1_5g = menu_item_gate.addMenu("4b1_5g")
menu_item_4b1_5g.addAction("4b1_5g_1")
menu_item_4b1_5g.addAction("4b1_5g_2")
menu_item_4b1_5g.addAction("4b1_5g_3")
menu_item_4b1_5g.addAction("4b1_5g_4")
menu_item_4b1_5g.addAction("4b1_5g_5")
menu_item_adder = menu_item_gate.addMenu("Adders")
menu_item_adder.addAction("1bitadder(rd32)")
menu_item_adder.addAction("5bitadder")
menu_item_adder.addAction("8bitadder")
menu_item_div_checker = menu_item_gate.addMenu("Divisiblity Checkers")
menu_item_div_checker.addAction("4mod5")
menu_item_div_checker.addAction("5mod5")
menu_item_cyclic = menu_item_gate.addMenu("Cycle Functions")
menu_item_cyclic.addAction("cycle10_2")
menu_item_cyclic.addAction("cycle17_3")
menu_item_galois = menu_item_gate.addMenu("Galois Field Multipliers")
menu_item_galois.addAction("gf2^3mult")
menu_item_galois.addAction("gf2^4mult")
menu_item_galois.addAction("gf2^5mult")
menu_item_galois.addAction("gf2^6mult")
menu_item_galois.addAction("gf2^7mult")
menu_item_galois.addAction("gf2^8mult")
menu_item_galois.addAction("gf2^9mult")
menu_item_galois.addAction("gf2^10mult")
menu_item_galois.addAction("gf2^11mult")
menu_item_galois.addAction("gf2^12mult")
menu_item_galois.addAction("gf2^13mult")
menu_item_galois.addAction("gf2^14mult")
menu_item_galois.addAction("gf2^15mult")
menu_item_galois.addAction("gf2^16mult")
menu_item_galois.addAction("gf2^17mult")
menu_item_galois.addAction("gf2^18mult")
menu_item_galois.addAction("gf2^19mult")
menu_item_galois.addAction("gf2^20mult")
menu_item_galois.addAction("gf2^32mult")
menu_item_galois.addAction("gf2^50mult")
menu_item_galois.addAction("gf2^64mult")
menu_item_galois.addAction("gf2^100mult")
menu_item_galois.addAction("gf2^127mult")
menu_item_galois.addAction("gf2^128mult")
menu_item_galois.addAction("gf2^256mult")
menu_item_galois.addAction("gf2^512mult")
menu_item_hamming = menu_item_gate.addMenu("Hamming Code Functions")
menu_item_hamming.addAction("ham3")
menu_item_hamming.addAction("ham7")
menu_item_hamming.addAction("ham15")
menu_item_hbw = menu_item_gate.addMenu("Hidden Weight Coding Functions")
menu_item_hbw.addAction("hbw4")
menu_item_hbw.addAction("hbw5")
menu_item_hbw.addAction("hbw6")
menu_item_hbw.addAction("hbw7")
menu_item_hbw.addAction("hbw8")
menu_item_hbw.addAction("hbw9")
menu_item_hbw.addAction("hbw10")
menu_item_hbw.addAction("hbw11")
menu_item_hbw.addAction("hbw12")
menu_item_hbw.addAction("hbw13")
menu_item_hbw.addAction("hbw14")
menu_item_hbw.addAction("hbw15")
menu_item_hbw.addAction("hbw16")
menu_item_hbw.addAction("hbw20")
menu_item_hbw.addAction("hbw50")
menu_item_hbw.addAction("hbw100")
menu_item_hbw.addAction("hbw200")
menu_item_hbw.addAction("hbw500")
menu_item_hbw.addAction("hbw1000")
menu_item_mdd = menu_item_gate.addMenu("MDD Worst Case")
menu_item_mdd.addAction("3_17.tfc")
menu_item_mdd.addAction("4_49")
menu_item_modular = menu_item_gate.addMenu("Modula Adders")
menu_item_modular.addAction("mod5adder")
menu_item_modular.addAction("mod1024adder")
menu_item_modular.addAction("mod1048576adder")
menu_item_prime = menu_item_gate.addMenu("N-th Prime")
menu_item_prime.addAction("nth_prime3_inc")
menu_item_prime.addAction("nth_prim4_inc")
menu_item_prime.addAction("nth_prime5_inc")
menu_item_prime.addAction("nth_prime6_inc")
menu_item_prime.addAction("nth_prime7_inc")
menu_item_prime.addAction("nth_prime8_inc")
menu_item_prime.addAction("nth_prime9_inc")
menu_item_prime.addAction("nth_prime10_inc")
menu_item_prime.addAction("nth_prime11_inc")
menu_item_prime.addAction("nth_prime12_inc")
menu_item_prime.addAction("nth_prime13_inc")
menu_item_prime.addAction("nth_prime14_inc")
menu_item_prime.addAction("nth_prime15_inc")
menu_item_prime.addAction("nth_prime16-inc")
menu_item_permanent = menu_item_gate.addMenu("Permanent")
menu_item_permanent.addAction("permanent1x1")
menu_item_permanent.addAction("permanent2x2")
menu_item_permanent.addAction("permanent3x3")
menu_item_permanent.addAction("permanent4x4")
menu_item_rd = menu_item_gate.addMenu("RD-Input Weight functions")
menu_item_rd.addAction("rd53")
menu_item_rd.addAction("rd73")
menu_item_rd.addAction("rd84")
menu_item_sym = menu_item_gate.addMenu("Symmetric Functions")
menu_item_sym.addAction("6sym")
menu_item_sym.addAction("9sym")
menu_item_oth = menu_item_gate.addMenu("Others")
menu_item_oth.addAction("2_4dec")
menu_item_oth.addAction("2of5")
menu_item_oth.addAction("xor5")
self.setWindowTitle("Reversible Fault Testing")
menu_item.triggered[QAction].connect(self.truth_table_gen)
def windowaction(self, q):
print("triggered")
print(q.text())
if "New" == "New":
MainWindow.count += 1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("tst")
self.mdi.addSubWindow(sub)
sub.show()
# truth table display widget
def truth_table_gen(self, q):
MainWindow.count += 1
MainWindow.filename = q.text()
to_readfile = open(q.text(), 'r')
try:
reading_file = to_readfile.read()
writefile = open('a.tfc', 'w')
try:
writefile.write(reading_file)
finally:
writefile.close()
finally:
to_readfile.close()
subprocess.call(['python truth_gen.py'], shell=True)
exx = UserWindow()
self.mdi.addSubWindow(exx)
exx.show()
self.mdi.tileSubWindows()
def main():
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
#ex.resize(1366, 750)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
when i click on button inside the Qmdi area widget, the code crashes.
I'm upgrading things as the title says, and now doing a rebuild_index seems to do nothing.
The output is a simple:
$ ./manage.py rebuild_index --noinput
Removing all documents from your index because you said so.
All documents removed.
Indexing 17019 users
Indexing 76 gears
Indexing 186523 images
and all of my prepare_FOO functions are not run.
These are my settings:
HAYSTACK_DEFAULT_OPERATOR = 'AND'
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 70
HAYSTACK_CONNECTIONS = {
'default': {
'engine': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8983/solr',
'EXCLUDED_INDEXES': [
'threaded_messages.search_indexes.Thread',
'threaded_messages.search_indexes.ThreadIndex',
],
},
}
And these are my indexes:
# Python
import string
import re
import datetime
# Django
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
# Third party apps
from haystack.indexes import *
from hitcount.models import HitCount
from toggleproperties.models import ToggleProperty
# This app
from astrobin.models import Image
from astrobin.models import DeepSky_Acquisition
from astrobin.models import SolarSystem_Acquisition
from astrobin.models import UserProfile
from astrobin.models import Gear, CommercialGear, RetailedGear
from astrobin.utils import unique_items
# Other AstroBin apps
from nested_comments.models import NestedComment
def _get_integration(image):
deep_sky_acquisitions = DeepSky_Acquisition.objects.filter(image=image)
solar_system_acquisition = None
integration = 0
try:
solar_system_acquisition = SolarSystem_Acquisition.objects.get(image=image)
except:
pass
if deep_sky_acquisitions:
for a in deep_sky_acquisitions:
if a.duration and a.number:
integration += (a.duration * a.number)
elif solar_system_acquisition:
return 0
return integration
def _prepare_likes(obj):
return ToggleProperty.objects.toggleproperties_for_object("like", obj).count()
def _prepare_moon_phase(obj):
from moon import MoonPhase
deep_sky_acquisitions = DeepSky_Acquisition.objects.filter(image=obj)
moon_illuminated_list = []
if deep_sky_acquisitions:
for a in deep_sky_acquisitions:
if a.date is not None:
m = MoonPhase(a.date)
moon_illuminated_list.append(m.illuminated * 100.0)
if len(moon_illuminated_list) == 0:
# We must make an assumption between 0 and 100, or this won't
# show up in any searches.
return 0
return sum(moon_illuminated_list) / float(len(moon_illuminated_list))
def _prepare_first_acquisition_date(obj):
deep_sky_acquisitions = DeepSky_Acquisition.objects.filter(image=obj)
solar_system_acquisition = None
try:
solar_system_acquisition = SolarSystem_Acquisition.objects.get(image=obj)
except:
pass
date = None
if deep_sky_acquisitions:
date = deep_sky_acquisitions[0].date
for a in deep_sky_acquisitions:
if a.date is not None and date is not None:
if a.date < date:
date = a.date
elif solar_system_acquisition:
date = solar_system_acquisition.date
return date
def _prepare_last_acquisition_date(obj):
deep_sky_acquisitions = DeepSky_Acquisition.objects.filter(image=obj)
solar_system_acquisition = None
try:
solar_system_acquisition = SolarSystem_Acquisition.objects.get(image=obj)
except:
pass
date = None
if deep_sky_acquisitions:
date = deep_sky_acquisitions[0].date
for a in deep_sky_acquisitions:
if a.date is not None and date is not None:
if a.date > date:
date = a.date
elif solar_system_acquisition:
date = solar_system_acquisition.date
return date if date else datetime.datetime.min
def _prepare_views(obj, content_type):
views = 0
try:
views = HitCount.objects.get(object_pk = obj.pk, content_type__name = content_type).hits
except:
pass
return views
def _prepare_min_aperture(obj):
d = 0
for telescope in obj.imaging_telescopes.all():
if telescope.aperture is not None and (d == 0 or telescope.aperture < d):
d = int(telescope.aperture)
return d
def _prepare_max_aperture(obj):
import sys
d = sys.maxint
for telescope in obj.imaging_telescopes.all():
if telescope.aperture is not None and (d == sys.maxint or telescope.aperture > d):
d = int(telescope.aperture)
return d
def _prepare_min_pixel_size(obj):
s = 0
for camera in obj.imaging_cameras.all():
if camera.pixel_size is not None and (s == 0 or camera.pixel_size < s):
s = int(camera.pixel_size)
return s
def _prepare_max_pixel_size(obj):
import sys
s = sys.maxint
for camera in obj.imaging_cameras.all():
if camera.pixel_size is not None and (s == sys.maxint or camera.pixel_size > s):
s = int(camera.pixel_size)
return s
def _prepare_telescope_types(obj):
return [x.type for x in obj.imaging_telescopes.all()]
def _prepare_camera_types(obj):
return [x.type for x in obj.imaging_cameras.all()]
def _prepare_comments(obj):
ct = ContentType.objects.get(app_label = 'astrobin', model = 'image')
return NestedComment.objects.filter(
content_type = ct,
object_id = obj.id,
deleted = False).count()
class GearIndex(SearchIndex, Indexable):
model_weight = IntegerField()
text = CharField(document=True, use_template=True)
images = IntegerField()
# Total likes of all images taken with this item.
likes = IntegerField()
# Total integration of images taken with this item.
integration = FloatField()
# Total views on images taken with this item.
views = IntegerField()
# Number of bookmarks on images taken with this item.
bookmarks = IntegerField()
# Number of comments on images taken with this item.
comments = IntegerField()
producers = MultiValueField()
retailers = MultiValueField()
def index_queryset(self, using = None):
return self.get_model().objects\
.exclude(commercial = None)\
.filter(commercial__producer__groups__name = 'Paying')
def get_model(self):
return Gear
def get_images(self, obj):
filters = (\
Q(imaging_telescopes = obj) |\
Q(guiding_telescopes = obj) |\
Q(mounts = obj) |\
Q(imaging_cameras = obj) |\
Q(guiding_cameras = obj) |\
Q(focal_reducers = obj) |\
Q(software = obj) |\
Q(filters = obj) |\
Q(accessories = obj)\
)
return Image.objects.filter(filters).distinct()
def prepare_model_weight(self, obj):
# Printing here just because it's the first "prepare" function.
print "%s: %d" % (obj.__class__.__name__, obj.pk)
return 100;
def prepare_images(self, obj):
return len(self.get_images(obj))
def prepare_likes(self, obj):
likes = 0
for i in self.get_images(obj):
likes += ToggleProperty.objects.toggleproperties_for_object("like", i).count()
return likes
def prepare_integration(self, obj):
integration = 0
for i in self.get_images(obj):
integration += _get_integration(i)
return integration / 3600.0
def prepare_views(self, obj):
views = 0
for i in self.get_images(obj):
views += _prepare_views(i, 'image')
return views
def prepare_bookmarks(self, obj):
bookmarks = 0
for i in self.get_images(obj):
bookmarks += ToggleProperty.objects.toggleproperties_for_object("bookmark", i).count()
return bookmarks
def prepare_comments(self, obj):
comments = 0
for i in self.get_images(obj):
comments += _prepare_comments(i)
return comments
def prepare_producers(self, obj):
producers = CommercialGear.objects\
.filter(base_gear = obj)\
.exclude(Q(producer__userprofile__company_name = None) | Q(producer__userprofile__company_name = ""))
return ["%s" % x.producer.userprofile.company_name for x in producers]
def prepare_retailers(self, obj):
retailers = RetailedGear.objects\
.filter(gear = obj)\
.exclude(Q(retailer__userprofile__company_name = None) | Q(retailer__userprofile__company_name = ""))
return ["%s" % x.retailer.userprofile.company_name for x in retailers]
class UserIndex(SearchIndex, Indexable):
model_weight = IntegerField()
text = CharField(document=True, use_template=True)
images = IntegerField()
avg_integration = FloatField()
# Total likes of all user's images.
likes = IntegerField()
# Total likes of all user's images.
average_likes = FloatField()
# Normalized likes (best images only)
normalized_likes = FloatField()
# Number of followers
followers = IntegerField()
# Total user ingegration.
integration = FloatField()
# Average moon phase under which this user has operated.
moon_phase = FloatField()
# First and last acquisition dates, including all images of course.
first_acquisition_date = DateTimeField()
last_acquisition_date = DateTimeField()
# Total views from all images.
views = IntegerField()
# Min and max aperture of all telescopes used in this user's images.
min_aperture = IntegerField()
max_aperture = IntegerField()
# Min and max pixel size of all cameras used in this user's images.
min_pixel_size = IntegerField()
max_pixel_size = IntegerField()
# Number of bookmarks on own images
bookmarks = IntegerField()
# Types of telescopes and cameras with which this user has imaged.
telescope_types = MultiValueField()
camera_types = MultiValueField()
comments = IntegerField()
comments_written = IntegerField()
username = CharField(model_attr = 'username')
def index_queryset(self, using = None):
return self.get_model().objects.all()
def get_model(self):
return User
def prepare_model_weight(self, obj):
# Printing here just because it's the first "prepare" function.
print "%s: %d" % (obj.__class__.__name__, obj.pk)
return 200;
def prepare_images(self, obj):
return Image.objects.filter(user = obj).count()
def prepare_avg_integration(self, obj):
integration = 0
images = 0
for i in Image.objects.filter(user = obj):
image_integration = _get_integration(i)
if image_integration:
images += 1
integration += image_integration
return (integration / 3600.0) / images if images else 0
def prepare_likes(self, obj):
likes = 0
for i in Image.objects.filter(user = obj):
likes += ToggleProperty.objects.toggleproperties_for_object("like", i).count()
return likes
def prepare_average_likes(self, obj):
likes = self.prepare_likes(obj)
images = self.prepare_images(obj)
return likes / float(images) if images > 0 else 0
def prepare_normalized_likes(self, obj):
def average(values):
if len(values):
return sum(values) / float(len(values))
return 0
def index(values):
import math
return average(values) * math.log(len(values)+1, 10)
avg = self.prepare_average_likes(obj)
norm = []
for i in Image.objects.filter(user = obj):
likes = i.likes()
if likes >= avg:
norm.append(likes)
if len(norm) == 0:
return 0
return index(norm)
def prepare_followers(self, obj):
return ToggleProperty.objects.filter(
property_type = "follow",
content_type = ContentType.objects.get_for_model(User),
object_id = obj.pk
).count()
def prepare_integration(self, obj):
integration = 0
for i in Image.objects.filter(user = obj):
integration += _get_integration(i)
return integration / 3600.0
def prepare_moon_phase(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l.append(_prepare_moon_phase(i))
if len(l) == 0:
return 0
return reduce(lambda x, y: x + y, l) / len(l)
def prepare_first_acquisition_date(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l.append(_prepare_first_acquisition_date(obj))
if len(l) == 0:
return None
return min(l)
def prepare_last_acquisition_date(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l.append(_prepare_last_acquisition_date(obj))
if len(l) == 0:
return None
return max(l)
def prepare_views(self, obj):
views = 0
for i in Image.objects.filter(user = obj):
views += _prepare_views(i, 'image')
return views
def prepare_min_aperture(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l.append(_prepare_min_aperture(i))
if len(l) == 0:
return 0
return min(l)
def prepare_max_aperture(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l.append(_prepare_max_aperture(i))
if len(l) == 0:
return 0
return max(l)
def prepare_min_pixel_size(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l.append(_prepare_min_pixel_size(i))
if len(l) == 0:
return 0
return min(l)
def prepare_max_pixel_size(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l.append(_prepare_max_pixel_size(i))
if len(l) == 0:
return 0
return max(l)
def prepare_bookmarks(self, obj):
bookmarks = 0
for i in Image.objects.filter(user = obj):
bookmarks += ToggleProperty.objects.toggleproperties_for_object("bookmark", i).count()
return bookmarks
def prepare_telescope_types(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l += _prepare_telescope_types(i)
return unique_items(l)
def prepare_camera_types(self, obj):
l = []
for i in Image.objects.filter(user = obj):
l += _prepare_camera_types(i)
return unique_items(l)
def prepare_comments(self, obj):
comments = 0
for i in Image.objects.filter(user = obj):
comments += _prepare_comments(i)
return comments
def prepare_comments_written(self, obj):
return NestedComment.objects.filter(author = obj, deleted = False).count()
class ImageIndex(SearchIndex, Indexable):
model_weight = IntegerField()
text = CharField(document=True, use_template=True)
uploaded = DateTimeField(model_attr='uploaded')
likes = IntegerField()
integration = FloatField()
moon_phase = FloatField()
first_acquisition_date = DateTimeField()
last_acquisition_date = DateTimeField()
views = IntegerField()
solar_system_main_subject = IntegerField()
is_deep_sky = BooleanField()
is_clusters = BooleanField()
is_nebulae = BooleanField()
is_galaxies = BooleanField()
is_solar_system = BooleanField()
is_sun = BooleanField()
is_moon = BooleanField()
is_planets = BooleanField()
is_comets = BooleanField()
license = IntegerField(model_attr = 'license')
min_aperture = IntegerField()
max_aperture = IntegerField()
min_pixel_size = IntegerField()
max_pixel_size = IntegerField()
bookmarks = IntegerField()
telescope_types = MultiValueField()
camera_types = MultiValueField()
comments = IntegerField()
is_commercial = BooleanField()
subject_type = IntegerField(model_attr = 'subject_type')
username = CharField(model_attr = 'user__username')
def index_queryset(self, using = None):
return self.get_model().objects.filter(moderator_decision = 1)
def get_model(self):
return Image
def prepare_model_weight(self, obj):
# Printing here just because it's the first "prepare" function.
print "%s: %d" % (obj.__class__.__name__, obj.pk)
return 300;
def prepare_likes(self, obj):
return _prepare_likes(obj)
def prepare_integration(self, obj):
return _get_integration(obj)
def prepare_moon_phase(self, obj):
return _prepare_moon_phase(obj)
def prepare_first_acquisition_date(self, obj):
return _prepare_first_acquisition_date(obj)
def prepare_last_acquisition_date(self, obj):
return _prepare_last_acquisition_date(obj)
def prepare_views(self, obj):
return _prepare_views(obj, 'image')
def prepare_solar_system_main_subject(self, obj):
return obj.solar_system_main_subject
def prepare_is_deep_sky(self, obj):
return DeepSky_Acquisition.objects.filter(image = obj).count() > 0
def prepare_is_solar_system(self, obj):
if obj.solar_system_main_subject:
return True
if SolarSystem_Acquisition.objects.filter(image = obj):
return True
return False
def prepare_is_sun(self, obj):
return obj.solar_system_main_subject == 0
def prepare_is_moon(self, obj):
return obj.solar_system_main_subject == 1
def prepare_is_planets(self, obj):
return obj.solar_system_main_subject in range(2, 8)
def prepare_is_comets(self, obj):
return obj.solar_system_main_subject == 10
def prepare_min_aperture(self, obj):
return _prepare_min_aperture(obj)
def prepare_max_aperture(self, obj):
return _prepare_max_aperture(obj)
def prepare_min_pixel_size(self, obj):
return _prepare_min_pixel_size(obj)
s = 0
for camera in obj.imaging_cameras.all():
if camera.pixel_size is not None and (s == 0 or camera.pixel_size < s):
s = int(camera.pixel_size)
return s
def prepare_max_pixel_size(self, obj):
return _prepare_max_pixel_size(obj)
import sys
s = sys.maxint
for camera in obj.imaging_cameras.all():
if camera.pixel_size is not None and (s == sys.maxint or camera.pixel_size > s):
s = int(camera.pixel_size)
return s
def prepare_bookmarks(self, obj):
return ToggleProperty.objects.toggleproperties_for_object("bookmark", obj).count()
def prepare_telescope_types(self, obj):
return _prepare_telescope_types(obj)
def prepare_camera_types(self, obj):
return _prepare_camera_types(obj)
def prepare_comments(self, obj):
return _prepare_comments(obj)
def prepare_is_commercial(self, obj):
commercial_gear = CommercialGear.objects.filter(image = obj)
return commercial_gear.count() > 0
Any idea what I might be missing? Thanks!
Got it. 'ENGINE' should be all capitals, in the settings.
""" Is there any way to print arithmetic parser for any input parenthesized arithmetic expression"""
importing nltk and system module
import nltk
import sys
import operator
continueChoice = 'y'
while continueChoice in ['y', 'Y']:
choice = int(raw_input(' 1. String Parser\n 2. Airthmatic Parser\n Enter Your Choice: '))
String Parser
if choice == 1 :
sentence = raw_input("Enter Your Sentence: ")
words = sentence.split()
try:
#Fetching the user input grammar
grammar_path = nltk.data.load("input_grammar.cfg")
ch_parser = nltk.ChartParser(grammar_path)
for tree in ch_parser.parse(words):
print tree
tree.draw()
except:
fin = open("input_grammar.cfg", "w+")
fin.write("\n")
print "Enter Your Grammar: "
# To take grammar as an input from the user
while 1:
try:
line = sys.stdin.readline()
fin.write(line)
except KeyboardInterrupt:
break
fin.close()
#Fetching the user input grammar
grammar_path = nltk.data.load("input_grammar.cfg")
ch_parser = nltk.ChartParser(grammar_path)
for tree in ch_parser.parse(words):
print tree
tree.draw()
# Arithmetic Parser
elif choice == 2:
# Stack Defination
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
# Binary Tree Defination
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if isinstance(newNode, BinaryTree):
t = newNode
else:
t = BinaryTree(newNode)
if self.leftChild is not None:
t.left = self.leftChild
self.leftChild = t
def insertRight(self,newNode):
if isinstance(newNode,BinaryTree):
t = newNode
else:
t = BinaryTree(newNode)
if self.rightChild is not None:
t.right = self.rightChild
self.rightChild = t
def isLeaf(self):
return ((not self.leftChild) and (not self.rightChild))
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.key = obj
def getRootVal(self,):
return self.key
def postorder(self):
if self.leftChild:
self.leftChild.postorder()
if self.rightChild:
self.rightChild.postorder()
print(self.key)
def postordereval(self):
opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}
res1 = None
res2 = None
if self.leftChild:
res1 = self.leftChild.postordereval() #// \label{peleft}
if self.rightChild:
res2 = self.rightChild.postordereval() #// \label{peright}
if res1 and res2:
return opers[self.key](res1,res2) #// \label{peeval}
else:
return self.key
# Aritmetic Parsing
def buildParseTree(fpexp):
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i not in ['+', '-', '*', '/', ')']:
currentTree.setRootVal(int(i))
parent = pStack.pop()
currentTree = parent
elif i in ['+', '-', '*', '/']:
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
else:
raise ValueError
return eTree
expression = raw_input("Enter Fully Paranthesized Arithmetic Expression: ")
# Checking Validity of Expression Entered
lst = expression.split()
parIncrement=0
parDecrement=0
for i in lst:
if i=='(':
parIncrement+=1
elif i==')':
parDecrement+=1
if parIncrement != parDecrement:
print ("Invalid!\n\t\t**** Expression is Not Correctly Parenthesized. ****")
exit(0)
pt = buildParseTree(expression)
pt.postorder()
print "Ans is: "
print pt.postordereval()
continueChoice = raw_input("Do you want to continue?(Y/N): ")
I need to make a treeView with 4 columns with a checkbox in the first
column. I have made the tree view, just that I do not put the
checkbox in the first column. I tried but it gets me in every position
(row, column ) ...........
Here is my code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from copy import deepcopy
from cPickle import dumps, load, loads
from cStringIO import StringIO
class myNode(object):
def __init__(self, name, state, description,otro, parent=None,checked=False):
self.name = QString(name)
self.state = QString(state)
self.description = QString(description)
self.otro = QString(otro)
self.parent = parent
self.children = []
self.setParent(parent)
def setParent(self, parent):
if parent != None:
self.parent = parent
self.parent.appendChild(self)
else:
self.parent = None
def appendChild(self, child):
self.children.append(child)
def childAtRow(self, row):
return self.children[row]
def rowOfChild(self, child):
for i, item in enumerate(self.children):
if item == child:
return i
return -1
def removeChild(self, row):
value = self.children[row]
self.children.remove(value)
return True
def __len__(self):
return len(self.children)
class myModel(QAbstractItemModel):
def __init__(self, parent=None):
super(myModel, self).__init__(parent)
self.treeView = parent
self.columns = 4
self.headers = ['Directorio','Peso','Tipo','Modificado']
# Create items
self.root = myNode('root', 'on', 'this is root','asd', None)
itemA = myNode('itemA', 'on', 'this is item A','dfg', self.root)
itemB = myNode('itemB', 'on', 'this is item B','fgh', self.root)
itemC = myNode('itemC', 'on', 'this is item C','cvb', self.root)
def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.headers[section])
return QVariant()
def supportedDropActions(self):
return Qt.CopyAction | Qt.MoveAction
def flags(self, index):
return Qt.ItemIsEnabled | Qt.ItemIsSelectable| Qt.ItemIsUserCheckable
def insertRow(self, row, parent):
return self.insertRows(row, 1, parent)
def insertRows(self, row, count, parent):
self.beginInsertRows(parent, row, (row + (count - 1)))
self.endInsertRows()
return True
def removeRow(self, row, parentIndex):
return self.removeRows(row, 1, parentIndex)
def removeRows(self, row, count, parentIndex):
self.beginRemoveRows(parentIndex, row, row)
node = self.nodeFromIndex(parentIndex)
node.removeChild(row)
self.endRemoveRows()
return True
def index(self, row, column, parent):
node = self.nodeFromIndex(parent)
return self.createIndex(row, column, node.childAtRow(row))
def data(self, index, role):
if role != Qt.DisplayRole:
return QVariant()
if not index.isValid():
return None
node = self.nodeFromIndex(index)
if role == Qt.DisplayRole:
if index.column() == 0:
return QVariant(node.name)
if role == Qt.CheckStateRole:
if node.checked():
return Qt.Checked
else:
return Qt.Unchecked
if index.column() == 1:
return QVariant(node.state)
elif index.column() == 2:
return QVariant(node.description)
elif index.column() == 3:
return QVariant(node.otro)
else:
return QVariant()
def setData(self, index, value, role=Qt.EditRole):
if index.isValid():
if role == Qt.CheckStateRole:
node = index.internalPointer()
node.setChecked(not node.checked())
return True
return False
def columnCount(self, parent):
return self.columns
def rowCount(self, parent):
node = self.nodeFromIndex(parent)
if node is None:
return 0
return len(node)
def parent(self, child):
if not child.isValid():
return QModelIndex()
node = self.nodeFromIndex(child)
if node is None:
return QModelIndex()
parent = node.parent
if parent is None:
return QModelIndex()
grandparent = parent.parent
if grandparent is None:
return QModelIndex()
row = grandparent.rowOfChild(parent)
assert row != - 1
return self.createIndex(row, 0, parent)
def nodeFromIndex(self, index):
return index.internalPointer() if index.isValid() else self.root
class myTreeView(QTreeView):
def __init__(self, parent=None):
super(myTreeView, self).__init__(parent)
self.myModel = myModel()
self.setModel(self.myModel)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(600, 400)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.treeView = myTreeView(self.centralwidget)
self.treeView.setObjectName("treeView")
self.horizontalLayout.addWidget(self.treeView)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setGeometry(QRect(0, 0, 600, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QApplication.translate("MainWindow",
"MainWindow", None, QApplication.UnicodeUTF8))
if __name__ == "__main__":
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
There are a few things wrong with your example code.
Firstly, your node class is missing some methods:
class myNode(object):
def __init__(self, name, state, description, otro, parent=None, checked=False):
...
self.setChecked(checked)
def checked(self):
return self._checked
def setChecked(self, checked=True):
self._checked = bool(checked)
Secondly, your model's flags method needs to return the correct values:
def flags(self, index):
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if index.column() == 0:
return flags | Qt.ItemIsUserCheckable
return flags
And finally, your model's data method needs to return the correct values:
def data(self, index, role):
if not index.isValid():
return None
node = self.nodeFromIndex(index)
if role == Qt.DisplayRole:
if index.column() == 0:
return QVariant(node.name)
if index.column() == 1:
return QVariant(node.state)
if index.column() == 2:
return QVariant(node.description)
if index.column() == 3:
return QVariant(node.otro)
elif role == Qt.CheckStateRole:
if index.column() == 0:
if node.checked():
return Qt.Checked
return Qt.Unchecked
return QVariant()
QTreeView determine which cell should have checkbox by the result of QAbstractItemModel::flags function. You should return value with Qt.ItemIsUserCheckable only for first column and without for others:
def flags(self, index):
if index.column() == 0:
return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
return Qt.ItemIsEnabled | Qt.ItemIsSelectable