def test_index_new_row(self): data = 'house,2005-10-10\nwindow,2005-05-10\ncomputer,2005-10-10' handler = Things() handler.load_state_from_string(data) handler.add_row(['flower', Date.decode('2005-05-10')]) self.assertEqual(handler.search(date=Date.decode('2005-05-10')), [1,3])
def test_load_state_with_schema(self): handler = Languages() handler.load_state_from_string(TEST_DATA_1) rows = list(handler.get_rows()) self.assertEqual(rows, [ [u"python", 'http://python.org/', 52343, Date.decode('2003-10-23')], [u"ruby", 'http://ruby-lang.org/', 42352, Date.decode('2001-03-28')]])
def test_load_state_with_schema(self): handler = Languages() handler.load_state_from_string(TEST_DATA_1) rows = list(handler.get_rows()) self.assertEqual(rows, [[ u"python", 'http://python.org/', 52343, Date.decode('2003-10-23') ], [ u"ruby", 'http://ruby-lang.org/', 42352, Date.decode('2001-03-28') ]])
class Books(Table): record_properties = { 'title': Unicode(multilingual=True), 'author': Unicode } record_parameters = { 'language': String(multiple=False), 'birth': Date(multiple=False), 'death': Date(multiple=False) }
def test_build_csv_data(self): handler = People() handler.load_state_from_string('') handler.add_row(['Piotr', 'Macuk', Date.decode('1975-12-08')]) handler.add_row(['Basia', 'Macuk', Date.decode('2002-02-14')]) self.assertEqual(handler.search(surname='macuk'), [0, 1]) handler.add_row(['Pawe³', 'Macuk', Date.decode('1977-05-13')]) self.assertEqual(handler.search(surname='macuk'), [0, 1, 2]) handler.del_row(2) self.assertEqual(handler.search(surname='macuk'), [0, 1]) handler.del_row(0) self.assertEqual(handler.search(surname='macuk'), [1])
def make_link(self, title, date, method=None): if method is None: method = self.context.view.method # Build link link = ';{method}?start={date}&end={date}' link = link.format(date=Date.encode(date), method=method) # Enabled ? enabled = self.context.view.method == method return {'title': title, 'link': link, 'css': 'enabled' if enabled else ''}
def make_link(self, title, date, method=None): if method is None: method = self.context.view.method # Build link link = ';{method}?start={date}&end={date}' link = link.format(date=Date.encode(date), method=method) # Enabled ? enabled = self.context.view.method == method return { 'title': title, 'link': link, 'css': 'enabled' if enabled else '' }
def get_calendar_namespace(self, resource, context): # Base namespace proxy = super(MultiweekView, self) namespace = proxy.get_calendar_namespace(resource, context) # Get today date today_date = date.today() # Current date c_date = self.get_current_date(context) # Display link to add/edit an event with_new_url = self.get_with_new_url(resource, context) # Start date start = self.get_start_date(c_date) nweeks = self.get_nweeks(c_date, start) # Get header line with days of the week namespace['days_of_week'] = self.days_of_week_ns(start, ndays=self.ndays) # Get the 5 weeks namespace['weeks'] = [] link = ';new_event?dtstart={date}&dtend={date}' day = start for kk in range(nweeks): ns_week = [] # 7 days a week for d in range(7): # Day in timetable if d < self.ndays: ns_day = { 'url': None, 'nday': day.day, 'selected': (day == today_date), 'events': [] } if day.day == 1: month_name = months[day.month].gettext() ns_day['nday'] = u'%d %s' % (day.day, month_name) if with_new_url: ns_day['url'] = link.format(date=Date.encode(day)) # Get a list of events to display on view for event in self.get_events(day): ns_day['events'].append({ 'stream': event.render(event=event, day=day), 'color': event.get_color(), 'status': event.get_value('status') or 'cal_busy' }) ns_week.append(ns_day) day = day + timedelta(1) namespace['weeks'].append(ns_week) return namespace
def value_(self): value = self.value if value is None: return '', '' try: value = self.datatype.decode(value) except StandardError: # XXX Heuristic here from itools.web import get_context context = get_context() return (context.get_form_value(self.name), context.get_form_value('%s_time' % self.name)) if type(value) is datetime: value_date = value.date() value_time = value.time() else: value_date = value value_time = self.value_time_default if value_time is None: return Date.encode(value_date), '' return Date.encode(value_date), value_time.strftime('%H:%M')
def get_calendar_namespace(self, resource, context): # Base namespace proxy = super(MultiweekView, self) namespace = proxy.get_calendar_namespace(resource, context) # Get today date today_date = date.today() # Current date c_date = self.get_current_date(context) # Display link to add/edit an event with_new_url = self.get_with_new_url(resource, context) # Start date start = self.get_start_date(c_date) nweeks = self.get_nweeks(c_date, start) # Get header line with days of the week namespace['days_of_week'] = self.days_of_week_ns(start, ndays=self.ndays) # Get the 5 weeks namespace['weeks'] = [] link = ';new_event?dtstart={date}&dtend={date}' day = start for kk in range(nweeks): ns_week = [] # 7 days a week for d in range(7): # Day in timetable if d < self.ndays: ns_day = { 'url': None, 'nday': day.day, 'selected': (day == today_date), 'events': []} if day.day == 1: month_name = months[day.month].gettext() ns_day['nday'] = u'%d %s' % (day.day, month_name) if with_new_url: ns_day['url'] = link.format(date=Date.encode(day)) # Get a list of events to display on view for event in self.get_events(day): ns_day['events'].append( {'stream': event.render(event=event, day=day), 'color': event.get_color(), 'status': event.get_value('status') or 'cal_busy'}) ns_week.append(ns_day) day = day + timedelta(1) namespace['weeks'].append(ns_week) return namespace
def start(self): return Date.encode(self.c_date)
def get_grid_data(data, grid, start_date=None, templates=(None, None), with_new_url=True, add_icon=None): """ Build final namespace from data and grid to be used in gridlayout templates. """ template, template_fd = templates if template is None: template = default_template if template_fd is None: template_fd = default_template_fd # Build grid with Time objects grid = [Time.decode(x) for x in grid] # Build.. headers, events_with_time, events_without_time = [], [], [] for column in data: time_grid = [] full_day = [] events = column['events'] # Build the time grid for event in events: start, end = event['start'], event['end'] # Put the event in the right place if not event['TIME']: event['ns'] = stl(template_fd, {'event': event}) full_day.append(event) else: start, end = Time.decode(start), Time.decode(end) insert_item(time_grid, start, end, event, event['cal']) # Fix grid if needed if start not in grid: grid.append(start) if end not in grid: grid.append(end) # Finalize headers.append(column.get('header')) events_with_time.append(time_grid) events_without_time.append(full_day) # Sort the grid grid.sort() ###################################################################### # Build_timegrids_collection with given data: # (events_with_time, headers, grid, events_without_time, # start_date=None) today = date.today() if start_date: current_date = start_date ns_full_day = None if filter(lambda x: x, events_without_time): ns_full_day = [] ns_headers = [] cols = [] for i in range(len(events_with_time)): table, ncols = render_namespace(events_with_time[i], grid, with_new_url) if headers is not None: if current_date == today: h_class = 'cal_day_selected' else: h_class = 'header' ns_headers.append({ 'header': headers[i], 'width': ncols, 'class': h_class }) if ns_full_day is not None: ns_full_day.append({ 'events': events_without_time[i], 'width': ncols }) # Add date to newurl for each cell having this parameter # Build namespace for the content of cells containing event (new) if start_date is not None: str_date = Date.encode(current_date) for column in table: for cell in column['cells']: if cell['newurl'] is not None: url = '%s&date=%s' % (cell['newurl'], str_date) cell['newurl'] = url if cell['new']: cell['ns'] = stl(template, { 'cell': cell, 'add_icon': add_icon }) current_date = current_date + timedelta(1) cols.append(table) body = [] for i in range(len(grid) - 1): body.append({ 'start': Time.encode(grid[i]), 'end': Time.encode(grid[i + 1]), 'items': [col[i] for col in cols] }) namespace = { 'headers': ns_headers, 'body': body, 'full_day_events': ns_full_day } return namespace
from ikaaro.table import OrderedTable, OrderedTableFile from ikaaro.table_views import OrderedTable_View, Table_EditRecord from ikaaro.text import CSV from ikaaro.tracker import Tracker # Import from wiki from wiki import WikiFolder # Import from tzm from chapter.chapter import Chapters from phoenix.phoenix import Phoenix from project.project import Projects #from training.training import Training from forums.forums import Forums message_date = Date.decode('2003-10-23') MESSAGES_DATA = """0, 0, 120124, 'hello world'""" ########################################################################### # Resources ########################################################################### class Affiliations(CSV): class_id = 'affiliations' def init_resource(self): super(Affiliations, self).init_resource() path = get_abspath('data/affiliations.csv') self.handler.load_state_from_uri(path) class Industry(CSV):
rest_create = Rest_Create rest_read = Rest_Read rest_update = Rest_Update rest_delete = Rest_Delete rest_schema = Rest_Schema ########################################################################### # Register read-only fields ########################################################################### # Path related fields register_field('abspath', String(indexed=True, stored=True)) register_field('abspath_depth', Integer(indexed=True, stored=True)) register_field('parent_paths', String(multiple=True, indexed=True)) register_field('name', String(stored=True, indexed=True)) # Class related fields register_field('format', String(indexed=True, stored=True)) register_field('base_classes', String(multiple=True, indexed=True)) register_field('class_version', Date(indexed=True, stored=True)) # Referential integrity register_field('links', String(multiple=True, indexed=True)) register_field('onchange_reindex', String(multiple=True, indexed=True)) # Full text search register_field('text', Unicode(indexed=True)) # Various classifications register_field('is_content', Boolean(indexed=True)) # Time events register_field('next_time_event', DateTime(stored=True)) register_field('next_time_event_payload', String(stored=True))
def get_grid_data(data, grid, start_date=None, templates=(None, None), with_new_url=True, add_icon=None): """ Build final namespace from data and grid to be used in gridlayout templates. """ template, template_fd = templates if template is None: template = default_template if template_fd is None: template_fd = default_template_fd # Build grid with Time objects grid = [ Time.decode(x) for x in grid ] # Build.. headers, events_with_time, events_without_time = [], [], [] for column in data: time_grid = [] full_day = [] events = column['events'] # Build the time grid for event in events: start, end = event['start'], event['end'] # Put the event in the right place if not event['TIME']: event['ns'] = stl(template_fd, {'event': event}) full_day.append(event) else: start, end = Time.decode(start), Time.decode(end) insert_item(time_grid, start, end, event, event['cal']) # Fix grid if needed if start not in grid: grid.append(start) if end not in grid: grid.append(end) # Finalize headers.append(column.get('header')) events_with_time.append(time_grid) events_without_time.append(full_day) # Sort the grid grid.sort() ###################################################################### # Build_timegrids_collection with given data: # (events_with_time, headers, grid, events_without_time, # start_date=None) today = date.today() if start_date: current_date = start_date ns_full_day = None if filter(lambda x: x, events_without_time): ns_full_day = [] ns_headers = [] cols = [] for i in range(len(events_with_time)): table, ncols = render_namespace(events_with_time[i], grid, with_new_url) if headers is not None: if current_date == today: h_class = 'cal_day_selected' else: h_class = 'header' ns_headers.append({'header': headers[i], 'width': ncols, 'class': h_class}) if ns_full_day is not None: ns_full_day.append({'events': events_without_time[i], 'width': ncols}) # Add date to newurl for each cell having this parameter # Build namespace for the content of cells containing event (new) if start_date is not None: str_date = Date.encode(current_date) for column in table: for cell in column['cells']: if cell['newurl'] is not None: url = '%s&date=%s' % (cell['newurl'], str_date) cell['newurl'] = url if cell['new']: cell['ns'] = stl(template, {'cell': cell, 'add_icon': add_icon}) current_date = current_date + timedelta(1) cols.append(table) body = [] for i in range(len(grid)-1): body.append({'start': Time.encode(grid[i]), 'end': Time.encode(grid[i+1]), 'items': [col[i] for col in cols]}) namespace = {'headers': ns_headers, 'body': body, 'full_day_events': ns_full_day} return namespace
def test_indexes_hit_in_many_rows(self): data = 'house,2005-10-10\nwindow,2005-05-10\ncomputer,2005-10-10' handler = Things(string=data) handler.load_state_from_string(data) self.assertEqual(handler.search(date=Date.decode('2005-01-01')), []) self.assertEqual(handler.search(date=Date.decode('2005-10-10')), [0,2])
def test_indexes_hit_in_one_row(self): handler = Languages() handler.load_state_from_string(TEST_DATA_1) self.assertEqual(handler.search(number=52343), [0]) self.assertEqual(handler.search(date=Date.decode('2001-03-28')), [1])
def get_errors(self): errors = [] handler = self.get_value('data') # Consistency check # First round on variables # Starting from 1 + header lineno = 2 locals_ = {} for line in handler.get_rows(): record = {} for index, key in enumerate(handler.columns): record[key] = line[index] # Name name = record['name'] if name is None: continue if not Variable.is_valid(name): err = ERR_BAD_NAME.gettext(line=lineno, name=name) errors.append(err) continue if name in locals_: err = ERR_DUPLICATE_NAME.gettext(line=lineno, name=name) errors.append(err) continue # Type type_name = record['type'] if type_name is None: # Write down default at this time record['type'] = type_name = 'str' datatype = Type.get_type(type_name) if datatype is None: err = ERR_BAD_TYPE.gettext(line=lineno, type=type_name) errors.append(err) continue # Length length = record['length'] if length is None: # Write down default at this time record['length'] = length = 20 if not ValidInteger.is_valid(length): err = ERR_BAD_LENGTH.gettext(line=lineno, length=length) errors.append(err) continue if issubclass(datatype, SqlEnumerate): # Enumerate Options enum_option = record['enum_options'] if enum_option is None: err = ERR_MISSING_OPTIONS(line=lineno) errors.append(err) continue # Split on "/" enum_options = EnumerateOptions.split(enum_option['value']) record['enum_options'] = enum_options # Enumerate Representation enum_repr = record['enum_repr'] if enum_repr is None: # Write down default at the time of writing record['enum_repr'] = enum_repr = 'radio' if not EnumerateRepresentation.is_valid(enum_repr): err = ERR_BAD_ENUM_REPR.gettext(line=lineno, enum_repr=enum_repr) errors.append(err) continue elif issubclass(datatype, NumDecimal): # Decimals decimals = record['decimals'] if decimals is None: # Write down default at the time of writing record['decimals'] = decimals = 2 if not ValidInteger.is_valid(decimals): err = ERR_BAD_DECIMALS.gettext(line=lineno, decimals=decimals) errors.append(err) continue # Mandatory mandatory = record['mandatory'] if mandatory is None: # Write down default at the time of writing record['mandatory'] = mandatory = True if not Mandatory.is_valid(mandatory): err = ERR_BAD_MANDATORY.gettext(line=lineno, mandatory=mandatory) errors.append(err) continue # Size size = record['size'] if size is None: # Write down default at the time of writing if type_name == 'text': record['size'] = size = 5 else: record['size'] = size = length if not ValidInteger.is_valid(size): err = ERR_BAD_SIZE.gettext(line=lineno, size=size) errors.append(err) continue # Default value default = record['default'] = record['default'].strip() if default: if issubclass(datatype, EnumBoolean): value = Mandatory.decode(default) default = EnumBoolean.encode(value) elif issubclass(datatype, SqlEnumerate): datatype = datatype(options=enum_options) #default = checkid(default) or '' default = default elif issubclass(datatype, NumTime): # "0-0-0 09:00:00" -> "09:00:00" default = default.split(' ')[-1] # "09:00:00" -> "09:00" if default.count(":") > 1: default = default.rsplit(":", 1)[0] elif issubclass(datatype, NumDate): # "2010-11-18 00:00:00" -> "18/11/2010" default = default.split(' ')[0] value = Date.decode(default) default = NumDate.encode(value) elif issubclass(datatype, NumDigit): datatype = datatype(length=length) if not datatype.is_valid(default): err = ERR_BAD_DEFAULT.gettext(line=lineno, default=unicode(default, 'utf_8')) errors.append(err) continue record['default'] = default if record['enum_repr'] == 'checkbox': locals_[name] = [] else: locals_[name] = 0 lineno += 1 # Second round on references # Starting from 1 + header lineno = 2 for row in handler.get_rows(): dependency = row.get_value('dependency') if dependency: try: Expression.is_valid(dependency, locals_) except Exception, err: err = ERR_BAD_DEPENDENCY.gettext(line=lineno, err=err) errors.append(err) continue formula = row.get_value('formula') if formula: try: datatype.sum except AttributeError: err = ERR_NO_FORMULA.gettext(line=lineno, type=type_name) errors.append(err) continue try: Expression.is_valid(formula, locals_) except Exception, err: err = ERR_BAD_FORMULA.gettext(line=lineno, err=err) errors.append(err) continue
class Date_Field(Metadata_Field): datatype = Date() widget = DateWidget()
last_author = context.root.get_user_title(last_author) body = message.gettext(last_author=last_author, resource_uri=uri, title=title, language=language) # And return return subject, body def get_color(self): calendar = self.get_resource(self.get_value('calendar')) return calendar.get_value('color') # Views new_instance = Event_NewInstance edit = Event_Edit class EventModel(Model): class_id = 'model-event' class_title = MSG(u'Event model') base_class = Event # Register register_field('dates', Date(indexed=True, multiple=True))