desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
''
def exclude_tag(self, html):
try: if (html.attributes['_class'] in self.exclude_class_list): return True if (html.attributes['_class'] in self.style_lookup): self.normalstyle = self.style_lookup[html.attributes['_class']] except: pass return False
'Parses a DIV element and converts it into a format for ReportLab @param html: the DIV element to convert @return: a list containing text that ReportLab can use'
def parse_div(self, html):
content = [] select_tag = self.select_tag for component in html.components: result = select_tag(component) if (result != None): content += result if (content == []): return None return content
'Parses an A element and converts it into a format for ReportLab @param html: the A element to convert @return: a list containing text that ReportLab can use'
def parse_a(self, html):
content = [] select_tag = self.select_tag for component in html.components: result = select_tag(component) if (result != None): content += result if (content == []): return None return content
'Parses an IMG element and converts it into an Image for ReportLab @param html: the IMG element to convert @param uploadfolder: an optional uploadfolder in which to find the file @return: a list containing an Image that ReportLab can use @note: The `src` attribute of the image must either point to a static resource, d...
@staticmethod def parse_img(html, uploadfolder=None):
I = None src = html.attributes.get('_src') if src: if uploadfolder: src = src.rsplit('/', 1) src = os.path.join(uploadfolder, src[1]) else: request = current.request base_url = ('/%s/' % request.application) STATIC = ('%sstatic' % b...
'Parses a P element and converts it into a format for ReportLab @param html: the P element to convert @return: a list containing text that ReportLab can use'
def parse_p(self, html):
font_sizes = {'p': 9, 'h1': 18, 'h2': 16, 'h3': 14, 'h4': 12, 'h5': 10, 'h6': 9} font_size = None title = False try: tag = html.tag except AttributeError: pass else: font_size = font_sizes.get(tag) title = (tag != 'p') style = (self.boldstyle if title else sel...
'Parses a TABLE element and converts it into a format for ReportLab @param html: the TABLE element to convert @return: a list containing text that ReportLab can use'
def parse_table(self, html):
style = [('FONTSIZE', (0, 0), ((-1), (-1)), self.fontsize), ('VALIGN', (0, 0), ((-1), (-1)), 'TOP'), ('FONTNAME', (0, 0), ((-1), (-1)), self.font_name), ('GRID', (0, 0), ((-1), (-1)), 0.5, colors.grey)] (content, row_count) = self.parse_table_components(html, style=style) if (content == []): return ...
'Parses TABLE components @param table: the TABLE instance or a subcomponent of it @param content: the current content array @param row_count: the current number of rows in the content array @param style: the style list'
def parse_table_components(self, table, content=None, row_count=None, style=None):
if (content is None): content = [] cappend = content.append if (row_count is None): row_count = 0 rowspans = [] exclude_tag = self.exclude_tag parse_tr = self.parse_tr parse = self.parse_table_components for component in table.components: result = None if ...
'Parses a TR element and converts it into a format for ReportLab @param html: the TR element to convert @param style: the default style @param rowCnt: the row counter @param rowspans: the remaining rowspans (if any) @return: a list containing text that ReportLab can use'
def parse_tr(self, html, style, rowCnt, rowspans):
row_styles = self._styles(html) background = self._color(row_styles.get('background-color')) color = self._color(row_styles.get('color')) row = [] rappend = row.append sappend = style.append select_tag = self.select_tag font_name_bold = self.font_name_bold exclude_tag = self.exclude_...
'Get the custom styles for the given element (match by tag and classes) @param element: the HTML element (web2py helper) @param styles: the pdf_html_styles dict'
def _styles(self, element):
element_styles = {} styles = self.styles if styles: classes = element['_class'] if classes: tag = element.tag classes = set(classes.split(' ')) for (k, v) in styles.items(): (t, c) = k.split('.', 1) if (t != tag): ...
'Get the Color instance from colors for: a given name (e.g. \'white\') or Hex string (e.g. \'#FFFFFF\') @param val: the name or hex string'
@staticmethod def _color(val):
if (not val): color = None elif (val[:1] == '#'): color = HexColor(val) else: try: color = object.__getattribute__(colors, val) except AttributeError: color = None return color
'Constructor'
def __init__(self):
pass
'Extract the items from the resource @param resource: the resource @param list_fields: fields to include in list views'
def extractResource(self, resource, list_fields):
title = self.crud_string(resource.tablename, 'title_list') get_vars = Storage(current.request.get_vars) get_vars['iColumns'] = len(list_fields) (query, orderby, left) = resource.datatable_filter(list_fields, get_vars) resource.add_filter(query) data = resource.select(list_fields, left=left, limi...
'Export data as a Scalable Vector Graphic @param resource: the source of the data that is to be encoded as an SVG. This may be: resource: the resource item: a list of pre-fetched values the headings are in the first row the data types are in the second row @param attr: dictionary of parameters: * title: Th...
def encode(self, resource, **attr):
if ((resource.prefix == 'gis') and (resource.name == 'location')): list_fields = ['wkt'] else: list_fields = ['location_id$wkt'] current.s3db.gis_location.wkt.represent = None (_title, types, lfields, headers, items) = self.extractResource(resource, list_fields) wkt = items[0]['gis_l...
'Import data from a Scalable Vector Graphic @param resource: the S3Resource @param source: the source @return: an S3XML ElementTree @ToDo: Handle encodings within SVG other than UTF-8'
def decode(self, resource, source, **attr):
raise NotImplementedError return root
'Extract the rows from the resource @param resource: the resource @param list_fields: fields to include in list views'
def extract(self, resource, list_fields):
title = self.crud_string(resource.tablename, 'title_list') get_vars = dict(current.request.vars) get_vars['iColumns'] = len(list_fields) (query, orderby, left) = resource.datatable_filter(list_fields, get_vars) resource.add_filter(query) if (orderby is None): orderby = resource.get_confi...
'Export data as a Microsoft Excel spreadsheet @param data_source: the source of the data that is to be encoded as a spreadsheet, can be either of: 1) an S3Resource 2) an array of value dicts (dict of column labels as first item, list of field types as second item) 3) a dict like: {columns: [key, ...], headers: {key: la...
def encode(self, data_source, title=None, as_stream=False, **attr):
try: import xlwt except ImportError: error = self.ERROR.XLWT_ERROR current.log.error(error) raise HTTP(503, body=error) try: from xlrd.xldate import xldate_from_date_tuple, xldate_from_time_tuple, xldate_from_datetime_tuple except ImportError: error = self...
'Translate a Python datetime format string into an Excel datetime format string @param pyfmt: the Python format string'
@staticmethod def dt_format_translate(pyfmt):
translate = {'%a': 'ddd', '%A': 'dddd', '%b': 'mmm', '%B': 'mmmm', '%c': '', '%d': 'dd', '%f': '', '%H': 'hh', '%I': 'hh', '%j': '', '%m': 'mm', '%M': 'mm', '%p': 'AM/PM', '%S': 'ss', '%U': '', '%w': '', '%W': '', '%x': '', '%X': '', '%y': 'yy', '%Y': 'yyyy', '%z': '', '%Z': ''} PERCENT = '__percent__' xlfm...
'XLS encoder standard cell styles @param use_colour: use background colour in cells @param evenodd: render different background colours for even/odd rows ("stripes") @param datetime_format: the date/time format'
@classmethod def _styles(cls, use_colour=False, evenodd=True, datetime_format=None):
import xlwt if (datetime_format is None): datetime_format = cls.dt_format_translate(current.deployment_settings.get_L10n_datetime_format()) large_header = xlwt.XFStyle() large_header.font.bold = True large_header.font.height = 400 if use_colour: SOLID_PATTERN = large_header.patte...
'Constructor'
def __init__(self):
pass
'Extract the items from the resource @param resource: the resource @param list_fields: fields to include in list views'
def extractResource(self, resource, list_fields):
title = self.crud_string(resource.tablename, 'title_list') get_vars = Storage(current.request.get_vars) get_vars['iColumns'] = len(list_fields) (query, orderby, left) = resource.datatable_filter(list_fields, get_vars) resource.add_filter(query) data = resource.select(list_fields, left=left, limi...
'Export data as a Shapefile @param data_source: the source of the data that is to be encoded as a shapefile. This may be: resource: the resource item: a list of pre-fetched values the headings are in the first row the data types are in the second row @param attr: dictionary of parameters: * title: The expo...
def encode(self, data_source, **attr):
title = attr.get('title') if isinstance(data_source, (list, tuple)): headers = data_source[0] items = data_source[2:] else: current.s3db.gis_location.wkt.represent = None list_fields = attr.get('list_fields') if (not list_fields): list_fields = data_source...
'Import data from a Shapefile @param resource: the S3Resource @param source: the source @return: an S3XML ElementTree @ToDo: Handle encodings within Shapefiles other than UTF-8'
def decode(self, resource, source, **attr):
raise NotImplementedError try: from lxml import etree except ImportError: import sys print >>sys.stderr, 'ERROR: lxml module needed for XML handling' raise try: from osgeo import ogr except ImportError: import sys print >>sys....
'Page-render entry point for REST interface. @param r: the S3Request instance @param attr: controller attributes'
def apply_method(self, r, **attr):
output = {} if (r.http == 'GET'): return self.report(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) return output
'Summary widget method @param r: the S3Request @param method: the widget method @param widget_id: the widget ID @param visible: whether the widget is initially visible @param attr: controller attributes'
def widget(self, r, method=None, widget_id=None, visible=True, **attr):
output = {} if (r.http == 'GET'): r.error(501, current.ERROR.NOT_IMPLEMENTED) else: r.error(405, current.ERROR.BAD_METHOD) return output
'Report generator @param r: the S3Request instance @param attr: controller attributes'
def report(self, r, **attr):
T = current.T output = {} resource = self.resource tablename = resource.tablename get_config = resource.get_config representation = r.representation show_filter_form = False if (representation in ('html', 'iframe')): filter_widgets = get_config('filter_widgets', None) if ...
'Get the configuration for the requested report, updated with URL options'
def get_report_config(self):
r = self.request get_vars = r.get_vars config = self.resource.get_config('grouped') if (not config): r.error(405, current.ERROR.NOT_IMPLEMENTED) report = get_vars.get('report', 'default') if isinstance(report, list): report = report[(-1)] report_config = config.get(report) ...
'Get all field selectors for the report, and resolve them against the resource @param resource: the resource @param config: the report config (will be updated) @return: a dict {selector: rfield}, where rfield can be None if the selector does not resolve against the resource'
def resolve(self, report_config):
resource = self.resource fields = report_config.get('fields') if (not fields): selectors = resource.list_fields('grouped_fields') fields = list(selectors) else: selectors = list(fields) groupby = report_config.get('groupby') if isinstance(groupby, (list, tuple)): ...
'Extract the data from the resource (default method, can be overridden in report config) @param resource: the resource @param selectors: the field selectors @returns: list of dicts {colname: value} including raw data (_row)'
@staticmethod def extract(resource, selectors, orderby):
data = resource.select(selectors, limit=None, orderby=orderby, raw_data=True, represent=True) return data.rows
'Render export links for the report @param r: the S3Request'
@staticmethod def export_links(r):
T = current.T formats = DIV(DIV(_title=T('Export as PDF'), _class='gi-export export_pdf', data={'url': r.url(method='grouped', representation='pdf', vars=r.get_vars)}), DIV(_title=T('Export as XLS'), _class='gi-export export_xls', data={'url': r.url(method='grouped', representation='xls', vars...
'Inject the groupedItems script and bind it to the container @param widget_id: the widget container DOM ID @param options: dict with options for the widget @note: options dict must be JSON-serializable'
@staticmethod def inject_script(widget_id, options=None):
s3 = current.response.s3 scripts = s3.scripts appname = current.request.application if s3.debug: script = ('/%s/static/scripts/S3/s3.ui.groupeditems.js' % appname) if (script not in scripts): scripts.append(script) else: script = ('/%s/static/scripts/S3/s3.grouped...
'Constructor @param resource: the resource @param title: the report title @param data: the JSON data (as dict) @param aggregate: the aggregation functions as list of tuples (method, colname) @param field_types: the field types as dict {colname: type} @param group_headers: render group header rows @param totals_label: t...
def __init__(self, resource, title=None, data=None, aggregate=None, field_types=None, group_headers=False, totals_label=None, pdf_header=DEFAULT, pdf_footer=None):
self.resource = resource self.title = title self.data = data self.aggregate = aggregate self.field_types = field_types self.totals_label = totals_label self.group_headers = group_headers if (pdf_header is DEFAULT): self.pdf_header = self._pdf_header else: self.pdf_hea...
'Produce a HTML representation of the grouped table @return: a TABLE instance'
def html(self):
table = TABLE() self.html_render_table_header(table) tbody = TBODY() self.html_render_group(tbody, self.data) table.append(tbody) self.html_render_table_footer(table) return table
'Produce a PDF representation of the grouped table @param r: the S3Request @return: the PDF document'
def pdf(self, r, filename=None):
styles = {'tr.gi-column-totals': {'background-color': 'black', 'color': 'white'}, 'tr.gi-group-footer.gi-level-1': {'background-color': 'lightgrey'}, 'tr.gi-group-header.gi-level-1': {'background-color': 'lightgrey'}} title = self.title pdf_header = self.pdf_header if callable(pdf_header): pdf_h...
'Produce an XLS sheet of the grouped table @param r: the S3Request @return: the XLS document'
def xls(self, r, filename=None):
field_types = self.field_types data = self.data columns = data.get('c') labels = data.get('l') aggregate = self.aggregate if aggregate: functions = dict(((c, m) for (m, c) in aggregate)) else: functions = {} types = {} for column in columns: field_type = field...
'Append a group to the XLS data @param rows: the XLS rows array to append to @param group: the group dict @param level: the grouping level'
def xls_group_data(self, rows, group, level=0):
subgroups = group.get('d') items = group.get('i') if (self.group_headers and (level > 0)): self.xls_group_header(rows, group, level=level) if subgroups: for subgroup in subgroups: self.xls_group_data(rows, subgroup, level=(level + 1)) elif items: for item in items...
'Render the group header (=group label) @param row: the XLS rows array to append to @param group: the group dict @param level: the grouping level'
def xls_group_header(self, rows, group, level=0):
columns = self.data.get('c') value = group.get('v') if (not value): value = '' row = {'_group': {'label': s3_unicode(s3_strip_markup(value)), 'span': len(columns), 'totals': False}, '_style': 'subheader'} rows.append(row)
'Append a group footer to the XLS data @param rows: the XLS rows array to append to @param group: the group dict @param level: the grouping level'
def xls_group_footer(self, rows, group, level=0):
columns = self.data.get('c') totals = group.get('t') if self.group_headers: value = self.totals_label else: v = group.get('v') value = ('%s %s' % (s3_unicode(s3_strip_markup(v)), self.totals_label)) row = {} footer = {} span = 0 has_totals = False if (not t...
'Render the table footer @param table: the TABLE instance'
def xls_table_footer(self, rows):
data = self.data columns = data.get('c') totals = data.get('t') if (not totals): return row = {} if columns: label = None span = 0 for column in columns: has_value = (column in totals) if (label is None): if (not has_value):...
'Append an item to the XLS data @param rows: the XLS rows array to append to @param item: the item dict @param level: the grouping level'
def xls_item_data(self, rows, item, level=0):
columns = self.data['c'] cells = {} for column in columns: cells[column] = item.get(column) rows.append(cells)
'Render the table header @param table: the TABLE instance'
def html_render_table_header(self, table):
data = self.data columns = data.get('c') labels = data.get('l') header_row = TR(_class='gi-column-headers') if columns: for column in columns: label = labels.get(column, column) header_row.append(TH(label)) table.append(THEAD(header_row))
'Render the table footer @param table: the TABLE instance'
def html_render_table_footer(self, table):
data = self.data columns = data.get('c') totals = data.get('t') if (not totals): return footer_row = TR(_class='gi-column-totals') if columns: label = None span = 0 for column in columns: has_value = (column in totals) if (label is None): ...
'Render a group of rows @param tbody: the TBODY or TABLE to append to @param group: the group dict @param level: the grouping level'
def html_render_group(self, tbody, group, level=0):
if (self.group_headers and (level > 0)): self.html_render_group_header(tbody, group, level=level) subgroups = group.get('d') items = group.get('i') if subgroups: for subgroup in subgroups: self.html_render_group(tbody, subgroup, level=(level + 1)) elif items: for ...
'Render the group header (=group label) @param tbody: the TBODY or TABLE to append to @param group: the group dict @param level: the grouping level'
def html_render_group_header(self, tbody, group, level=0):
data = self.data columns = data.get('c') value = group.get('v') if (not value): value = '' header = TD(s3_unicode(s3_strip_markup(value)), _colspan=(len(columns) if columns else None)) tbody.append(TR(header, _class=('gi-group-header gi-level-%s' % level)))
'Render the group footer (=group totals) @param tbody: the TBODY or TABLE to append to @param group: the group dict @param level: the grouping level'
def html_render_group_footer(self, tbody, group, level=0):
columns = self.data.get('c') totals = group.get('t') if self.group_headers: value = self.totals_label else: v = group.get('v') value = ('%s %s' % (s3_unicode(s3_strip_markup(v)), self.totals_label)) footer_row = TR(_class=('gi-group-footer gi-level-%s' % level)) if ...
'Render an item @param tbody: the TBODY or TABLE to append to @param item: the item dict @param level: the grouping level'
def html_render_item(self, tbody, item, level=0):
columns = self.data['c'] cells = [] for column in columns: cells.append(TD(item.get(column, ''))) tbody.append(TR(cells, _class=('gi-item gi-level-%s' % level)))
'Default PDF header (report title as H2)'
@staticmethod def _pdf_header(r, title=None):
return H2(title)
'Constructor @param items: ordered iterable of items (e.g. list, tuple, iterator, Rows), grouping tries to maintain the original item order @param groupby: attribute key or ordered iterable of attribute keys (e.g. list, tuple, iterator) for the items to be grouped by; grouping happens in order of appearance of the keys...
def __init__(self, items, groupby=None, aggregate=None, values=None):
self._groups_dict = {} self._groups_list = [] self.values = (values or {}) self._aggregates = {} if groupby: if isinstance(groupby, basestring): groupby = [groupby] else: groupby = list(groupby) self.key = groupby.pop(0) self.groupby = groupby ...
'Generator for iteration over subgroups'
@property def groups(self):
groups = self._groups_dict for value in self._groups_list: (yield groups.get(value))
'Getter for the grouping values dict @param key: the grouping key'
def __getitem__(self, key):
if (type(key) is tuple): return self.aggregate(key[0], key[1]).result else: return self.values.get(key)
'Add a new item, either to this group or to a subgroup @param item: the item'
def add(self, item):
if self._aggregates: self._aggregates = {} key = self.key if key: raw = item.get('_row') if (raw is None): value = item.get(key) else: try: value = raw.get(key) except (AttributeError, TypeError): value = ite...
'Add an item to a subgroup. Create that subgroup if it does not yet exist. @param key: the grouping key @param value: the grouping value for the subgroup @param item: the item to add to the subgroup'
def add_to_group(self, key, value, item):
groups = self._groups_dict if (value in groups): group = groups[value] group.add(item) else: values = dict(self.values) values[key] = value group = S3GroupedItems([item], groupby=self.groupby, values=values) groups[value] = group self._groups_list.appe...
'Get a list of attribute values for the items in this group @param key: the attribute key @return: the list of values'
def get_values(self, key):
if (self.items is None): return None values = [] append = values.append extend = values.extend for item in self.items: raw = item.get('_row') if (raw is None): value = item.get(key) else: try: value = raw.get(key) ex...
'Aggregate item attribute values (recursively over subgroups) @param method: the aggregation method @param key: the attribute key @return: an S3GroupAggregate instance'
def aggregate(self, method, key):
aggregates = self._aggregates if ((method, key) in aggregates): return aggregates[(method, key)] if (self.items is not None): values = self.get_values(key) aggregate = S3GroupAggregate(method, key, values) else: combine = S3GroupAggregate.aggregate aggregate = com...
'Represent this group and all its subgroups as string'
def __repr__(self):
return self.__represent()
'Represent this group and all its subgroups as string @param level: the hierarchy level of this group (for indentation)'
def __represent(self, level=0):
output = '' indent = (' ' * level) aggregates = self._aggregates for aggregate in aggregates.values(): output = ('%s\n%s %s(%s) = %s' % (output, indent, aggregate.method, aggregate.key, aggregate.result)) if aggregates: output = ('%s\n' % output) key = self.key ...
'Serialize this group as JSON @param fields: the columns to include for each item @param labels: columns labels as dict {key: label}, including the labels for grouping axes @param represent: dict of representation methods for grouping axis values {colname: function} @param as_dict: return output as dict rather than JSO...
def json(self, fields=None, labels=None, represent=None, as_dict=False, master=True):
T = current.T output = {} if (not fields): raise SyntaxError if master: if (labels is None): labels = {} def check_label(colname): if (colname in labels): label = (labels[colname] or '') else: fname = colname.spl...
'Constructor @param method: the aggregation method (count, sum, min, max, avg) @param key: the attribute key @param values: the attribute values'
def __init__(self, method, key, values):
self.method = method self.key = key self.values = values self.result = self.__compute(method, values)
'Compute the aggregated value @param method: the aggregation method @param values: the values @return: the aggregated value'
def __compute(self, method, values):
result = None if (values is not None): try: values = [v for v in values if (v is not None)] except TypeError: result = None else: if (method == 'count'): result = len(set(values)) else: values = [v for v in v...
'Combine sub-aggregates @param items: iterable of sub-aggregates @return: an S3GroupAggregate instance'
@classmethod def aggregate(cls, items):
method = None key = None values = [] for item in items: if (method is None): method = item.method key = item.key elif ((key != item.key) or (method != item.method)): raise TypeError if item.values: values.extend(item.values) ret...
'Return a list of language codes'
@staticmethod def get_langcodes():
lang_list = [] langdir = os.path.join(current.request.folder, 'languages') files = os.listdir(langdir) for f in files: lang_list.append(f[:(-3)]) return lang_list
'Return a list of modules'
def get_modules(self):
return self.grp.modlist
'Return a list of strings corresponding to a module'
def get_strings_by_module(self, module):
grp = self.grp d = grp.d if (module in d.keys()): fileList = d[module] else: current.log.warning(("Module '%s' doesn't exist!" % module)) return [] modlist = grp.modlist strings = [] sappend = strings.append R = TranslateReadFiles() findstr = R.findst...
'Return a list of strings in a given file'
def get_strings_by_file(self, filename):
if os.path.isfile(filename): filename = os.path.abspath(filename) else: print ("'%s' is not a valid file path!" % filename) return [] R = TranslateReadFiles() strings = [] sappend = strings.append tmpstr = [] if (filename.endswith('.py') == True): ...
'Set up a dictionary to hold files belonging to a particular module with the module name as the key. Files which contain strings belonging to more than one module are grouped under the "special" key.'
def __init__(self):
d = {} modlist = self.get_module_list(current.request.folder) for m in modlist: d[m] = [] d['core'] = [] d['special'] = [] self.d = d self.modlist = modlist
'Returns a list of modules using files in /controllers/ as point of reference'
@staticmethod def get_module_list(dir):
mod = [] mappend = mod.append cont_dir = os.path.join(dir, 'controllers') mod_files = os.listdir(cont_dir) for f in mod_files: if (f[0] != '.'): mappend(f[:(-3)]) mod += ['support', 'translate'] return mod
'Recursive function to group Eden files into respective modules'
def group_files(self, currentDir, curmod='', vflag=0):
path = os.path currentDir = path.abspath(currentDir) base_dir = path.basename(currentDir) if (base_dir in ('.git', 'docs', 'languages', 'private', 'templates', 'tests', 'uploads')): return if (base_dir == 'views'): vflag = 1 d = self.d files = os.listdir(currentDir) for f...
'Initializes all object variables'
def __init__(self):
self.cflag = 0 self.fflag = 0 self.sflag = 0 self.tflag = 0 self.mflag = 0 self.bracket = 0 self.outstr = '' self.class_name = '' self.func_name = '' self.mod_name = '' self.findent = (-1)
'Recursive function to extract strings from a parse tree'
def parseList(self, entry, tmpstr):
if isinstance(entry, list): id = entry[0] value = entry[1] if isinstance(value, list): parseList = self.parseList for element in entry: parseList(element, tmpstr) elif (token.tok_name[id] == 'STRING'): tmpstr.append(value)
'Function to extract strings from config.py / 000_config.py'
def parseConfig(self, spmod, strings, entry, modlist):
if isinstance(entry, list): id = entry[0] value = entry[1] if isinstance(value, list): parseConfig = self.parseConfig for element in entry: parseConfig(spmod, strings, element, modlist) elif ((self.fflag == 1) and (token.tok_name[id] == 'NAME')...
'Function to extract the strings from s3cfg.py'
def parseS3cfg(self, spmod, strings, entry, modlist):
if isinstance(entry, list): id = entry[0] value = entry[1] if isinstance(value, list): parseS3cfg = self.parseS3cfg for element in entry: parseS3cfg(spmod, strings, element, modlist) elif (self.fflag == 1): self.func_name = value ...
'Function to extract the strings from menus.py'
def parseMenu(self, spmod, strings, entry, level):
if isinstance(entry, list): id = entry[0] value = entry[1] if isinstance(value, list): parseMenu = self.parseMenu for element in entry: parseMenu(spmod, strings, element, (level + 1)) elif (self.cflag == 1): self.class_name = value ...
'Function to extract all the strings from a file'
def parseAll(self, strings, entry):
if isinstance(entry, list): id = entry[0] value = entry[1] if isinstance(value, list): parseAll = self.parseAll for element in entry: parseAll(strings, element) elif ((token.tok_name[id] == 'NAME') and (value == 'T')): self.sflag = ...
'Using the methods in TranslateParseFiles to extract the strings fileName -> the file to be used for extraction spmod -> the required module modlist -> a list of all modules in Eden'
@staticmethod def findstr(fileName, spmod, modlist):
try: f = open(fileName) except: path = os.path.split(__file__)[0] fileName = os.path.join(path, fileName) try: f = open(fileName) except: return fileContent = f.read() f.close() fileContent = ('%s\n' % fileContent.replace('\r', '')) ...
'Function to read and extract strings from html/js files using regular expressions'
@staticmethod def read_html_js(filename):
import re PY_STRING_LITERAL_RE = (((('(?<=[^\\w]T\\()(?P<name>' + "[uU]?[rR]?(?:'''(?:[^']|'{1,2}(?!'))*''')|") + "(?:'(?:[^'\\\\]|\\\\.)*')|") + '(?:"""(?:[^"]|"{1,2}(?!"))*""")|') + '(?:"(?:[^"\\\\]|\\\\.)*"))') regex_trans = re.compile(PY_STRING_LITERAL_RE, re.DOTALL) findall = regex_trans.findall ...
'Function to return the list of user-supplied strings'
@staticmethod def get_user_strings():
user_file = os.path.join(current.request.folder, 'uploads', 'user_strings.txt') strings = [] COMMENT = 'User supplied' if os.path.exists(user_file): f = open(user_file, 'r') for line in f: line = line.replace('\n', '').replace('\r', '') strings.append((COMMENT,...
'Function to merge the existing file of user-supplied strings with newly uploaded strings'
@staticmethod def merge_user_strings_file(newstrings):
user_file = os.path.join(current.request.folder, 'uploads', 'user_strings.txt') oldstrings = [] oappend = oldstrings.append if os.path.exists(user_file): f = open(user_file, 'r') for line in f: oappend(line) f.close() f = open(user_file, 'a') for s in newstrin...
'Function to get database strings from csv files which are to be considered for translation.'
@staticmethod def get_database_strings(all_template_flag):
from s3import import S3BulkImporter database_strings = [] dappend = database_strings.append template_list = [] base_dir = current.request.folder path = os.path if all_template_flag: template_dir = path.join(base_dir, 'modules', 'templates') files = os.listdir(template_dir) ...
'Function to remove single or double quotes around the strings'
@staticmethod def remove_quotes(Strings):
l = [] lappend = l.append for (d1, d2) in Strings: if (((d1[0] == '"') and (d1[(-1)] == '"')) or ((d1[0] == "'") and (d1[(-1)] == "'"))): d1 = d1[1:(-1)] if (((d2[0] == '"') and (d2[(-1)] == '"')) or ((d2[0] == "'") and (d2[(-1)] == "'"))): d2 = d2[1:(-1)] lap...
'Function to club all the duplicate strings into one row with ";" separated locations'
@staticmethod def remove_duplicates(Strings):
uniq = {} appname = current.request.application for (loc, data) in Strings: uniq[data] = '' for (loc, data) in Strings: loc = loc.split(appname, 1)[1] if (uniq[data] != ''): uniq[data] = ((uniq[data] + ';') + loc) else: uniq[data] = loc l = [] ...
'Function to remove all untranslated strings from a lang_code.py'
@staticmethod def remove_untranslated(lang_code):
w2pfilename = os.path.join(current.request.folder, 'languages', ('%s.py' % lang_code)) data = read_dict(w2pfilename) newdata = {} for (k, v) in data.iteritems(): if (k != v): new_data[k] = v data = new_data write_dict(w2pfilename, data)
'Function to get the strings by module(s)/file(s), merge with those strings from existing w2p language file which are already translated and call the "write_xls()" method if the default filetype "xls" is chosen. If "po" is chosen, then the write_po()" method is called.'
def export_file(self, langfile, modlist, filelist, filetype, all_template_flag):
request = current.request settings = current.deployment_settings appname = request.application folder = request.folder join = os.path.join langcode = langfile[:(-3)] langfile = join(folder, 'languages', langfile) if (not os.path.exists(langfile)): f = open(langfile, 'w') ...
'Function to read a CSV file and return a list of rows'
@staticmethod def read_csv(fileName):
import csv csv.field_size_limit((2 ** 20)) data = [] dappend = data.append f = open(fileName, 'rb') transReader = csv.reader(f) for row in transReader: dappend(row) f.close() return data
'Function to read a web2py language file and return a list of translation string pairs'
@staticmethod def read_w2p(fileName):
data = read_dict(fileName) strings = [] sappend = strings.append for s in data: sappend((s, data[s])) return strings
'Function to write a list of rows into a csv file'
@staticmethod def write_csv(fileName, data):
import csv f = open(fileName, 'wb') transWriter = csv.writer(f, delimiter=' ', quotechar='"', quoting=csv.QUOTE_ALL) transWriter.writerow(('location', 'source', 'target')) for row in data: transWriter.writerow(row) f.close()
'Returns a ".po" file constructed from given strings'
def write_po(self, data):
from subprocess import call from tempfile import NamedTemporaryFile from gluon.contenttype import contenttype f = NamedTemporaryFile(delete=False) csvfilename = ('%s.csv' % f.name) self.write_csv(csvfilename, data) g = NamedTemporaryFile(delete=False) pofilename = ('%s.po' % g.name) ...
'Function to merge multiple translated csv files into one and then merge/overwrite the existing w2p language file'
def write_w2p(self, csvfiles, lang_code, option):
w2pfilename = os.path.join(current.request.folder, 'languages', ('%s.py' % lang_code)) data = {} errors = 0 for f in csvfiles: newdata = self.read_csv(f) cols = len(newdata[0]) if (cols == 1): raise SyntaxError('CSV file needs to have at least 2 ...
'Function to create a spreadsheet (.xls file) of strings with location, original string and translated string as columns'
@staticmethod def write_xls(Strings, langcode):
try: from cStringIO import StringIO except: from StringIO import StringIO import xlwt from gluon.contenttype import contenttype wbk = xlwt.Workbook('utf-8') sheet = wbk.add_sheet('Translate') style = xlwt.XFStyle() font = xlwt.Font() font.name = 'Times New Roman...
'Upload a file to Pootle'
def upload(self, lang_code, filename):
import mechanize import re br = mechanize.Browser() br.addheaders = [('User-agent', 'Firefox')] br.set_handle_equiv(False) br.set_handle_robots(False) br.set_handle_referer(False) settings = current.deployment_settings username = settings.get_L10n_pootle_username() if (username i...
'Download a file from Pootle @ToDo: Allow selection between different variants of language files'
def download(self, lang_code):
import requests import zipfile try: from cStringIO import StringIO except: from StringIO import StringIO from subprocess import call from tempfile import NamedTemporaryFile code = lang_code if (len(lang_code) > 2): code = ('%s_%s' % (lang_code[:2], lang_code[(-2):...
'Merge strings from a PO file and a Py file'
def merge_strings(self, postrings, pystrings, preference):
lim_po = len(postrings) lim_py = len(pystrings) i = 0 j = 0 extra = [] eappend = extra.append while ((i < lim_py) and (j < lim_po)): if (pystrings[i][0] < postrings[j][0]): if (preference == False): eappend(pystrings[i]) i += 1 elif (py...
'Create master file of strings and their distribution in modules'
@classmethod def create_master_file(cls):
try: import cPickle as pickle except: import pickle api = TranslateAPI() modules = api.get_modules() modules.append('core') all_strings = [] addstring = all_strings.append indices = {} string_indices = {} index = 0 get_strings_by_module = api.get_strings_by_mo...
'Update the translation percentages for all modules for a given language. @ToDo: Generate fresh .py files with all relevant strings for this (since we don\'t store untranslated strings)'
@classmethod def update_string_counts(cls, lang_code):
try: import cPickle as pickle except: import pickle base_dir = current.request.folder langfile = ('%s.py' % lang_code) langfile = os.path.join(base_dir, 'languages', langfile) lang_strings = read_dict(langfile) data_file = os.path.join(base_dir, 'uploads', 'temp.pkl') f =...
'Get the percentages of translated strings per module for the given language code. @param lang_code: the language code'
@classmethod def get_translation_percentages(cls, lang_code):
pickle_file = os.path.join(current.request.folder, 'uploads', 'temp.pkl') if (not os.path.exists(pickle_file)): cls.create_master_file() db = current.db ptable = current.s3db.translate_percentage query = (ptable.code == lang_code) fields = ('dirty', 'translated', 'untranslated', 'module'...
'Constructor @param r: the request object (defaults to current.request) @param dashboard: the dashboard (S3Dashboard)'
def __init__(self, r=None, dashboard=None):
self.dashboard = dashboard self.shared = {} self.filters = {} self._parse()
'Action upon error @param status: HTTP status code @param message: the error message @param _next: destination URL for redirection upon error (defaults to the index page of the module)'
def error(self, status, message, _next=None):
if (self.representation == 'html'): current.session.error = message if (_next is None): _next = URL(f='index') redirect(_next) else: current.log.error(message) if (self.representation == 'popup'): headers = {} body = DIV(message, _style...
'Called upon context.<key> - looks up the value for the <key> attribute. Falls back to current.request if the attribute is not defined in this context. @param key: the key to lookup'
def __getattr__(self, key):
if (key in self.__dict__): return self.__dict__[key] sentinel = object() value = getattr(current.request, key, sentinel) if (value is sentinel): raise AttributeError return value
'Parse the request info @param r: the web2py Request, falls back to current.request'
def _parse(self, r=None):
request = (current.request if (r is None) else r) args = request.args get_vars = request.get_vars command = None if (len(args) > 0): command = args[0] if ('.' in command): command = command.split('.', 1)[0] if command: self.command = command bulk = get_var...
'Constructor @param layout: the layout, or the config dict @param widgets: the available widgets as dict {name: widget} @param default: the default configuration (=list of widget configs) @param configurable: whether this dashboard is user-configurable'
def __init__(self, layout, widgets=None, default=None, configurable=False):
if isinstance(layout, dict): config = layout title = config.get('title', current.T('Dashboard')) layout = config.get('layout') widgets = config.get('widgets', widgets) default = config.get('default', default) configurable = config.get('configurable', configurable) ...
'Load the current active configuration for the context @param context: the current S3DashboardContext'
def load(self, context):
if (not self.configurable): return table = current.s3db.s3_dashboard query = ((((table.controller == context.controller) & (table.function == context.function)) & (table.active == True)) & (table.deleted != True)) row = current.db(query).select(table.id, table.layout, table.title, table.version,...
'Save this configuration in the database @param context: the current S3DashboardContext @param update: widget configurations to update, as dict {widget_id: {config-dict}} @return: the new version key, or None if not successful'
def save(self, context, update=None):
if ((not self.configurable) or (not self.loaded)): return None db = current.db table = current.s3db.s3_dashboard widgets = self.active_widgets configs = [] for widget in widgets: widget_id = widget.get('widget_id') new_config = update.get(widget_id) if new_config:...